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