a89a14877500bd4a4787fd4cdbb475d76e627e8d
[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                     canvas.setCurrentElement(canvas.getCursor().getPosition().element, {caretTo: false})
174             });
175          
176             this.wrapper.on('keydown', function(e) {
177                 if(e.which >= 37 && e.which <= 40) {
178                     var position = canvas.getCursor().getPosition(),
179                         element = position.element;
180                     if(element && (element instanceof documentElement.DocumentTextElement)) {
181                         if(element.isEmpty()) {
182                             var direction, caretTo;
183                             if(e.which === KEYS.ARROW_LEFT  || e.which === KEYS.ARROW_UP) {
184                                 direction = 'above';
185                                 caretTo = 'end';
186                             } else {
187                                 direction = 'below';
188                                 caretTo = 'start';
189                             }
190                             var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, window.getSelection().focusNode))
191                             canvas.setCurrentElement(element, {caretTo: caretTo});
192                         } else {
193                             var txt = element.dom().contents()[0].data;
194                             if(e.which === KEYS.ARROW_LEFT && position.offset > 1 && txt.charAt(position.offset-2) === utils.unicode.ZWS) {
195                                 e.preventDefault();
196                                 canvas._moveCaretToTextElement(element, position.offset-2);
197                             }
198                             if(e.which === KEYS.ARROW_RIGHT && position.offset < txt.length - 1 && txt.charAt(position.offset+1) === utils.unicode.ZWS) {
199                                 e.preventDefault();
200                                 canvas._moveCaretToTextElement(element, position.offset+2);
201                             }
202                         }
203                     }
204
205
206                 }
207             });
208
209             this.wrapper.on('click', '[wlxml-tag], [wlxml-text]', function(e) {
210                 e.stopPropagation();
211                 canvas.setCurrentElement(canvas.getDocumentElement(e.target), {caretTo: false});
212             });
213
214             var observer = new MutationObserver(function(mutations) {
215                 mutations.forEach(function(mutation) {
216                     if(documentElement.DocumentTextElement.isContentContainer(mutation.target) && mutation.target.data === '')
217                         mutation.target.data = utils.unicode.ZWS;
218                 });
219             });
220             var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
221             observer.observe(this.d[0], config);
222
223             this.wrapper.on('mouseover', '[wlxml-tag], [wlxml-text]', function(e) {
224                 var el = canvas.getDocumentElement(e.target);
225                 if(!el)
226                     return;
227                 e.stopPropagation();
228                 if(el instanceof documentElement.DocumentTextElement)
229                     el = el.parent();
230                 el.toggleLabel(true);
231             });
232             this.wrapper.on('mouseout', '[wlxml-tag], [wlxml-text]', function(e) {
233                 var el = canvas.getDocumentElement(e.target);
234                 if(!el)
235                     return;
236                 e.stopPropagation();
237                 if(el instanceof documentElement.DocumentTextElement)
238                     el = el.parent();
239                 el.toggleLabel(false);
240             });
241
242         } else {
243             this.d = null;
244         }
245     },
246
247     view: function() {
248         return this.wrapper;
249     },
250
251     doc: function() {
252         if(this.d === null)
253             return null;
254         return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
255     },
256
257     wrapText: function(params) {
258         params = _.extend({textNodeIdx: 0}, params);
259         if(typeof params.textNodeIdx === 'number')
260             params.textNodeIdx = [params.textNodeIdx];
261         
262         var childrenInside = params.inside.children(),
263             idx1 = Math.min.apply(Math, params.textNodeIdx),
264             idx2 = Math.max.apply(Math, params.textNodeIdx),
265             textNode1 = childrenInside[idx1],
266             textNode2 = childrenInside[idx2],
267             sameNode = textNode1.sameNode(textNode2),
268             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
269             prefixInside = textNode1.getText().substr(params.offsetStart),
270             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
271             suffixOutside = textNode2.getText().substr(params.offsetEnd)
272         ;
273         
274         var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
275         textNode1.after(wrapperElement);
276         textNode1.detach();
277         
278         if(prefixOutside.length > 0)
279             wrapperElement.before({text:prefixOutside});
280         if(sameNode) {
281             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
282             wrapperElement.append({text: core});
283         } else {
284             textNode2.detach();
285             if(prefixInside.length > 0)
286                 wrapperElement.append({text: prefixInside});
287             for(var i = idx1 + 1; i < idx2; i++) {
288                 wrapperElement.append(childrenInside[i]);
289             }
290             if(suffixInside.length > 0)
291                 wrapperElement.append({text: suffixInside});
292         }
293         if(suffixOutside.length > 0)
294             wrapperElement.after({text: suffixOutside});
295         return wrapperElement;
296     },
297     getDocumentElement: function(from) {
298         if(from instanceof HTMLElement || from instanceof Text) {
299            return documentElement.DocumentElement.fromHTMLElement(from, this);
300         }
301     },
302     getCursor: function() {
303         return new Cursor(this);
304     },
305
306     list: {},
307
308
309
310     highlightElement: function(element) {
311         this.wrapper.find('.highlighted-element').removeClass('highlighted-element');
312         element.dom().addClass('highlighted-element');
313     },
314
315     dimElement: function(element) {
316         element.dom().removeClass('highlighted-element');
317     },
318     
319     getCurrentNodeElement: function() {
320         return this.getDocumentElement(this.wrapper.find('.current-node-element')[0]);
321     },
322
323     getCurrentTextElement: function() {
324         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
325     },
326
327
328
329     setCurrentElement: function(element, params) {
330         params = _.extend({caretTo: 'end'}, params);
331         var findFirstDirectTextChild = function(e, nodeToLand) {
332             var byBrowser = this.getCursor().getPosition().element;
333             if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
334                 return byBrowser;
335             var children = e.children();
336             for(var i = 0; i < children.length; i++) {
337                 if(children[i] instanceof documentElement.DocumentTextElement)
338                     return children[i];
339             }
340             return null;
341         }.bind(this);
342         var _markAsCurrent = function(element) {
343             if(element instanceof documentElement.DocumentTextElement) {
344                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
345                 element.dom().addClass('current-text-element');
346             } else {
347                 this.wrapper.find('.current-node-element').removeClass('current-node-element')
348                 element.dom().addClass('current-node-element');
349                 this.publisher('currentElementChanged', element);
350             }
351         }.bind(this);
352
353
354         var isTextElement = element instanceof documentElement.DocumentTextElement,
355             nodeElementToLand = isTextElement ? element.parent() : element,
356             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
357             currentTextElement = this.getCurrentTextElement(),
358             currentNodeElement = this.getCurrentNodeElement();
359
360         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
361             this.wrapper.find('.current-text-element').removeClass('current-text-element');
362
363         if(textElementToLand) {
364             _markAsCurrent(textElementToLand);
365             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
366                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
367             if(!(textElementToLand.sameNode(currentTextElement)))
368                 this.publisher('currentTextElementSet', textElementToLand);
369         } else {
370             document.getSelection().removeAllRanges();
371         }
372
373         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
374             _markAsCurrent(nodeElementToLand);
375
376             this.publisher('currentNodeElementSet', nodeElementToLand);
377         }
378     },
379
380     _moveCaretToTextElement: function(element, where) {
381         var range = document.createRange(),
382             node = element.dom().contents()[0];
383
384         if(typeof where !== 'number') {
385             range.selectNodeContents(node);
386         } else {
387             range.setStart(node, where);
388         }
389         
390         var collapseArg = true;
391         if(where === 'end')
392             collapseArg = false;
393         range.collapse(collapseArg);
394         
395         var selection = document.getSelection();
396
397         selection.removeAllRanges();
398         selection.addRange(range);
399         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
400     },
401
402     setCursorPosition: function(position) {
403         if(position.element)
404             this._moveCaretToTextElement(position.element, position.offset);
405     },
406
407     toXML: function() {
408         var parent = $('<div>'),
409             parts = this.doc().toXML(0);
410         parent.append(parts);
411         return parent.html();
412     }
413 });
414
415 $.extend(Canvas.prototype.list, {
416     create: function(params) {
417         if(!(params.element1.parent().sameNode(params.element2.parent())))
418             return false;
419             
420         var parent = params.element1.parent();
421         
422         if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
423             var tmp = params.element1;
424             params.element1 = params.element2;
425             params.element2 = tmp;
426         }
427         
428         var elementsToWrap = [];
429         
430         var place = 'before';
431         var canvas = this;
432         parent.children().some(function(element) {
433             var _e = element;
434             if(element.sameNode(params.element1))
435                 place = 'inside';
436             if(place === 'inside') {
437                 if(element instanceof documentElement.DocumentTextElement) {
438                     element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
439                     if(element.children()[0].sameNode(params.element1))
440                         params.element1 = element;
441                 }
442                 element.setWlxmlClass('item');
443                 elementsToWrap.push(element);
444             }
445             if(_e.sameNode(params.element2))
446                 return true;
447         });
448         
449         var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
450         
451         var toret;
452         if(parent.is('list')) {
453             listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
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 instanceof documentElement.DocumentNodeElement || 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: anchorElement && anchorElement.getText().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: focusElement && focusElement.getText().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         return {
638             element: element,
639             offset: offset,
640             offsetAtBeginning: offset === 0,
641             offsetAtEnd: element.getText().length === offset
642         }
643     }
644 })
645
646 return {
647     fromXML: function(xml, publisher) {
648         return new Canvas(xml, publisher);
649     }
650 };
651
652 });