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