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