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