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