2 'libs/jquery-1.9.1.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) {
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)
18 this._setupDOMHandler(htmlElement);
21 var elementTypeFromParams = function(params) {
22 return params.text !== undefined ? DocumentTextElement : DocumentNodeElement;
26 $.extend(DocumentElement, {
27 create: function(params, canvas) {
28 return elementTypeFromParams(params).create(params);
31 createDOM: function(params) {
32 return elementTypeFromParams(params).createDOM(params);
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);
45 $.extend(DocumentElement.prototype, {
46 _setupDOMHandler: function(htmlElement) {
47 this.$element = $(htmlElement);
50 return this.canvas !== undefined;
56 var parents = this.$element.parents('[document-node-element]');
58 return DocumentElement.fromHTMLElement(parents[0], this.canvas);
64 parent = this.parent();
67 parent = parent.parent();
72 sameNode: function(other) {
73 return other && (typeof other === typeof this) && other.dom()[0] === this.dom()[0];
76 wrapWithNodeElement: function(wlxmlNode) {
77 var wrapper = DocumentNodeElement.create({tag: wlxmlNode.tag, klass: wlxmlNode.klass}, this);
78 this.dom().replaceWith(wrapper.dom());
83 markAsCurrent: function() {
84 this.canvas.markAsCurrent(this);
87 getVerticallyFirstTextElement: function() {
89 this.children().some(function(child) {
90 if(!child.isVisible())
91 return false; // continue
92 if(child instanceof DocumentTextElement) {
96 toret = child.getVerticallyFirstTextElement();
104 getPreviousTextElement: function(includeInvisible) {
105 return this.getNearestTextElement('above', includeInvisible);
108 getNextTextElement: function(includeInvisible) {
109 return this.getNearestTextElement('below', includeInvisible);
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]));
118 isVisible: function() {
119 return this instanceof DocumentTextElement || this.getWlxmlTag() !== 'metadata';
122 isInsideList: function() {
123 return this.parents().some(function(parent) {
124 return parent.is('list');
128 exec: function(method) {
129 var manager = this.data('_wlxmlManager');
131 return manager[method].apply(manager, Array.prototype.slice.call(arguments, 1));
136 // DocumentNodeElement represents an element node from WLXML document rendered inside Canvas
137 var DocumentNodeElement = function(htmlElement, canvas) {
138 DocumentElement.call(this, htmlElement, canvas);
141 $.extend(DocumentNodeElement, {
142 createDOM: function(params, canvas) {
144 .attr('document-node-element', ''),
145 widgetsContainer = $('<div>')
146 .addClass('canvas-widgets')
147 .attr('contenteditable', false),
148 container = $('<div>')
149 .attr('document-element-content', '');
151 dom.append(widgetsContainer, container);
152 // Make sure widgets aren't navigable with arrow keys
153 widgetsContainer.find('*').add(widgetsContainer).attr('tabindex', -1);
155 var element = this.fromHTMLElement(dom[0], canvas);
157 element.setWlxml({tag: params.tag, klass: params.klass});
159 _.keys(params.meta).forEach(function(key) {
160 element.setWlxmlMetaAttr(key, params.meta[key]);
163 element.data('other-attrs', params.others);
165 if(params.rawChildren && params.rawChildren.length) {
166 container.append(params.rawChildren);
167 } else if(params.prepopulateOnEmpty) {
168 element.append(DocumentTextElement.create({text: ''}));
173 create: function(params, canvas) {
174 return this.fromHTMLElement(this.createDOM(params, canvas)[0], canvas);
177 fromHTMLElement: function(htmlElement, canvas) {
178 return new this(htmlElement, canvas);
182 var manipulate = function(e, params, action) {
184 if(params instanceof DocumentElement) {
187 element = DocumentElement.create(params);
189 var target = (action === 'append' || action === 'prepend') ? e._container() : e.dom();
190 target[action](element.dom());
194 DocumentNodeElement.prototype = new DocumentElement();
197 $.extend(DocumentNodeElement.prototype, {
198 _container: function() {
199 return this.dom().children('[document-element-content]');
202 var parent = this.parent();
206 var parentChildren = parent.children(),
207 myIdx = parent.childIndex(this);
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();
220 var dom = this.dom(),
221 args = Array.prototype.slice.call(arguments, 0);
222 if(args.length === 2 && args[1] === undefined)
223 return dom.removeData(args[0]);
224 return dom.data.apply(dom, arguments);
226 toXML: function(level) {
227 var node = $('<' + this.getWlxmlTag() + '>');
229 if(this.getWlxmlClass())
230 node.attr('class', this.getWlxmlClass());
231 var meta = this.getWlxmlMetaAttrs();
232 meta.forEach(function(attr) {
234 node.attr('meta-' + attr.name, attr.value);
236 _.keys(this.data('other-attrs') || {}).forEach(function(key) {
237 node.attr(key, this.data('other-attrs')[key]);
240 var addFormatting = function() {
241 var toret = $('<div>');
242 var formattings = {};
244 if(this.data('orig-before') !== undefined) {
245 if(this.data('orig-before')) {
246 toret.prepend(document.createTextNode(this.data('orig-before')));
248 } else if(level && this.getWlxmlTag() !== 'span') {
249 toret.append('\n' + (new Array(level * 2 + 1)).join(' '));
254 if(this.data('orig-after')) {
255 toret.append(document.createTextNode(this.data('orig-after')));
259 if(this.data('orig-begin')) {
260 node.prepend(this.data('orig-begin'));
261 formattings.begin = true;
264 if(this.data('orig-end') !== undefined) {
265 if(this.data('orig-end')) {
266 node.append(this.data('orig-end'));
268 } else if(this.getWlxmlTag() !== 'span' && children.length){
269 node.append('\n' + (new Array(level * 2 + 1)).join(' '));
272 return {parts: toret.contents(), formattings: formattings};
277 var children = this.children(),
280 var formatting = addFormatting(node);
282 for(var i = children.length - 1; i >= 0; i--) {
283 childParts = children[i].toXML(level + 1);
284 if(typeof childParts === 'string')
285 childParts = [document.createTextNode(childParts)];
287 if(formatting.formattings.begin) {
288 $(node.contents()[0]).after(childParts);
290 node.prepend(childParts);
292 return formatting.parts;
294 append: function(params) {
295 if(params.tag !== 'span')
296 this.data('orig-end', undefined);
297 return manipulate(this, params, 'append');
299 prepend: function(params) {
300 return manipulate(this, params, 'prepend');
302 before: function(params) {
303 return manipulate(this, params, 'before');
306 after: function(params) {
307 return manipulate(this, params, 'after');
309 children: function() {
311 if(this instanceof DocumentTextElement)
315 var elementContent = this._container().contents();
317 elementContent.each(function(idx) {
318 var childElement = DocumentElement.fromHTMLElement(this, element.canvas);
319 if(childElement === undefined)
321 if(idx === 0 && elementContent.length > 1 && elementContent[1].nodeType === Node.ELEMENT_NODE && (childElement instanceof DocumentTextElement) && $.trim($(this).text()) === '')
323 if(idx > 0 && childElement instanceof DocumentTextElement) {
324 if(toret[toret.length-1] instanceof DocumentNodeElement && $.trim($(this).text()) === '')
327 toret.push(childElement);
331 childIndex: function(child) {
332 var children = this.children(),
334 children.forEach(function(c, idx) {
335 if(c.sameNode(child)) {
342 getWlxmlTag: function() {
343 return this._container().attr('wlxml-tag');
345 setWlxmlTag: function(tag) {
346 if(tag === this.getWlxmlTag())
349 this._container().attr('wlxml-tag', tag);
350 if(!this.__updatingWlxml)
351 this._updateWlxmlManager();
353 getWlxmlClass: function() {
354 var klass = this._container().attr('wlxml-class');
356 return klass.replace(/-/g, '.');
359 setWlxmlClass: function(klass) {
360 if(klass === this.getWlxmlClass())
363 this.getWlxmlMetaAttrs().forEach(function(attr) {
364 if(!classAttributes.hasMetaAttr(klass, attr.name))
365 this.dom().removeAttr('wlxml-meta-' + attr.name);
369 this._container().attr('wlxml-class', klass.replace(/\./g, '-'));
371 this._container().removeAttr('wlxml-class');
372 if(!this.__updatingWlxml)
373 this._updateWlxmlManager();
375 setWlxml: function(params) {
376 this.__updatingWlxml = true;
377 if(params.tag !== undefined)
378 this.setWlxmlTag(params.tag);
379 if(params.klass !== undefined)
380 this.setWlxmlClass(params.klass);
381 this._updateWlxmlManager();
382 this.__updatingWlxml = false;
384 _updateWlxmlManager: function() {
385 var manager = wlxmlManagers.getFor(this);
386 this.data('_wlxmlManager', manager);
390 if(what === 'list' && _.contains(['list.items', 'list.items.enum'], this.getWlxmlClass()))
395 getWlxmlMetaAttr: function(attr) {
396 return this.dom().attr('wlxml-meta-'+attr);
399 getWlxmlMetaAttrs: function() {
401 var attrList = classAttributes.getMetaAttrsList(this.getWlxmlClass());
402 attrList.all.forEach(function(attr) {
403 toret.push({name: attr.name, value: this.getWlxmlMetaAttr(attr.name) || ''});
408 setWlxmlMetaAttr: function(attr, value) {
409 this.dom().attr('wlxml-meta-'+attr, value);
412 toggleLabel: function(toggle) {
413 var displayCss = toggle ? 'inline-block' : 'none';
414 var label = this.dom().children('.canvas-widgets').find('.canvas-widget-label');
415 label.css('display', displayCss);
416 this.toggleHighlight(toggle);
419 toggleHighlight: function(toggle) {
420 this._container().toggleClass('highlighted-element', toggle);
423 toggle: function(toggle) {
424 var mng = this.data('_wlxmlManager');
432 // DocumentNodeElement represents a text node from WLXML document rendered inside Canvas
433 var DocumentTextElement = function(htmlElement, canvas) {
434 DocumentElement.call(this, htmlElement, canvas);
437 $.extend(DocumentTextElement, {
438 createDOM: function(params) {
440 .attr('document-text-element', '')
441 .text(params.text || utils.unicode.ZWS);
444 create: function(params, canvas) {
445 return this.fromHTMLElement(this.createDOM(params)[0]);
448 fromHTMLElement: function(htmlElement, canvas) {
449 return new this(htmlElement, canvas);
451 isContentContainer: function(htmlElement) {
452 return htmlElement.nodeType === Node.TEXT_NODE && $(htmlElement).parent().is('[document-text-element]');
456 DocumentTextElement.prototype = new DocumentElement();
458 $.extend(DocumentTextElement.prototype, {
459 toXML: function(parent) {
460 return this.getText();
462 _setupDOMHandler: function(htmlElement) {
463 var $element = $(htmlElement);
464 if(htmlElement.nodeType === Node.TEXT_NODE)
465 this.$element = $element.parent();
467 this.$element = $element;
474 setText: function(text) {
475 this.dom().contents()[0].data = text;
477 appendText: function(text) {
478 this.dom().contents()[0].data += text;
480 getText: function() {
481 return this.dom().text().replace(utils.unicode.ZWS, '');
483 isEmpty: function() {
484 // Having at least Zero Width Space is guaranteed be Content Observer
485 return this.dom().contents()[0].data === utils.unicode.ZWS;
487 after: function(params) {
488 if(params instanceof DocumentTextElement || params.text)
491 if(params instanceof DocumentNodeElement) {
494 element = DocumentNodeElement.create(params, this.canvas);
496 this.dom().wrap('<div>');
497 this.dom().parent().after(element.dom());
501 before: function(params) {
502 if(params instanceof DocumentTextElement || params.text)
505 if(params instanceof DocumentNodeElement) {
508 element = DocumentNodeElement.create(params, this.canvas);
510 this.dom().wrap('<div>');
511 this.dom().parent().before(element.dom());
515 wrapWithNodeElement: function(wlxmlNode) {
516 if(typeof wlxmlNode.start === 'number' && typeof wlxmlNode.end === 'number') {
517 return this.canvas.wrapText({
518 inside: this.parent(),
519 textNodeIdx: this.parent().childIndex(this),
520 offsetStart: Math.min(wlxmlNode.start, wlxmlNode.end),
521 offsetEnd: Math.max(wlxmlNode.start, wlxmlNode.end),
522 _with: {tag: wlxmlNode.tag, klass: wlxmlNode.klass}
525 return DocumentElement.prototype.wrapWithNodeElement.call(this, wlxmlNode);
529 var parent = this.parent(),
531 if(parent.children().length === 1) {
532 toret = parent.parent();
533 var grandParent = parent.parent();
535 var grandParentChildren = grandParent.children(),
536 idx = grandParent.childIndex(parent),
537 prev = idx - 1 > -1 ? grandParentChildren[idx-1] : null,
538 next = idx + 1 < grandParentChildren.length ? grandParentChildren[idx+1] : null;
540 prev = (prev instanceof DocumentTextElement) ? prev : null;
541 next = (next instanceof DocumentTextElement) ? next : null;
544 prev.setText(prev.getText() + this.getText() + next.getText());
546 } else if (prev || next) {
547 var target = prev ? prev : next,
548 newText = prev ? target.getText() + this.getText() : this.getText() + target.getText();
549 target.setText(newText);
560 split: function(params) {
561 var parentElement = this.parent(),
562 myIdx = parentElement.childIndex(this),
563 myCanvas = this.canvas,
565 succeedingChildren = [],
567 prefix = this.getText().substr(0, params.offset),
568 suffix = this.getText().substr(params.offset);
570 parentElement.children().forEach(function(child) {
572 succeedingChildren.push(child);
573 if(child.sameNode(thisElement))
577 if(prefix.length > 0)
578 this.setText(prefix);
582 var newElement = DocumentNodeElement.create({tag: parentElement.getWlxmlTag(), klass: parentElement.getWlxmlClass()}, myCanvas);
583 parentElement.after(newElement);
585 if(suffix.length > 0)
586 newElement.append({text: suffix});
587 succeedingChildren.forEach(function(child) {
588 newElement.append(child);
591 return {first: parentElement, second: newElement};
593 divide: function(params) {
594 var myText = this.getText();
596 if(params.offset === myText.length)
597 return this.after(params);
598 if(params.offset === 0)
599 return this.before(params);
601 var lhsText = myText.substr(0, params.offset),
602 rhsText = myText.substr(params.offset),
603 newElement = DocumentNodeElement.create({tag: params.tag, klass: params.klass}, this.canvas),
604 rhsTextElement = DocumentTextElement.create({text: rhsText});
606 this.setText(lhsText);
607 this.after(newElement);
608 newElement.after(rhsTextElement);
612 toggleHighlight: function() {
613 // do nothing for now
618 DocumentElement: DocumentElement,
619 DocumentNodeElement: DocumentNodeElement,
620 DocumentTextElement: DocumentTextElement