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