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