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