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