FIX: white-space: pre-wrap prevents collapsing spaces in document-text-element
[fnpeditor.git] / modules / documentCanvas / canvas / canvas.js
1 define([
2 'libs/jquery-1.9.1.min',
3 'libs/underscore-min',
4 'libs/backbone-min',
5 'modules/documentCanvas/canvas/documentElement',
6 'modules/documentCanvas/canvas/utils'
7 ], function($, _, Backbone, documentElement, utils) {
8     
9 'use strict';
10
11 var Canvas = function(wlxml, publisher) {
12     this.eventBus = _.extend({}, Backbone.Events);
13     this.loadWlxml(wlxml);
14     this.publisher = publisher ? publisher : function() {};
15 };
16
17 $.extend(Canvas.prototype, {
18
19     loadWlxml: function(wlxml) {
20         var d = wlxml ? $($.trim(wlxml)) : null;
21         if(d) {
22             this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
23             this.wrapper.append(d);
24             var canvas = this;
25
26             this.wrapper.find('*').replaceWith(function() {
27                 var currentTag = $(this);
28                 if(currentTag.attr('wlxml-tag'))
29                     return;
30
31                 var meta = {}, others = {};
32                 for(var i = 0; i < this.attributes.length; i++) {
33                     var attr = this.attributes[i];
34                     if(attr.name.substr(0, 5) === 'meta-')
35                         meta[attr.name.substr(5)] = attr.value;
36                     else if(attr.name !== 'class')
37                         others[attr.name] = attr.value;
38                 }
39
40                 var element = documentElement.DocumentNodeElement.create({
41                     tag: currentTag.prop('tagName').toLowerCase(),
42                     klass: currentTag.attr('class'),
43                     meta: meta,
44                     others: others,
45                     rawChildren: currentTag.contents()
46                 }, canvas);
47
48                 ['orig-before', 'orig-after', 'orig-begin', 'orig-end'].forEach(function(attr) {
49                     element.data(attr, '');
50                 });
51                 return element.dom();
52             });
53
54             var FIRST_CONTENT_INDEX = 0;
55
56             // @@ TODO - refactor!
57             var getNode = function(element) {
58                 return element.children('[document-element-content]');
59             }
60
61             this.wrapper.find(':not(iframe)').addBack().contents()
62                 .filter(function() {return this.nodeType === Node.TEXT_NODE})
63                 .each(function() {
64
65                     // TODO: use DocumentElement API
66
67                     var el = $(this),
68                         text = {original: el.text(), trimmed: $.trim(el.text())},
69                         elParent = el.parent(),
70                         hasSpanParent = elParent.attr('wlxml-tag') === 'span',
71                         hasSpanBefore = el.prev().length > 0  && getNode($(el.prev()[0])).attr('wlxml-tag') === 'span',
72                         hasSpanAfter = el.next().length > 0 && getNode($(el.next()[0])).attr('wlxml-tag') === 'span';
73
74                     if(el.parent().hasClass('canvas-widget'))
75                         return true; // continue
76
77                     var addInfo = function(toAdd, where) {
78                         var parentContents = elParent.contents(),
79                             idx = parentContents.index(el[0]),
80                             prev = idx > FIRST_CONTENT_INDEX ? parentContents[idx-1] : null,
81                             next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
82                             target, key;
83
84                         if(where === 'above') {
85                             target = prev ? $(prev) : elParent.parent();
86                             key = prev ? 'orig-after' : 'orig-begin';
87                         } else if(where === 'below') {
88                             target = next ? $(next) : elParent.parent();
89                             key = next ? 'orig-before' : 'orig-end';
90                         } else { throw new Object;}
91
92                         target.data(key, toAdd);
93                     }
94
95                     text.transformed = text.trimmed;
96                     
97                     if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
98                         var startSpace = /\s/g.test(text.original.substr(0,1)),
99                             endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
100                         text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '')
101                                     + text.trimmed
102                                     + (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
103                     } else {
104                         if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1)
105                             text.transformed = ' ';
106                     }
107
108                     if(!text.transformed) {
109                         addInfo(text.original, 'below');
110                         el.remove();
111                         return true; // continue
112                     }
113
114                     if(text.transformed !== text.original) {
115                         if(!text.trimmed) {
116                             addInfo(text.original, 'below');
117                         } else {
118                             var startingMatch = text.original.match(/^\s+/g),
119                                 endingMatch = text.original.match(/\s+$/g),
120                                 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
121                                 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
122
123                             if(endingWhiteSpace) {
124                                 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ')
125                                     endingWhiteSpace = endingWhiteSpace.substr(1);
126                                 addInfo(endingWhiteSpace, 'below');
127                             }
128
129                             if(startingWhiteSpace) {
130                                 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ')
131                                     startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
132                                 addInfo(startingWhiteSpace, 'above');
133                             }
134                         }
135                     }
136
137                     var element = documentElement.DocumentTextElement.create({text: text.transformed});
138                     el.replaceWith(element.dom());
139                 });
140             
141             this.d = this.wrapper.children(0);
142
143             this.wrapper.on('keydown', function(e) {
144                 if(e.which === 13) { 
145                     e.preventDefault();
146                     var cursor = canvas.getCursor();
147                     if(!cursor.isSelecting()) {
148                         var position = cursor.getPosition(),
149                             element = position.element;
150
151                         if(!(element.parent().parent())) {
152                             return false; // top level element is unsplittable
153                         }
154
155                         var elements = position.element.split({offset: position.offset}),
156                             newEmpty,
157                             goto;
158
159                         if(position.offsetAtBeginning)
160                             newEmpty = elements.first;
161                         else if(position.offsetAtEnd)
162                             newEmpty = elements.second;
163                         if(newEmpty) {
164                             goto = newEmpty.append(documentElement.DocumentTextElement.create({text: ''}, this));
165                             canvas.setCurrentElement(goto);
166                         }
167                     }
168                 }
169             });
170
171
172             var KEYS = {
173                 ARROW_LEFT: 37,
174                 ARROW_UP: 38,
175                 ARROW_RIGHT: 39,
176                 ARROW_DOWN: 40,
177                 BACKSPACE: 8,
178                 DELETE: 46,
179                 X: 88
180             }
181
182             this.wrapper.on('keyup', function(e) {
183                 if(e.which >= 37 && e.which <= 40) {
184                     var element = canvas.getCursor().getPosition().element,
185                         caretTo = false;
186                     if(!element) {
187                         // Chrome hack
188                         var direction;
189                         if(e.which === KEYS.ARROW_LEFT  || e.which === KEYS.ARROW_UP) {
190                             direction = 'above';
191                             caretTo = 'end';
192                         } else {
193                             direction = 'below';
194                             caretTo = 'start';
195                         }
196                         element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', direction, window.getSelection().focusNode));
197                     }
198                     canvas.setCurrentElement(element, {caretTo: caretTo});
199                 }
200             });
201          
202             this.wrapper.on('keydown', function(e) {
203                 var cursor = canvas.getCursor(),
204                     position = canvas.getCursor().getPosition(),
205                     element = position.element;
206                 if(e.which >= 37 && e.which <= 40) {
207
208                     if(element && (element instanceof documentElement.DocumentTextElement)) {
209                         if(element.isEmpty()) {
210                             var direction, caretTo;
211                             if(e.which === KEYS.ARROW_LEFT  || e.which === KEYS.ARROW_UP) {
212                                 direction = 'above';
213                                 caretTo = 'end';
214                             } else {
215                                 direction = 'below';
216                                 caretTo = 'start';
217                             }
218                             var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, window.getSelection().focusNode))
219                             canvas.setCurrentElement(element, {caretTo: caretTo});
220                         } else {
221                             var txt = element.dom().contents()[0].data;
222                             if(e.which === KEYS.ARROW_LEFT && position.offset > 1 && txt.charAt(position.offset-2) === utils.unicode.ZWS) {
223                                 e.preventDefault();
224                                 canvas._moveCaretToTextElement(element, position.offset-2);
225                             }
226                             if(e.which === KEYS.ARROW_RIGHT && position.offset < txt.length - 1 && txt.charAt(position.offset+1) === utils.unicode.ZWS) {
227                                 e.preventDefault();
228                                 canvas._moveCaretToTextElement(element, position.offset+2);
229                             }
230                         }
231                     }
232
233
234                 }
235
236                 var selectsWholeTextElement = function() {
237                     if(cursor.isSelecting() && cursor.getSelectionStart().offsetAtBeginning && cursor.getSelectionEnd().offsetAtEnd)
238                         return true;
239                     return false;
240                 }
241
242                 if(e.which === KEYS.X && e.ctrlKey && selectsWholeTextElement()) {
243                     e.preventDefault();
244                 }
245
246                 if(e.which === KEYS.BACKSPACE || e.which === KEYS.DELETE) {
247                     if(cursor.isSelecting() && !cursor.isSelectingWithinElement()) {
248                         e.preventDefault();
249                         return;
250                     }
251                         
252                     var cursorAtOperationEdge = position.offsetAtBeginning;
253                     if(e.which === KEYS.DELETE) {
254                         cursorAtOperationEdge = position.offsetAtEnd;
255                     }
256
257                     if(element.getText().length === 1 || selectsWholeTextElement()) {
258                         e.preventDefault();
259                         element.setText('');
260                     }
261                     else if(element.isEmpty()) {
262
263                         var direction = 'above',
264                             caretTo = 'end';
265                             
266                         if(e.which === KEYS.DELETE) {
267                             direction = 'below';
268                             caretTo = 'start';
269                         }
270
271                         e.preventDefault();
272
273                         var parent = element.parent(),
274                             grandParent = parent ? parent.parent() : null,
275                             goto;
276                         if(parent.children().length === 1) {
277                             if(grandParent && grandParent.children().length === 1) {
278                                 goto = grandParent.append({text: ''});
279                             } else {
280                                 goto = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, element.dom()[0]));
281                             }
282                             parent.detach();
283                         } else {
284                             goto = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, element.dom()[0]));
285                             element.detach();
286                         }
287                         canvas.setCurrentElement(goto, {caretTo: caretTo});
288                     }
289                     else if(cursorAtOperationEdge) {
290                         // todo
291                         e.preventDefault();
292                     }
293                 }
294             });
295
296             this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
297                 e.stopPropagation();
298                 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
299             });
300
301             var observer = new MutationObserver(function(mutations) {
302                 mutations.forEach(function(mutation) {
303                     if(documentElement.DocumentTextElement.isContentContainer(mutation.target) && mutation.target.data === '')
304                         mutation.target.data = utils.unicode.ZWS;
305                 });
306             });
307             var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
308             observer.observe(this.d[0], config);
309
310
311             this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
312                 var el = canvas.getDocumentElement(e.currentTarget);
313                 if(!el)
314                     return;
315                 e.stopPropagation();
316                 if(el instanceof documentElement.DocumentTextElement)
317                     el = el.parent();
318                 el.toggleLabel(true);
319             });
320             this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
321                 var el = canvas.getDocumentElement(e.currentTarget);
322                 if(!el)
323                     return;
324                 e.stopPropagation();
325                 if(el instanceof documentElement.DocumentTextElement)
326                     el = el.parent();
327                 el.toggleLabel(false);
328             });
329
330             this.eventBus.on('elementToggled', function(toggle, element) {
331                 if(!toggle) {
332                     element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', 'above', element.dom()[0]));
333                     canvas.setCurrentElement(element);
334                 }
335             })
336
337         } else {
338             this.d = null;
339         }
340     },
341
342     view: function() {
343         return this.wrapper;
344     },
345
346     doc: function() {
347         if(this.d === null)
348             return null;
349         return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
350     },
351
352     wrapText: function(params) {
353         params = _.extend({textNodeIdx: 0}, params);
354         if(typeof params.textNodeIdx === 'number')
355             params.textNodeIdx = [params.textNodeIdx];
356         
357         var childrenInside = params.inside.children(),
358             idx1 = Math.min.apply(Math, params.textNodeIdx),
359             idx2 = Math.max.apply(Math, params.textNodeIdx),
360             textNode1 = childrenInside[idx1],
361             textNode2 = childrenInside[idx2],
362             sameNode = textNode1.sameNode(textNode2),
363             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
364             prefixInside = textNode1.getText().substr(params.offsetStart),
365             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
366             suffixOutside = textNode2.getText().substr(params.offsetEnd)
367         ;
368         
369         var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
370         textNode1.after(wrapperElement);
371         textNode1.detach();
372         
373         if(prefixOutside.length > 0)
374             wrapperElement.before({text:prefixOutside});
375         if(sameNode) {
376             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
377             wrapperElement.append({text: core});
378         } else {
379             textNode2.detach();
380             if(prefixInside.length > 0)
381                 wrapperElement.append({text: prefixInside});
382             for(var i = idx1 + 1; i < idx2; i++) {
383                 wrapperElement.append(childrenInside[i]);
384             }
385             if(suffixInside.length > 0)
386                 wrapperElement.append({text: suffixInside});
387         }
388         if(suffixOutside.length > 0)
389             wrapperElement.after({text: suffixOutside});
390         return wrapperElement;
391     },
392
393     wrapElements: function(params) {
394         if(!(params.element1.parent().sameNode(params.element2.parent())))
395             return;
396
397         var parent = params.element1.parent(),
398             parentChildren = parent.children(),
399             wrapper = documentElement.DocumentNodeElement.create({
400                 tag: params._with.tag,
401                 klass: params._with.klass}),
402             idx1 = parent.childIndex(params.element1),
403             idx2 = parent.childIndex(params.element2);
404
405         if(idx1 > idx2) {
406             var tmp = idx1;
407             idx1 = idx2;
408             idx2 = tmp;
409         }
410
411         var insertingMethod, insertingTarget;
412         if(idx1 === 0) {
413             insertingMethod = 'prepend';
414             insertingTarget = parent;
415         } else {
416             insertingMethod = 'after';
417             insertingTarget = parentChildren[idx1-1];
418         }
419
420         for(var i = idx1; i <= idx2; i++) {
421             wrapper.append(parentChildren[i].detach());
422         }
423
424         insertingTarget[insertingMethod](wrapper);
425         return wrapper;
426     },
427
428     getSiblingParents: function(params) {
429         var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
430             parents2 = [params.element2].concat(params.element2.parents()).reverse(),
431             noSiblingParents = null;
432
433         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
434             return noSiblingParents;
435
436         var i;
437         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
438             if(parents1[i].sameNode(parents2[i]))
439                 continue;
440             break;
441         }
442         return {element1: parents1[i], element2: parents2[i]};
443     },
444
445     getDocumentElement: function(from) {
446         if(from instanceof HTMLElement || from instanceof Text) {
447            return documentElement.DocumentElement.fromHTMLElement(from, this);
448         }
449     },
450     getCursor: function() {
451         return new Cursor(this);
452     },
453
454     list: {},
455
456     
457     getCurrentNodeElement: function() {
458         return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
459     },
460
461     getCurrentTextElement: function() {
462         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
463     },
464
465
466
467     setCurrentElement: function(element, params) {
468         params = _.extend({caretTo: 'end'}, params);
469         var findFirstDirectTextChild = function(e, nodeToLand) {
470             var byBrowser = this.getCursor().getPosition().element;
471             if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
472                 return byBrowser;
473             var children = e.children();
474             for(var i = 0; i < children.length; i++) {
475                 if(children[i] instanceof documentElement.DocumentTextElement)
476                     return children[i];
477             }
478             return null;
479         }.bind(this);
480         var _markAsCurrent = function(element) {
481             if(element instanceof documentElement.DocumentTextElement) {
482                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
483                 element.dom().addClass('current-text-element');
484             } else {
485                 this.wrapper.find('.current-node-element').removeClass('current-node-element')
486                 element._container().addClass('current-node-element');
487                 this.publisher('currentElementChanged', element);
488             }
489         }.bind(this);
490
491
492         var isTextElement = element instanceof documentElement.DocumentTextElement,
493             nodeElementToLand = isTextElement ? element.parent() : element,
494             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
495             currentTextElement = this.getCurrentTextElement(),
496             currentNodeElement = this.getCurrentNodeElement();
497
498         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
499             this.wrapper.find('.current-text-element').removeClass('current-text-element');
500
501         if(textElementToLand) {
502             _markAsCurrent(textElementToLand);
503             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
504                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
505             if(!(textElementToLand.sameNode(currentTextElement)))
506                 this.publisher('currentTextElementSet', textElementToLand);
507         } else {
508             document.getSelection().removeAllRanges();
509         }
510
511         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
512             _markAsCurrent(nodeElementToLand);
513
514             this.publisher('currentNodeElementSet', nodeElementToLand);
515         }
516     },
517
518     _moveCaretToTextElement: function(element, where) {
519         var range = document.createRange(),
520             node = element.dom().contents()[0];
521
522         if(typeof where !== 'number') {
523             range.selectNodeContents(node);
524         } else {
525             range.setStart(node, where);
526         }
527         
528         var collapseArg = true;
529         if(where === 'end')
530             collapseArg = false;
531         range.collapse(collapseArg);
532         
533         var selection = document.getSelection();
534
535         selection.removeAllRanges();
536         selection.addRange(range);
537         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
538     },
539
540     setCursorPosition: function(position) {
541         if(position.element)
542             this._moveCaretToTextElement(position.element, position.offset);
543     },
544
545     toXML: function() {
546         var parent = $('<div>'),
547             parts = this.doc().toXML(0);
548         parent.append(parts);
549         return parent.html();
550     }
551 });
552
553 $.extend(Canvas.prototype.list, {
554     create: function(params) {
555         if(!(params.element1.parent().sameNode(params.element2.parent())))
556             return false;
557             
558         var parent = params.element1.parent();
559         
560         if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
561             var tmp = params.element1;
562             params.element1 = params.element2;
563             params.element2 = tmp;
564         }
565         
566         var elementsToWrap = [];
567         
568         var place = 'before';
569         var canvas = this;
570         parent.children().some(function(element) {
571             var _e = element;
572             if(element.sameNode(params.element1))
573                 place = 'inside';
574             if(place === 'inside') {
575                 if(element instanceof documentElement.DocumentTextElement) {
576                     element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
577                     if(element.children()[0].sameNode(params.element1))
578                         params.element1 = element;
579                 }
580                 element.setWlxmlClass('item');
581                 elementsToWrap.push(element);
582             }
583             if(_e.sameNode(params.element2))
584                 return true;
585         });
586         
587         var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
588         
589         var toret;
590         if(parent.is('list')) {
591             listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
592             toret = listElement.parent();
593         } else {
594             toret = listElement;
595         }  
596         
597         params.element1.before(toret);
598         
599         elementsToWrap.forEach(function(element) {
600             element.detach();
601             listElement.append(element);
602         });
603     },
604     extractItems: function(params) {
605         params = _.extend({merge: true}, params);
606         var list = params.element1.parent();
607         if(!list.is('list') || !(list.sameNode(params.element2.parent())))
608             return false;
609
610         var idx1 = list.childIndex(params.element1),
611             idx2 = list.childIndex(params.element2),
612             precedingItems = [],
613             extractedItems = [],
614             succeedingItems = [],
615             items = list.children(),
616             listIsNested = list.parent().getWlxmlClass() === 'item',
617             i;
618
619         if(idx1 > idx2) {
620             var tmp = idx1; idx1 = idx2; idx2 = tmp;
621         }
622
623         items.forEach(function(item, idx) {
624             if(idx < idx1)
625                 precedingItems.push(item);
626             else if(idx >= idx1 && idx <= idx2) {
627                 extractedItems.push(item);
628             }
629             else {
630                 succeedingItems.push(item);
631             }
632         });
633
634         var reference = listIsNested ? list.parent() : list;
635         if(succeedingItems.length === 0) {
636             var reference_orig = reference;
637             extractedItems.forEach(function(item) {
638                 reference.after(item);
639                 reference = item;
640                 if(!listIsNested)
641                     item.setWlxmlClass(null);
642             });
643             if(precedingItems.length === 0)
644                 reference_orig.detach();
645         } else if(precedingItems.length === 0) {
646             extractedItems.forEach(function(item) {
647                 reference.before(item);
648                 if(!listIsNested)
649                     item.setWlxmlClass(null);
650             });
651         } else {
652             extractedItems.forEach(function(item) {
653                 reference.after(item);
654                 if(!listIsNested)
655                     item.setWlxmlClass(null);
656                 reference = item;
657             });
658             var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
659                 toAdd = secondList;
660             
661             if(listIsNested) {
662                 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
663             }
664             succeedingItems.forEach(function(item) {
665                 secondList.append(item);
666             });
667
668             reference.after(toAdd);
669         }
670         if(!params.merge && listIsNested) {
671             return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
672         }
673         return true;
674     },
675     areItemsOfTheSameList: function(params) {
676         var e1 = params.element1,
677             e2 = params.element2;
678         return e1.parent().sameNode(e2.parent())
679             && e1.parent().is('list');
680     }
681 });
682
683
684 var Cursor = function(canvas) {
685     this.canvas = canvas;
686 };
687
688 $.extend(Cursor.prototype, {
689     isSelecting: function() {
690         var selection = window.getSelection();
691         return !selection.isCollapsed;
692     },
693     isSelectingWithinElement: function() {
694         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
695     },
696     isSelectingSiblings: function() {
697         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
698     },
699     getPosition: function() {
700         return this.getSelectionAnchor();
701     },
702     getSelectionStart: function() {
703         return this.getSelectionBoundry('start');
704     },
705     getSelectionEnd: function() {
706         return this.getSelectionBoundry('end');
707     },
708     getSelectionAnchor: function() {
709         return this.getSelectionBoundry('anchor');
710     },
711     getSelectionFocus: function() {
712         return this.getSelectionBoundry('focus');
713     },
714     getSelectionBoundry: function(which) {
715         var selection = window.getSelection(),
716             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
717             focusElement = this.canvas.getDocumentElement(selection.focusNode);
718         
719         var getOffset = function(where) {
720             var toret, node;
721             if(where === 'anchor') {
722                 node = selection.anchorNode;
723                 toret = selection.anchorOffset;
724             } else {
725                 node = selection.focusNode;
726                 toret = selection.focusOffset;
727             }
728                         
729             if(toret === 1 && node.data.charAt(0) === utils.unicode.ZWS)
730                 toret = 0;
731             else if((toret === node.data.length - 1) && (node.data.charAt(node.data.length - 1) === utils.unicode.ZWS))
732                 toret++;
733             return toret;
734         }
735
736         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
737             return {};
738
739         if(which === 'anchor') {
740             return {
741                 element: anchorElement,
742                 offset: getOffset('anchor'),
743                 offsetAtBeginning: getOffset('anchor') === 0,
744                 offsetAtEnd: selection.anchorNode.data.length === getOffset('anchor')
745             };
746         }
747         if(which === 'focus') {
748             return {
749                 element: focusElement,
750                 offset: getOffset('focus'),
751                 offsetAtBeginning: getOffset('focus') === 0,
752                 offsetAtEnd: selection.focusNode.data.length === getOffset('focus')
753             };
754         }
755         
756         var element,
757             offset;
758
759         if(anchorElement.parent().sameNode(focusElement.parent())) {
760             var parent = anchorElement.parent(),
761                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
762             if(anchorFirst) {
763                 if(which === 'start') {
764                     element = anchorElement;
765                     offset = getOffset('anchor')
766                 }
767                 else if(which === 'end') {
768                     element = focusElement,
769                     offset = getOffset('focus')
770                 }
771             } else {
772                 if(which === 'start') {
773                     element = focusElement,
774                     offset = getOffset('focus')
775                 }
776                 else if(which === 'end') {
777                     element = anchorElement;
778                     offset = getOffset('anchor')
779                 }
780             }
781         } else {
782             // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
783             if(which === 'start') {
784                 element = anchorElement;
785                 offset = getOffset('anchor')
786             } else {
787                 element = focusElement;
788                 offset = getOffset('focus')
789             }
790         }
791
792         var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
793         return {
794             element: element,
795             offset: offset,
796             offsetAtBeginning: offset === 0,
797             offsetAtEnd: nodeLen === offset
798         }
799     }
800 })
801
802 return {
803     fromXML: function(xml, publisher) {
804         return new Canvas(xml, publisher);
805     }
806 };
807
808 });