smartxml: handle node being a root in DocumentNode.getIndex
[fnpeditor.git] / src / editor / modules / documentCanvas / canvas / documentElement.js
1 define([
2 'libs/jquery',
3 'libs/underscore',
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 $.contains(document.documentElement, this.dom()[0]);
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, leftMerged;
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             leftMerged = true;
238         } else {
239             leftMerged = false;
240         }
241
242         if(!(leftMerged && myChildren.length === 1)) {
243             if(myIdx < parentChildren.length - 1 && (parentChildren[myIdx+1] instanceof DocumentTextElement) && (myChildren[myChildren.length-1] instanceof DocumentTextElement)) {
244                 parentChildren[myIdx+1].prependText(myChildren[myChildren.length-1].getText());
245                 myChildren[myChildren.length-1].detach();
246                 moveRightRange = true;
247             }
248         }
249
250         var childrenLength = this.children().length;
251         this.children().forEach(function(child) {
252             this.before(child);
253         }.bind(this));
254
255         this.detach();
256
257         return {
258             element1: parent.children()[myIdx + (moveLeftRange ? -1 : 0)],
259             element2: parent.children()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
260         };
261     },
262     data: function() {
263         var dom = this.dom(),
264             args = Array.prototype.slice.call(arguments, 0);
265         if(args.length === 2 && args[1] === undefined)
266             return dom.removeData(args[0]);
267         return dom.data.apply(dom, arguments);
268     },
269     toXML: function(level) {
270         var node = $('<' + this.getWlxmlTag() + '>');
271
272         if(this.getWlxmlClass())
273             node.attr('class', this.getWlxmlClass());
274         var meta = this.getWlxmlMetaAttrs();
275         meta.forEach(function(attr) {
276             if(attr.value)
277                 node.attr('meta-' + attr.name, attr.value);
278         });
279         _.keys(this.data('other-attrs') || {}).forEach(function(key) {
280             node.attr(key, this.data('other-attrs')[key]);
281         }, this);
282
283         var addFormatting = function() {
284             var toret = $('<div>');
285             var formattings = {};
286
287             if(this.data('orig-before') !== undefined) {
288                 if(this.data('orig-before')) {
289                     toret.prepend(document.createTextNode(this.data('orig-before')));
290                 }
291             } else if(level && this.getWlxmlTag() !== 'span') {
292                 toret.append('\n' + (new Array(level * 2 + 1)).join(' '));
293             }
294
295             toret.append(node);
296
297             if(this.data('orig-after')) {
298                 toret.append(document.createTextNode(this.data('orig-after')));
299             }
300
301             /* Inside node */
302             if(this.data('orig-begin')) {
303                 node.prepend(this.data('orig-begin'));
304                 formattings.begin = true;
305             }
306
307             if(this.data('orig-end') !== undefined) {
308                 if(this.data('orig-end')) {
309                     node.append(this.data('orig-end'));
310                 }
311             } else if(this.getWlxmlTag() !== 'span' && children.length){
312                 node.append('\n' + (new Array(level * 2 + 1)).join(' '));
313             }
314            
315             return {parts: toret.contents(), formattings: formattings};
316         }.bind(this);
317
318         
319         
320         var children = this.children(),
321             childParts;
322
323         var formatting = addFormatting(node);
324
325         for(var i = children.length - 1; i >= 0; i--) {
326             childParts = children[i].toXML(level + 1);
327             if(typeof childParts === 'string')
328                 childParts = [document.createTextNode(childParts)];
329
330             if(formatting.formattings.begin) {
331                 $(node.contents()[0]).after(childParts);
332             } else
333                 node.prepend(childParts);
334         }
335         return formatting.parts;
336     },
337     append: function(params) {
338         if(params.tag !== 'span')
339             this.data('orig-end', undefined);
340         return manipulate(this, params, 'append');
341     },
342     prepend: function(params) {
343         return manipulate(this, params, 'prepend');
344     },
345     before: function(params) {
346         return manipulate(this, params, 'before');
347
348     },
349     after: function(params) {
350         return manipulate(this, params, 'after');
351     },
352     children: function() {
353         var toret = [];
354         if(this instanceof DocumentTextElement)
355             return toret;
356
357
358         var elementContent = this._container().contents();
359         var element = this;
360         elementContent.each(function(idx) {
361             var childElement = DocumentElement.fromHTMLElement(this, element.canvas);
362             if(childElement === undefined)
363                 return true;
364             if(idx === 0 && elementContent.length > 1 && elementContent[1].nodeType === Node.ELEMENT_NODE && (childElement instanceof DocumentTextElement) && $.trim($(this).text()) === '')
365                 return true;
366             if(idx > 0 && childElement instanceof DocumentTextElement) {
367                 if(toret[toret.length-1] instanceof DocumentNodeElement && $.trim($(this).text()) === '')
368                     return true;
369             }
370             toret.push(childElement);
371         });
372         return toret;
373     },
374     childIndex: function(child) {
375         var children = this.children(),
376             toret = null;
377         children.forEach(function(c, idx) {
378             if(c.sameNode(child)) {
379                 toret = idx;
380                 return false;
381             }
382         });
383         return toret;
384     },
385     getWlxmlTag: function() {
386         return this._container().attr('wlxml-tag');
387     },
388     setWlxmlTag: function(tag) {
389         if(tag === this.getWlxmlTag())
390             return;
391
392         this._container().attr('wlxml-tag', tag);
393         if(!this.__updatingWlxml)
394             this._updateWlxmlManager();
395     },
396     getWlxmlClass: function() {
397         var klass = this._container().attr('wlxml-class');
398         if(klass)
399             return klass.replace(/-/g, '.');
400         return undefined;
401     },
402     setWlxmlClass: function(klass) {
403         if(klass === this.getWlxmlClass())
404             return;
405
406         this.getWlxmlMetaAttrs().forEach(function(attr) {
407             if(!classAttributes.hasMetaAttr(klass, attr.name))
408                 this.dom().removeAttr('wlxml-meta-' + attr.name);
409         }, this);
410
411         if(klass)
412             this._container().attr('wlxml-class', klass.replace(/\./g, '-'));
413         else
414             this._container().removeAttr('wlxml-class');
415         if(!this.__updatingWlxml)
416             this._updateWlxmlManager();
417     },
418     setWlxml: function(params) {
419         this.__updatingWlxml = true;
420         if(params.tag !== undefined)
421             this.setWlxmlTag(params.tag);
422         if(params.klass !== undefined)
423             this.setWlxmlClass(params.klass);
424         this._updateWlxmlManager();
425         this.__updatingWlxml = false;
426     },
427     _updateWlxmlManager: function() {
428         var manager = wlxmlManagers.getFor(this);
429         this.data('_wlxmlManager', manager);
430         manager.setup();
431     },
432     is: function(what) {
433         if(what === 'list' && _.contains(['list.items', 'list.items.enum'], this.getWlxmlClass()))
434             return true;
435         return false;
436     },
437
438     getWlxmlMetaAttr: function(attr) {
439         return this.dom().attr('wlxml-meta-'+attr);
440     },
441
442     getWlxmlMetaAttrs: function() {
443         var toret = [];
444         var attrList = classAttributes.getMetaAttrsList(this.getWlxmlClass());
445         attrList.all.forEach(function(attr) {
446             toret.push({name: attr.name, value: this.getWlxmlMetaAttr(attr.name) || ''});
447         }, this);
448         return toret;
449     },
450
451     setWlxmlMetaAttr: function(attr, value) {
452         this.dom().attr('wlxml-meta-'+attr, value);
453     },
454     
455     toggleLabel: function(toggle) {
456         var displayCss = toggle ? 'inline-block' : 'none';
457         var label = this.dom().children('.canvas-widgets').find('.canvas-widget-label');
458         label.css('display', displayCss);
459         this.toggleHighlight(toggle);
460     },
461
462     toggleHighlight: function(toggle) {
463         this._container().toggleClass('highlighted-element', toggle);
464     },
465
466     toggle: function(toggle) {
467         var mng = this.data('_wlxmlManager');
468         if(mng) {
469             mng.toggle(toggle);
470         }
471     }
472 });
473
474
475 // DocumentNodeElement represents a text node from WLXML document rendered inside Canvas
476 var DocumentTextElement = function(htmlElement, canvas) {
477     DocumentElement.call(this, htmlElement, canvas);
478 };
479
480 $.extend(DocumentTextElement, {
481     createDOM: function(params) {
482         return $('<div>')
483             .attr('document-text-element', '')
484             .text(params.text || utils.unicode.ZWS);
485     },
486
487     create: function(params, canvas) {
488         return this.fromHTMLElement(this.createDOM(params)[0]);
489     },
490
491     fromHTMLElement: function(htmlElement, canvas) {
492         return new this(htmlElement, canvas);
493     },
494     isContentContainer: function(htmlElement) {
495         return htmlElement.nodeType === Node.TEXT_NODE && $(htmlElement).parent().is('[document-text-element]');
496     }
497 });
498
499 DocumentTextElement.prototype = new DocumentElement();
500
501 $.extend(DocumentTextElement.prototype, {
502     toXML: function(parent) {
503         return this.getText();
504     },
505     _setupDOMHandler: function(htmlElement) {
506         var $element = $(htmlElement);
507         if(htmlElement.nodeType === Node.TEXT_NODE)
508             this.$element = $element.parent();
509         else
510             this.$element = $element;
511     },
512     detach: function() {
513         this.dom().detach();
514         this.canvas = null;
515         return this;
516     },
517     setText: function(text) {
518         this.dom().contents()[0].data = text;
519     },
520     appendText: function(text) {
521         this.dom().contents()[0].data += text;
522     },
523     prependText: function(text) {
524         this.dom().contents()[0].data = text + this.dom().contents()[0].data;
525     },
526     getText: function() {
527         return this.dom().text().replace(utils.unicode.ZWS, '');
528     },
529     isEmpty: function() {
530         // Having at least Zero Width Space is guaranteed be Content Observer
531         return this.dom().contents()[0].data === utils.unicode.ZWS;
532     },
533     after: function(params) {
534         if(params instanceof DocumentTextElement || params.text)
535             return false;
536         var element;
537         if(params instanceof DocumentNodeElement) {
538             element = params;
539         } else {
540             element = DocumentNodeElement.create(params, this.canvas);
541         }
542         this.dom().wrap('<div>');
543         this.dom().parent().after(element.dom());
544         this.dom().unwrap();
545         return element;
546     },
547     before: function(params) {
548         if(params instanceof DocumentTextElement || params.text)
549             return false;
550         var element;
551         if(params instanceof DocumentNodeElement) {
552             element = params;
553         } else {
554             element = DocumentNodeElement.create(params, this.canvas);
555         }
556         this.dom().wrap('<div>');
557         this.dom().parent().before(element.dom());
558         this.dom().unwrap();
559         return element;
560     },
561     wrapWithNodeElement: function(wlxmlNode) {
562         if(typeof wlxmlNode.start === 'number' && typeof wlxmlNode.end === 'number') {
563             return this.canvas.wrapText({
564                 inside: this.parent(),
565                 textNodeIdx: this.parent().childIndex(this),
566                 offsetStart: Math.min(wlxmlNode.start, wlxmlNode.end),
567                 offsetEnd: Math.max(wlxmlNode.start, wlxmlNode.end),
568                 _with: {tag: wlxmlNode.tag, klass: wlxmlNode.klass}
569             });
570         } else {
571             return DocumentElement.prototype.wrapWithNodeElement.call(this, wlxmlNode);
572         }
573     },
574     unwrap: function() {
575         var parent = this.parent(),
576             toret;
577         if(parent.children().length === 1) {
578             toret = parent.parent();
579             var grandParent = parent.parent();
580             if(grandParent) {
581                 var grandParentChildren = grandParent.children(),
582                     idx = grandParent.childIndex(parent),
583                     prev = idx - 1 > -1 ? grandParentChildren[idx-1] : null,
584                     next = idx + 1 < grandParentChildren.length ? grandParentChildren[idx+1] : null;
585                 
586                 prev = (prev instanceof DocumentTextElement) ? prev : null;
587                 next = (next instanceof DocumentTextElement) ? next : null;
588
589                 if(prev && next) {
590                     prev.setText(prev.getText() + this.getText() + next.getText());
591                     next.detach();
592                 } else if (prev || next) {
593                     var target = prev ? prev : next,
594                         newText = prev ? target.getText() + this.getText() : this.getText() + target.getText();
595                     target.setText(newText);
596                 } else {
597                     parent.after(this);
598                 }
599             } else {
600                 parent.after(this);
601             }
602             parent.detach();
603             return toret;
604         }
605     },
606     split: function(params) {
607         var parentElement = this.parent(),
608             myIdx = parentElement.childIndex(this),
609             myCanvas = this.canvas,
610             passed = false,
611             succeedingChildren = [],
612             thisElement = this,
613             prefix = this.getText().substr(0, params.offset),
614             suffix = this.getText().substr(params.offset);
615
616         parentElement.children().forEach(function(child) {
617             if(passed)
618                 succeedingChildren.push(child);
619             if(child.sameNode(thisElement))
620                 passed = true;
621         });
622
623         if(prefix.length > 0)
624             this.setText(prefix);
625         else
626             this.detach();
627         
628         var newElement = DocumentNodeElement.create({tag: parentElement.getWlxmlTag(), klass: parentElement.getWlxmlClass()}, myCanvas);
629         parentElement.after(newElement);
630
631         if(suffix.length > 0)
632             newElement.append({text: suffix});
633         succeedingChildren.forEach(function(child) {
634             newElement.append(child);
635         });
636
637         return {first: parentElement, second: newElement};
638     },
639     divide: function(params) {
640         var myText = this.getText();
641
642         if(params.offset === myText.length)
643             return this.after(params);
644         if(params.offset === 0)
645             return this.before(params);
646
647         var lhsText = myText.substr(0, params.offset),
648             rhsText = myText.substr(params.offset),
649             newElement = DocumentNodeElement.create({tag: params.tag, klass: params.klass}, this.canvas),
650             rhsTextElement = DocumentTextElement.create({text: rhsText});
651
652         this.setText(lhsText);
653         this.after(newElement);
654         newElement.after(rhsTextElement);
655         return newElement;
656     },
657
658     toggleHighlight: function() {
659         // do nothing for now
660     }
661 });
662
663 return {
664     DocumentElement: DocumentElement,
665     DocumentNodeElement: DocumentNodeElement,
666     DocumentTextElement: DocumentTextElement
667 };
668
669 });