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 $.contains(document.documentElement, this.dom()[0]);
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();
219 unwrapContents: function() {
220 var parent = this.parent();
224 var parentChildren = parent.children(),
225 myChildren = this.children(),
226 myIdx = parent.childIndex(this);
228 if(myChildren.length === 0)
229 return this.detach();
231 var moveLeftRange, moveRightRange;
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;
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;
245 var childrenLength = this.children().length;
246 this.children().forEach(function(child) {
253 element1: parent.children()[myIdx + (moveLeftRange ? -1 : 0)],
254 element2: parent.children()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
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);
264 toXML: function(level) {
265 var node = $('<' + this.getWlxmlTag() + '>');
267 if(this.getWlxmlClass())
268 node.attr('class', this.getWlxmlClass());
269 var meta = this.getWlxmlMetaAttrs();
270 meta.forEach(function(attr) {
272 node.attr('meta-' + attr.name, attr.value);
274 _.keys(this.data('other-attrs') || {}).forEach(function(key) {
275 node.attr(key, this.data('other-attrs')[key]);
278 var addFormatting = function() {
279 var toret = $('<div>');
280 var formattings = {};
282 if(this.data('orig-before') !== undefined) {
283 if(this.data('orig-before')) {
284 toret.prepend(document.createTextNode(this.data('orig-before')));
286 } else if(level && this.getWlxmlTag() !== 'span') {
287 toret.append('\n' + (new Array(level * 2 + 1)).join(' '));
292 if(this.data('orig-after')) {
293 toret.append(document.createTextNode(this.data('orig-after')));
297 if(this.data('orig-begin')) {
298 node.prepend(this.data('orig-begin'));
299 formattings.begin = true;
302 if(this.data('orig-end') !== undefined) {
303 if(this.data('orig-end')) {
304 node.append(this.data('orig-end'));
306 } else if(this.getWlxmlTag() !== 'span' && children.length){
307 node.append('\n' + (new Array(level * 2 + 1)).join(' '));
310 return {parts: toret.contents(), formattings: formattings};
315 var children = this.children(),
318 var formatting = addFormatting(node);
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)];
325 if(formatting.formattings.begin) {
326 $(node.contents()[0]).after(childParts);
328 node.prepend(childParts);
330 return formatting.parts;
332 append: function(params) {
333 if(params.tag !== 'span')
334 this.data('orig-end', undefined);
335 return manipulate(this, params, 'append');
337 prepend: function(params) {
338 return manipulate(this, params, 'prepend');
340 before: function(params) {
341 return manipulate(this, params, 'before');
344 after: function(params) {
345 return manipulate(this, params, 'after');
347 children: function() {
349 if(this instanceof DocumentTextElement)
353 var elementContent = this._container().contents();
355 elementContent.each(function(idx) {
356 var childElement = DocumentElement.fromHTMLElement(this, element.canvas);
357 if(childElement === undefined)
359 if(idx === 0 && elementContent.length > 1 && elementContent[1].nodeType === Node.ELEMENT_NODE && (childElement instanceof DocumentTextElement) && $.trim($(this).text()) === '')
361 if(idx > 0 && childElement instanceof DocumentTextElement) {
362 if(toret[toret.length-1] instanceof DocumentNodeElement && $.trim($(this).text()) === '')
365 toret.push(childElement);
369 childIndex: function(child) {
370 var children = this.children(),
372 children.forEach(function(c, idx) {
373 if(c.sameNode(child)) {
380 getWlxmlTag: function() {
381 return this._container().attr('wlxml-tag');
383 setWlxmlTag: function(tag) {
384 if(tag === this.getWlxmlTag())
387 this._container().attr('wlxml-tag', tag);
388 if(!this.__updatingWlxml)
389 this._updateWlxmlManager();
391 getWlxmlClass: function() {
392 var klass = this._container().attr('wlxml-class');
394 return klass.replace(/-/g, '.');
397 setWlxmlClass: function(klass) {
398 if(klass === this.getWlxmlClass())
401 this.getWlxmlMetaAttrs().forEach(function(attr) {
402 if(!classAttributes.hasMetaAttr(klass, attr.name))
403 this.dom().removeAttr('wlxml-meta-' + attr.name);
407 this._container().attr('wlxml-class', klass.replace(/\./g, '-'));
409 this._container().removeAttr('wlxml-class');
410 if(!this.__updatingWlxml)
411 this._updateWlxmlManager();
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;
422 _updateWlxmlManager: function() {
423 var manager = wlxmlManagers.getFor(this);
424 this.data('_wlxmlManager', manager);
428 if(what === 'list' && _.contains(['list.items', 'list.items.enum'], this.getWlxmlClass()))
433 getWlxmlMetaAttr: function(attr) {
434 return this.dom().attr('wlxml-meta-'+attr);
437 getWlxmlMetaAttrs: function() {
439 var attrList = classAttributes.getMetaAttrsList(this.getWlxmlClass());
440 attrList.all.forEach(function(attr) {
441 toret.push({name: attr.name, value: this.getWlxmlMetaAttr(attr.name) || ''});
446 setWlxmlMetaAttr: function(attr, value) {
447 this.dom().attr('wlxml-meta-'+attr, value);
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);
457 toggleHighlight: function(toggle) {
458 this._container().toggleClass('highlighted-element', toggle);
461 toggle: function(toggle) {
462 var mng = this.data('_wlxmlManager');
470 // DocumentNodeElement represents a text node from WLXML document rendered inside Canvas
471 var DocumentTextElement = function(htmlElement, canvas) {
472 DocumentElement.call(this, htmlElement, canvas);
475 $.extend(DocumentTextElement, {
476 createDOM: function(params) {
478 .attr('document-text-element', '')
479 .text(params.text || utils.unicode.ZWS);
482 create: function(params, canvas) {
483 return this.fromHTMLElement(this.createDOM(params)[0]);
486 fromHTMLElement: function(htmlElement, canvas) {
487 return new this(htmlElement, canvas);
489 isContentContainer: function(htmlElement) {
490 return htmlElement.nodeType === Node.TEXT_NODE && $(htmlElement).parent().is('[document-text-element]');
494 DocumentTextElement.prototype = new DocumentElement();
496 $.extend(DocumentTextElement.prototype, {
497 toXML: function(parent) {
498 return this.getText();
500 _setupDOMHandler: function(htmlElement) {
501 var $element = $(htmlElement);
502 if(htmlElement.nodeType === Node.TEXT_NODE)
503 this.$element = $element.parent();
505 this.$element = $element;
512 setText: function(text) {
513 this.dom().contents()[0].data = text;
515 appendText: function(text) {
516 this.dom().contents()[0].data += text;
518 prependText: function(text) {
519 this.dom().contents()[0].data = text + this.dom().contents()[0].data;
521 getText: function() {
522 return this.dom().text().replace(utils.unicode.ZWS, '');
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;
528 after: function(params) {
529 if(params instanceof DocumentTextElement || params.text)
532 if(params instanceof DocumentNodeElement) {
535 element = DocumentNodeElement.create(params, this.canvas);
537 this.dom().wrap('<div>');
538 this.dom().parent().after(element.dom());
542 before: function(params) {
543 if(params instanceof DocumentTextElement || params.text)
546 if(params instanceof DocumentNodeElement) {
549 element = DocumentNodeElement.create(params, this.canvas);
551 this.dom().wrap('<div>');
552 this.dom().parent().before(element.dom());
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}
566 return DocumentElement.prototype.wrapWithNodeElement.call(this, wlxmlNode);
570 var parent = this.parent(),
572 if(parent.children().length === 1) {
573 toret = parent.parent();
574 var grandParent = parent.parent();
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;
581 prev = (prev instanceof DocumentTextElement) ? prev : null;
582 next = (next instanceof DocumentTextElement) ? next : null;
585 prev.setText(prev.getText() + this.getText() + next.getText());
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);
601 split: function(params) {
602 var parentElement = this.parent(),
603 myIdx = parentElement.childIndex(this),
604 myCanvas = this.canvas,
606 succeedingChildren = [],
608 prefix = this.getText().substr(0, params.offset),
609 suffix = this.getText().substr(params.offset);
611 parentElement.children().forEach(function(child) {
613 succeedingChildren.push(child);
614 if(child.sameNode(thisElement))
618 if(prefix.length > 0)
619 this.setText(prefix);
623 var newElement = DocumentNodeElement.create({tag: parentElement.getWlxmlTag(), klass: parentElement.getWlxmlClass()}, myCanvas);
624 parentElement.after(newElement);
626 if(suffix.length > 0)
627 newElement.append({text: suffix});
628 succeedingChildren.forEach(function(child) {
629 newElement.append(child);
632 return {first: parentElement, second: newElement};
634 divide: function(params) {
635 var myText = this.getText();
637 if(params.offset === myText.length)
638 return this.after(params);
639 if(params.offset === 0)
640 return this.before(params);
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});
647 this.setText(lhsText);
648 this.after(newElement);
649 newElement.after(rhsTextElement);
653 toggleHighlight: function() {
654 // do nothing for now
659 DocumentElement: DocumentElement,
660 DocumentNodeElement: DocumentNodeElement,
661 DocumentTextElement: DocumentTextElement