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