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