f96e62ef135a471d26977a19c6b8ea70eeb4a21b
[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], [document-text-element]', 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
224             this.wrapper.on('mouseover', '[wlxml-tag], [document-text-element]', function(e) {
225                 var el = canvas.getDocumentElement(e.target);
226                 if(!el)
227                     return;
228                 e.stopPropagation();
229                 if(el instanceof documentElement.DocumentTextElement)
230                     el = el.parent();
231                 el.toggleLabel(true);
232             });
233             this.wrapper.on('mouseout', '[wlxml-tag], [document-text-element]', function(e) {
234                 var el = canvas.getDocumentElement(e.target);
235                 if(!el)
236                     return;
237                 e.stopPropagation();
238                 if(el instanceof documentElement.DocumentTextElement)
239                     el = el.parent();
240                 el.toggleLabel(false);
241             });
242
243         } else {
244             this.d = null;
245         }
246     },
247
248     view: function() {
249         return this.wrapper;
250     },
251
252     doc: function() {
253         if(this.d === null)
254             return null;
255         return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
256     },
257
258     wrapText: function(params) {
259         params = _.extend({textNodeIdx: 0}, params);
260         if(typeof params.textNodeIdx === 'number')
261             params.textNodeIdx = [params.textNodeIdx];
262         
263         var childrenInside = params.inside.children(),
264             idx1 = Math.min.apply(Math, params.textNodeIdx),
265             idx2 = Math.max.apply(Math, params.textNodeIdx),
266             textNode1 = childrenInside[idx1],
267             textNode2 = childrenInside[idx2],
268             sameNode = textNode1.sameNode(textNode2),
269             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
270             prefixInside = textNode1.getText().substr(params.offsetStart),
271             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
272             suffixOutside = textNode2.getText().substr(params.offsetEnd)
273         ;
274         
275         var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
276         textNode1.after(wrapperElement);
277         textNode1.detach();
278         
279         if(prefixOutside.length > 0)
280             wrapperElement.before({text:prefixOutside});
281         if(sameNode) {
282             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
283             wrapperElement.append({text: core});
284         } else {
285             textNode2.detach();
286             if(prefixInside.length > 0)
287                 wrapperElement.append({text: prefixInside});
288             for(var i = idx1 + 1; i < idx2; i++) {
289                 wrapperElement.append(childrenInside[i]);
290             }
291             if(suffixInside.length > 0)
292                 wrapperElement.append({text: suffixInside});
293         }
294         if(suffixOutside.length > 0)
295             wrapperElement.after({text: suffixOutside});
296         return wrapperElement;
297     },
298     getDocumentElement: function(from) {
299         if(from instanceof HTMLElement || from instanceof Text) {
300            return documentElement.DocumentElement.fromHTMLElement(from, this);
301         }
302     },
303     getCursor: function() {
304         return new Cursor(this);
305     },
306
307     list: {},
308
309
310
311     highlightElement: function(element) {
312         this.wrapper.find('.highlighted-element').removeClass('highlighted-element');
313         element.dom().addClass('highlighted-element');
314     },
315
316     dimElement: function(element) {
317         element.dom().removeClass('highlighted-element');
318     },
319     
320     getCurrentNodeElement: function() {
321         return this.getDocumentElement(this.wrapper.find('.current-node-element')[0]);
322     },
323
324     getCurrentTextElement: function() {
325         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
326     },
327
328
329
330     setCurrentElement: function(element, params) {
331         params = _.extend({caretTo: 'end'}, params);
332         var findFirstDirectTextChild = function(e, nodeToLand) {
333             var byBrowser = this.getCursor().getPosition().element;
334             if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
335                 return byBrowser;
336             var children = e.children();
337             for(var i = 0; i < children.length; i++) {
338                 if(children[i] instanceof documentElement.DocumentTextElement)
339                     return children[i];
340             }
341             return null;
342         }.bind(this);
343         var _markAsCurrent = function(element) {
344             if(element instanceof documentElement.DocumentTextElement) {
345                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
346                 element.dom().addClass('current-text-element');
347             } else {
348                 this.wrapper.find('.current-node-element').removeClass('current-node-element')
349                 element.dom().addClass('current-node-element');
350                 this.publisher('currentElementChanged', element);
351             }
352         }.bind(this);
353
354
355         var isTextElement = element instanceof documentElement.DocumentTextElement,
356             nodeElementToLand = isTextElement ? element.parent() : element,
357             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
358             currentTextElement = this.getCurrentTextElement(),
359             currentNodeElement = this.getCurrentNodeElement();
360
361         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
362             this.wrapper.find('.current-text-element').removeClass('current-text-element');
363
364         if(textElementToLand) {
365             _markAsCurrent(textElementToLand);
366             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
367                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
368             if(!(textElementToLand.sameNode(currentTextElement)))
369                 this.publisher('currentTextElementSet', textElementToLand);
370         } else {
371             document.getSelection().removeAllRanges();
372         }
373
374         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
375             _markAsCurrent(nodeElementToLand);
376
377             this.publisher('currentNodeElementSet', nodeElementToLand);
378         }
379     },
380
381     _moveCaretToTextElement: function(element, where) {
382         var range = document.createRange(),
383             node = element.dom().contents()[0];
384
385         if(typeof where !== 'number') {
386             range.selectNodeContents(node);
387         } else {
388             range.setStart(node, where);
389         }
390         
391         var collapseArg = true;
392         if(where === 'end')
393             collapseArg = false;
394         range.collapse(collapseArg);
395         
396         var selection = document.getSelection();
397
398         selection.removeAllRanges();
399         selection.addRange(range);
400         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
401     },
402
403     setCursorPosition: function(position) {
404         if(position.element)
405             this._moveCaretToTextElement(position.element, position.offset);
406     },
407
408     toXML: function() {
409         var parent = $('<div>'),
410             parts = this.doc().toXML(0);
411         parent.append(parts);
412         return parent.html();
413     }
414 });
415
416 $.extend(Canvas.prototype.list, {
417     create: function(params) {
418         if(!(params.element1.parent().sameNode(params.element2.parent())))
419             return false;
420             
421         var parent = params.element1.parent();
422         
423         if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
424             var tmp = params.element1;
425             params.element1 = params.element2;
426             params.element2 = tmp;
427         }
428         
429         var elementsToWrap = [];
430         
431         var place = 'before';
432         var canvas = this;
433         parent.children().some(function(element) {
434             var _e = element;
435             if(element.sameNode(params.element1))
436                 place = 'inside';
437             if(place === 'inside') {
438                 if(element instanceof documentElement.DocumentTextElement) {
439                     element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
440                     if(element.children()[0].sameNode(params.element1))
441                         params.element1 = element;
442                 }
443                 element.setWlxmlClass('item');
444                 elementsToWrap.push(element);
445             }
446             if(_e.sameNode(params.element2))
447                 return true;
448         });
449         
450         var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
451         
452         var toret;
453         if(parent.is('list')) {
454             listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
455             toret = listElement.parent();
456         } else {
457             toret = listElement;
458         }  
459         
460         params.element1.before(toret);
461         
462         elementsToWrap.forEach(function(element) {
463             element.detach();
464             listElement.append(element);
465         });
466     },
467     extractItems: function(params) {
468         params = _.extend({merge: true}, params);
469         var list = params.element1.parent();
470         if(!list.is('list') || !(list.sameNode(params.element2.parent())))
471             return false;
472
473         var idx1 = list.childIndex(params.element1),
474             idx2 = list.childIndex(params.element2),
475             precedingItems = [],
476             extractedItems = [],
477             succeedingItems = [],
478             items = list.children(),
479             listIsNested = list.parent().getWlxmlClass() === 'item',
480             i;
481
482         if(idx1 > idx2) {
483             var tmp = idx1; idx1 = idx2; idx2 = tmp;
484         }
485
486         items.forEach(function(item, idx) {
487             if(idx < idx1)
488                 precedingItems.push(item);
489             else if(idx >= idx1 && idx <= idx2) {
490                 extractedItems.push(item);
491             }
492             else {
493                 succeedingItems.push(item);
494             }
495         });
496
497         var reference = listIsNested ? list.parent() : list;
498         if(succeedingItems.length === 0) {
499             var reference_orig = reference;
500             extractedItems.forEach(function(item) {
501                 reference.after(item);
502                 reference = item;
503                 if(!listIsNested)
504                     item.setWlxmlClass(null);
505             });
506             if(precedingItems.length === 0)
507                 reference_orig.detach();
508         } else if(precedingItems.length === 0) {
509             extractedItems.forEach(function(item) {
510                 reference.before(item);
511                 if(!listIsNested)
512                     item.setWlxmlClass(null);
513             });
514         } else {
515             extractedItems.forEach(function(item) {
516                 reference.after(item);
517                 if(!listIsNested)
518                     item.setWlxmlClass(null);
519                 reference = item;
520             });
521             var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
522                 toAdd = secondList;
523             
524             if(listIsNested) {
525                 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
526             }
527             succeedingItems.forEach(function(item) {
528                 secondList.append(item);
529             });
530
531             reference.after(toAdd);
532         }
533         if(!params.merge && listIsNested) {
534             return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
535         }
536         return true;
537     },
538     areItemsOfTheSameList: function(params) {
539         var e1 = params.element1,
540             e2 = params.element2;
541         return e1.parent().sameNode(e2.parent())
542             && e1.parent().is('list');
543     }
544 });
545
546
547 var Cursor = function(canvas) {
548     this.canvas = canvas;
549 };
550
551 $.extend(Cursor.prototype, {
552     isSelecting: function() {
553         var selection = window.getSelection();
554         return !selection.isCollapsed;
555     },
556     isSelectingWithinElement: function() {
557         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
558     },
559     isSelectingSiblings: function() {
560         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
561     },
562     getPosition: function() {
563         return this.getSelectionAnchor();
564     },
565     getSelectionStart: function() {
566         return this.getSelectionBoundry('start');
567     },
568     getSelectionEnd: function() {
569         return this.getSelectionBoundry('end');
570     },
571     getSelectionAnchor: function() {
572         return this.getSelectionBoundry('anchor');
573     },
574     getSelectionFocus: function() {
575         return this.getSelectionBoundry('focus');
576     },
577     getSelectionBoundry: function(which) {
578         var selection = window.getSelection(),
579             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
580             focusElement = this.canvas.getDocumentElement(selection.focusNode);
581         
582         if(anchorElement instanceof documentElement.DocumentNodeElement || focusElement instanceof documentElement.DocumentNodeElement)
583             return {};
584
585         if(which === 'anchor') {
586             return {
587                 element: anchorElement,
588                 offset: selection.anchorOffset,
589                 offsetAtBeginning: selection.anchorOffset === 0,
590                 offsetAtEnd: anchorElement && anchorElement.getText().length === selection.anchorOffset
591             };
592         }
593         if(which === 'focus') {
594             return {
595                 element: focusElement,
596                 offset: selection.focusOffset,
597                 offsetAtBeginning: selection.focusOffset === 0,
598                 offsetAtEnd: focusElement && focusElement.getText().length === selection.focusOffset
599             };
600         }
601         
602         var element,
603             offset;
604
605         if(anchorElement.parent().sameNode(focusElement.parent())) {
606             var parent = anchorElement.parent(),
607                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
608             if(anchorFirst) {
609                 if(which === 'start') {
610                     element = anchorElement;
611                     offset = selection.anchorOffset;
612                 }
613                 else if(which === 'end') {
614                     element = focusElement,
615                     offset = selection.focusOffset;
616                 }
617             } else {
618                 if(which === 'start') {
619                     element = focusElement,
620                     offset = selection.focusOffset
621                 }
622                 else if(which === 'end') {
623                     element = anchorElement;
624                     offset = selection.anchorOffset;
625                 }
626             }
627         } else {
628             // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
629             if(which === 'start') {
630                 element = anchorElement;
631                 offset = selection.anchorOffset
632             } else {
633                 element = focusElement;
634                 offset = selection.focusOffset
635             }
636         }
637
638         return {
639             element: element,
640             offset: offset,
641             offsetAtBeginning: offset === 0,
642             offsetAtEnd: element.getText().length === offset
643         }
644     }
645 })
646
647 return {
648     fromXML: function(xml, publisher) {
649         return new Canvas(xml, publisher);
650     }
651 };
652
653 });