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