Fix: adding/clearing node widgets corrupted widgets on all children nodes
[fnpeditor.git] / modules / documentCanvas / canvas / documentElement.js
1 define([
2 'libs/jquery-1.9.1.min',
3 'libs/underscore-min',
4 'modules/documentCanvas/classAttributes',
5 'modules/documentCanvas/canvas/utils',
6 'modules/documentCanvas/canvas/widgets',
7 'modules/documentCanvas/canvas/wlxmlManagers'
8 ], function($, _, classAttributes, utils, widgets, wlxmlManagers) {
9     
10 'use strict';
11
12
13 // DocumentElement represents a text or an element node from WLXML document rendered inside Canvas
14 var DocumentElement = function(htmlElement, canvas) {
15     if(arguments.length === 0)
16         return;
17     this.canvas = canvas;
18     this._setupDOMHandler(htmlElement);
19 }
20
21 var elementTypeFromParams = function(params) {
22     return params.text !== undefined ? DocumentTextElement : DocumentNodeElement;
23
24 };
25
26 $.extend(DocumentElement, {
27     create: function(params, canvas) {
28         return elementTypeFromParams(params).create(params);
29     },
30
31     createDOM: function(params) {
32         return elementTypeFromParams(params).createDOM(params);
33     },
34
35     fromHTMLElement: function(htmlElement, canvas) {
36         var $element = $(htmlElement);
37         if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined)
38             return DocumentNodeElement.fromHTMLElement(htmlElement, canvas);
39         if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined))
40             return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
41         return undefined;
42     }
43 });
44
45 $.extend(DocumentElement.prototype, {
46     _setupDOMHandler: function(htmlElement) {
47         this.$element = $(htmlElement);
48     },
49     bound: function() {
50         return this.canvas !== undefined;
51     },
52     dom: function() {
53         return this.$element;
54     },
55     parent: function() {
56         var parents = this.$element.parents('[document-node-element]');
57         if(parents.length)
58             return DocumentElement.fromHTMLElement(parents[0], this.canvas);
59         return null;
60     },
61
62     parents: function() {
63         var parents = [],
64             parent = this.parent();
65         while(parent) {
66             parents.push(parent);
67             parent = parent.parent();
68         }
69         return parents;
70     },
71
72     sameNode: function(other) {
73         return other && (typeof other === typeof this) && other.dom()[0] === this.dom()[0];
74     },
75
76     wrapWithNodeElement: function(wlxmlNode) {
77         var wrapper = DocumentNodeElement.create({tag: wlxmlNode.tag, klass: wlxmlNode.klass}, this);
78         this.dom().replaceWith(wrapper.dom());
79         wrapper.append(this);
80         return wrapper;
81     },
82
83     markAsCurrent: function() {
84         this.canvas.markAsCurrent(this);
85     },
86
87     getVerticallyFirstTextElement: function() {
88         var toret;
89         this.children().some(function(child) {
90             if(!child.isVisible())
91                 return false; // continue
92             if(child instanceof DocumentTextElement) {
93                 toret = child;
94                 return true; // break
95             } else {
96                 toret = child.getVerticallyFirstTextElement();
97                 if(toret)
98                     return true; // break
99             }
100         });
101         return toret;
102     },
103
104     getPreviousTextElement: function(includeInvisible) {
105         return this.getNearestTextElement('above', includeInvisible);
106     },
107
108     getNextTextElement: function(includeInvisible) {
109         return this.getNearestTextElement('below', includeInvisible);
110     },
111
112     getNearestTextElement: function(direction, includeInvisible) {
113         includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
114         var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
115         return this.canvas.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, this.dom()[0]));
116     },
117
118     isVisible: function() {
119         return this instanceof DocumentTextElement || this.getWlxmlTag() !== 'metadata';
120     },
121
122     isInsideList: function() {
123         return this.parents().some(function(parent) {
124             return parent.is('list');
125         });
126     },
127
128     exec: function(method) {
129         var manager = this.data('_wlxmlManager');
130         if(manager[method])
131             return manager[method].apply(manager, Array.prototype.slice.call(arguments, 1));
132     }
133 });
134
135
136 // DocumentNodeElement represents an element node from WLXML document rendered inside Canvas
137 var DocumentNodeElement = function(htmlElement, canvas) {
138     DocumentElement.call(this, htmlElement, canvas);
139 };
140
141 $.extend(DocumentNodeElement, {
142     createDOM: function(params, canvas) {
143         var dom = $('<div>')
144                 .attr('document-node-element', ''),
145             widgetsContainer = $('<div>')
146                 .addClass('canvas-widgets')
147                 .attr('contenteditable', false),
148             container = $('<div>')
149                 .attr('document-element-content', '');
150         
151         dom.append(widgetsContainer, container);
152         // Make sure widgets aren't navigable with arrow keys
153         widgetsContainer.find('*').add(widgetsContainer).attr('tabindex', -1);
154
155         var element = this.fromHTMLElement(dom[0], canvas);
156
157         element.setWlxml({tag: params.tag, klass: params.klass});
158         if(params.meta) {
159             _.keys(params.meta).forEach(function(key) {
160                 element.setWlxmlMetaAttr(key, params.meta[key]);
161             });
162         }
163         element.data('other-attrs', params.others);
164
165         if(params.rawChildren && params.rawChildren.length) {
166             container.append(params.rawChildren);
167         } else if(params.prepopulateOnEmpty) {
168             element.append(DocumentTextElement.create({text: ''}));
169         }
170         return dom;
171     },
172
173     create: function(params, canvas) {
174         return this.fromHTMLElement(this.createDOM(params, canvas)[0], canvas);
175     },
176
177     fromHTMLElement: function(htmlElement, canvas) {
178         return new this(htmlElement, canvas);
179     }
180 });
181
182 var manipulate = function(e, params, action) {
183     var element;
184     if(params instanceof DocumentElement) {
185         element = params;
186     } else {
187         element = DocumentElement.create(params);
188     }
189     var target = (action === 'append' || action === 'prepend') ? e._container() : e.dom();
190     target[action](element.dom());
191     return element;
192 };
193
194 DocumentNodeElement.prototype = new DocumentElement();
195
196
197 $.extend(DocumentNodeElement.prototype, {
198     _container: function() {
199         return this.dom().children('[document-element-content]');
200     },
201     detach: function() {
202         var parent = this.parent();
203         if(!parent)
204             return;
205
206         var parentChildren = parent.children(),
207             myIdx = parent.childIndex(this);
208
209         if(myIdx > 0 && myIdx < parentChildren.length) {
210             if((parentChildren[myIdx-1] instanceof DocumentTextElement) && (parentChildren[myIdx+1] instanceof DocumentTextElement)) {
211                 parentChildren[myIdx-1].appendText(parentChildren[myIdx+1].getText());
212                 parentChildren[myIdx+1].detach();
213             }
214         }
215         this.dom().detach();
216         this.canvas = null;
217         return this;
218     },
219     unwrapContents: function() {
220         var parent = this.parent();
221         if(!parent)
222             return;
223
224         var parentChildren = parent.children(),
225             myChildren = this.children(),
226             myIdx = parent.childIndex(this);
227
228         if(myChildren.length === 0)
229             return this.detach();
230
231         var moveLeftRange, moveRightRange;
232
233         if(myIdx > 0 && (parentChildren[myIdx-1] instanceof DocumentTextElement) && (myChildren[0] instanceof DocumentTextElement)) {
234             parentChildren[myIdx-1].appendText(myChildren[0].getText());
235             myChildren[0].detach();
236             moveLeftRange = true;
237         }
238
239         if(myIdx < parentChildren.length - 1 && (parentChildren[parentChildren.length-1] instanceof DocumentTextElement) && (myChildren[myChildren.length-1] instanceof DocumentTextElement)) {
240             parentChildren[parentChildren.length-1].prependText(myChildren[myChildren.length-1].getText());
241             myChildren[myChildren.length-1].detach();
242             moveRightRange = true;
243         }
244
245         var childrenLength = this.children().length;
246         this.children().forEach(function(child) {
247             this.before(child);
248         }.bind(this));
249
250         this.detach();
251
252         return {
253             element1: parent.children()[myIdx + (moveLeftRange ? -1 : 0)],
254             element2: parent.children()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
255         };
256     },
257     data: function() {
258         var dom = this.dom(),
259             args = Array.prototype.slice.call(arguments, 0);
260         if(args.length === 2 && args[1] === undefined)
261             return dom.removeData(args[0]);
262         return dom.data.apply(dom, arguments);
263     },
264     toXML: function(level) {
265         var node = $('<' + this.getWlxmlTag() + '>');
266
267         if(this.getWlxmlClass())
268             node.attr('class', this.getWlxmlClass());
269         var meta = this.getWlxmlMetaAttrs();
270         meta.forEach(function(attr) {
271             if(attr.value)
272                 node.attr('meta-' + attr.name, attr.value);
273         });
274         _.keys(this.data('other-attrs') || {}).forEach(function(key) {
275             node.attr(key, this.data('other-attrs')[key]);
276         }, this);
277
278         var addFormatting = function() {
279             var toret = $('<div>');
280             var formattings = {};
281
282             if(this.data('orig-before') !== undefined) {
283                 if(this.data('orig-before')) {
284                     toret.prepend(document.createTextNode(this.data('orig-before')));
285                 }
286             } else if(level && this.getWlxmlTag() !== 'span') {
287                 toret.append('\n' + (new Array(level * 2 + 1)).join(' '));
288             }
289
290             toret.append(node);
291
292             if(this.data('orig-after')) {
293                 toret.append(document.createTextNode(this.data('orig-after')));
294             }
295
296             /* Inside node */
297             if(this.data('orig-begin')) {
298                 node.prepend(this.data('orig-begin'));
299                 formattings.begin = true;
300             }
301
302             if(this.data('orig-end') !== undefined) {
303                 if(this.data('orig-end')) {
304                     node.append(this.data('orig-end'));
305                 }
306             } else if(this.getWlxmlTag() !== 'span' && children.length){
307                 node.append('\n' + (new Array(level * 2 + 1)).join(' '));
308             }
309            
310             return {parts: toret.contents(), formattings: formattings};
311         }.bind(this);
312
313         
314         
315         var children = this.children(),
316             childParts;
317
318         var formatting = addFormatting(node);
319
320         for(var i = children.length - 1; i >= 0; i--) {
321             childParts = children[i].toXML(level + 1);
322             if(typeof childParts === 'string')
323                 childParts = [document.createTextNode(childParts)];
324
325             if(formatting.formattings.begin) {
326                 $(node.contents()[0]).after(childParts);
327             } else
328                 node.prepend(childParts);
329         }
330         return formatting.parts;
331     },
332     append: function(params) {
333         if(params.tag !== 'span')
334             this.data('orig-end', undefined);
335         return manipulate(this, params, 'append');
336     },
337     prepend: function(params) {
338         return manipulate(this, params, 'prepend');
339     },
340     before: function(params) {
341         return manipulate(this, params, 'before');
342
343     },
344     after: function(params) {
345         return manipulate(this, params, 'after');
346     },
347     children: function() {
348         var toret = [];
349         if(this instanceof DocumentTextElement)
350             return toret;
351
352
353         var elementContent = this._container().contents();
354         var element = this;
355         elementContent.each(function(idx) {
356             var childElement = DocumentElement.fromHTMLElement(this, element.canvas);
357             if(childElement === undefined)
358                 return true;
359             if(idx === 0 && elementContent.length > 1 && elementContent[1].nodeType === Node.ELEMENT_NODE && (childElement instanceof DocumentTextElement) && $.trim($(this).text()) === '')
360                 return true;
361             if(idx > 0 && childElement instanceof DocumentTextElement) {
362                 if(toret[toret.length-1] instanceof DocumentNodeElement && $.trim($(this).text()) === '')
363                     return true;
364             }
365             toret.push(childElement);
366         });
367         return toret;
368     },
369     childIndex: function(child) {
370         var children = this.children(),
371             toret = null;
372         children.forEach(function(c, idx) {
373             if(c.sameNode(child)) {
374                 toret = idx;
375                 return false;
376             }
377         });
378         return toret;
379     },
380     getWlxmlTag: function() {
381         return this._container().attr('wlxml-tag');
382     },
383     setWlxmlTag: function(tag) {
384         if(tag === this.getWlxmlTag())
385             return;
386
387         this._container().attr('wlxml-tag', tag);
388         if(!this.__updatingWlxml)
389             this._updateWlxmlManager();
390     },
391     getWlxmlClass: function() {
392         var klass = this._container().attr('wlxml-class');
393         if(klass)
394             return klass.replace(/-/g, '.');
395         return undefined;
396     },
397     setWlxmlClass: function(klass) {
398         if(klass === this.getWlxmlClass())
399             return;
400
401         this.getWlxmlMetaAttrs().forEach(function(attr) {
402             if(!classAttributes.hasMetaAttr(klass, attr.name))
403                 this.dom().removeAttr('wlxml-meta-' + attr.name);
404         }, this);
405
406         if(klass)
407             this._container().attr('wlxml-class', klass.replace(/\./g, '-'));
408         else
409             this._container().removeAttr('wlxml-class');
410         if(!this.__updatingWlxml)
411             this._updateWlxmlManager();
412     },
413     setWlxml: function(params) {
414         this.__updatingWlxml = true;
415         if(params.tag !== undefined)
416             this.setWlxmlTag(params.tag);
417         if(params.klass !== undefined)
418             this.setWlxmlClass(params.klass);
419         this._updateWlxmlManager();
420         this.__updatingWlxml = false;
421     },
422     _updateWlxmlManager: function() {
423         var manager = wlxmlManagers.getFor(this);
424         this.data('_wlxmlManager', manager);
425         manager.setup();
426     },
427     is: function(what) {
428         if(what === 'list' && _.contains(['list.items', 'list.items.enum'], this.getWlxmlClass()))
429             return true;
430         return false;
431     },
432
433     getWlxmlMetaAttr: function(attr) {
434         return this.dom().attr('wlxml-meta-'+attr);
435     },
436
437     getWlxmlMetaAttrs: function() {
438         var toret = [];
439         var attrList = classAttributes.getMetaAttrsList(this.getWlxmlClass());
440         attrList.all.forEach(function(attr) {
441             toret.push({name: attr.name, value: this.getWlxmlMetaAttr(attr.name) || ''});
442         }, this);
443         return toret;
444     },
445
446     setWlxmlMetaAttr: function(attr, value) {
447         this.dom().attr('wlxml-meta-'+attr, value);
448     },
449     
450     toggleLabel: function(toggle) {
451         var displayCss = toggle ? 'inline-block' : 'none';
452         var label = this.dom().children('.canvas-widgets').find('.canvas-widget-label');
453         label.css('display', displayCss);
454         this.toggleHighlight(toggle);
455     },
456
457     toggleHighlight: function(toggle) {
458         this._container().toggleClass('highlighted-element', toggle);
459     },
460
461     toggle: function(toggle) {
462         var mng = this.data('_wlxmlManager');
463         if(mng) {
464             mng.toggle(toggle);
465         }
466     }
467 });
468
469
470 // DocumentNodeElement represents a text node from WLXML document rendered inside Canvas
471 var DocumentTextElement = function(htmlElement, canvas) {
472     DocumentElement.call(this, htmlElement, canvas);
473 };
474
475 $.extend(DocumentTextElement, {
476     createDOM: function(params) {
477         return $('<div>')
478             .attr('document-text-element', '')
479             .text(params.text || utils.unicode.ZWS);
480     },
481
482     create: function(params, canvas) {
483         return this.fromHTMLElement(this.createDOM(params)[0]);
484     },
485
486     fromHTMLElement: function(htmlElement, canvas) {
487         return new this(htmlElement, canvas);
488     },
489     isContentContainer: function(htmlElement) {
490         return htmlElement.nodeType === Node.TEXT_NODE && $(htmlElement).parent().is('[document-text-element]');
491     }
492 });
493
494 DocumentTextElement.prototype = new DocumentElement();
495
496 $.extend(DocumentTextElement.prototype, {
497     toXML: function(parent) {
498         return this.getText();
499     },
500     _setupDOMHandler: function(htmlElement) {
501         var $element = $(htmlElement);
502         if(htmlElement.nodeType === Node.TEXT_NODE)
503             this.$element = $element.parent();
504         else
505             this.$element = $element;
506     },
507     detach: function() {
508         this.dom().detach();
509         this.canvas = null;
510         return this;
511     },
512     setText: function(text) {
513         this.dom().contents()[0].data = text;
514     },
515     appendText: function(text) {
516         this.dom().contents()[0].data += text;
517     },
518     prependText: function(text) {
519         this.dom().contents()[0].data = text + this.dom().contents()[0].data;
520     },
521     getText: function() {
522         return this.dom().text().replace(utils.unicode.ZWS, '');
523     },
524     isEmpty: function() {
525         // Having at least Zero Width Space is guaranteed be Content Observer
526         return this.dom().contents()[0].data === utils.unicode.ZWS;
527     },
528     after: function(params) {
529         if(params instanceof DocumentTextElement || params.text)
530             return false;
531         var element;
532         if(params instanceof DocumentNodeElement) {
533             element = params;
534         } else {
535             element = DocumentNodeElement.create(params, this.canvas);
536         }
537         this.dom().wrap('<div>');
538         this.dom().parent().after(element.dom());
539         this.dom().unwrap();
540         return element;
541     },
542     before: function(params) {
543         if(params instanceof DocumentTextElement || params.text)
544             return false;
545         var element;
546         if(params instanceof DocumentNodeElement) {
547             element = params;
548         } else {
549             element = DocumentNodeElement.create(params, this.canvas);
550         }
551         this.dom().wrap('<div>');
552         this.dom().parent().before(element.dom());
553         this.dom().unwrap();
554         return element;
555     },
556     wrapWithNodeElement: function(wlxmlNode) {
557         if(typeof wlxmlNode.start === 'number' && typeof wlxmlNode.end === 'number') {
558             return this.canvas.wrapText({
559                 inside: this.parent(),
560                 textNodeIdx: this.parent().childIndex(this),
561                 offsetStart: Math.min(wlxmlNode.start, wlxmlNode.end),
562                 offsetEnd: Math.max(wlxmlNode.start, wlxmlNode.end),
563                 _with: {tag: wlxmlNode.tag, klass: wlxmlNode.klass}
564             });
565         } else {
566             return DocumentElement.prototype.wrapWithNodeElement.call(this, wlxmlNode);
567         }
568     },
569     unwrap: function() {
570         var parent = this.parent(),
571             toret;
572         if(parent.children().length === 1) {
573             toret = parent.parent();
574             var grandParent = parent.parent();
575             if(grandParent) {
576                 var grandParentChildren = grandParent.children(),
577                     idx = grandParent.childIndex(parent),
578                     prev = idx - 1 > -1 ? grandParentChildren[idx-1] : null,
579                     next = idx + 1 < grandParentChildren.length ? grandParentChildren[idx+1] : null;
580                 
581                 prev = (prev instanceof DocumentTextElement) ? prev : null;
582                 next = (next instanceof DocumentTextElement) ? next : null;
583
584                 if(prev && next) {
585                     prev.setText(prev.getText() + this.getText() + next.getText());
586                     next.detach();
587                 } else if (prev || next) {
588                     var target = prev ? prev : next,
589                         newText = prev ? target.getText() + this.getText() : this.getText() + target.getText();
590                     target.setText(newText);
591                 } else {
592                     parent.after(this);
593                 }
594             } else {
595                 parent.after(this);
596             }
597             parent.detach();
598             return toret;
599         }
600     },
601     split: function(params) {
602         var parentElement = this.parent(),
603             myIdx = parentElement.childIndex(this),
604             myCanvas = this.canvas,
605             passed = false,
606             succeedingChildren = [],
607             thisElement = this,
608             prefix = this.getText().substr(0, params.offset),
609             suffix = this.getText().substr(params.offset);
610
611         parentElement.children().forEach(function(child) {
612             if(passed)
613                 succeedingChildren.push(child);
614             if(child.sameNode(thisElement))
615                 passed = true;
616         });
617
618         if(prefix.length > 0)
619             this.setText(prefix);
620         else
621             this.detach();
622         
623         var newElement = DocumentNodeElement.create({tag: parentElement.getWlxmlTag(), klass: parentElement.getWlxmlClass()}, myCanvas);
624         parentElement.after(newElement);
625
626         if(suffix.length > 0)
627             newElement.append({text: suffix});
628         succeedingChildren.forEach(function(child) {
629             newElement.append(child);
630         });
631
632         return {first: parentElement, second: newElement};
633     },
634     divide: function(params) {
635         var myText = this.getText();
636
637         if(params.offset === myText.length)
638             return this.after(params);
639         if(params.offset === 0)
640             return this.before(params);
641
642         var lhsText = myText.substr(0, params.offset),
643             rhsText = myText.substr(params.offset),
644             newElement = DocumentNodeElement.create({tag: params.tag, klass: params.klass}, this.canvas),
645             rhsTextElement = DocumentTextElement.create({text: rhsText});
646
647         this.setText(lhsText);
648         this.after(newElement);
649         newElement.after(rhsTextElement);
650         return newElement;
651     },
652
653     toggleHighlight: function() {
654         // do nothing for now
655     }
656 });
657
658 return {
659     DocumentElement: DocumentElement,
660     DocumentNodeElement: DocumentNodeElement,
661     DocumentTextElement: DocumentTextElement
662 };
663
664 });