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