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