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, leftMerged;
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;
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;
250 var childrenLength = this.children().length;
251 this.children().forEach(function(child) {
258 element1: parent.children()[myIdx + (moveLeftRange ? -1 : 0)],
259 element2: parent.children()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
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);
269 toXML: function(level) {
270 var node = $('<' + this.getWlxmlTag() + '>');
272 if(this.getWlxmlClass())
273 node.attr('class', this.getWlxmlClass());
274 var meta = this.getWlxmlMetaAttrs();
275 meta.forEach(function(attr) {
277 node.attr('meta-' + attr.name, attr.value);
279 _.keys(this.data('other-attrs') || {}).forEach(function(key) {
280 node.attr(key, this.data('other-attrs')[key]);
283 var addFormatting = function() {
284 var toret = $('<div>');
285 var formattings = {};
287 if(this.data('orig-before') !== undefined) {
288 if(this.data('orig-before')) {
289 toret.prepend(document.createTextNode(this.data('orig-before')));
291 } else if(level && this.getWlxmlTag() !== 'span') {
292 toret.append('\n' + (new Array(level * 2 + 1)).join(' '));
297 if(this.data('orig-after')) {
298 toret.append(document.createTextNode(this.data('orig-after')));
302 if(this.data('orig-begin')) {
303 node.prepend(this.data('orig-begin'));
304 formattings.begin = true;
307 if(this.data('orig-end') !== undefined) {
308 if(this.data('orig-end')) {
309 node.append(this.data('orig-end'));
311 } else if(this.getWlxmlTag() !== 'span' && children.length){
312 node.append('\n' + (new Array(level * 2 + 1)).join(' '));
315 return {parts: toret.contents(), formattings: formattings};
320 var children = this.children(),
323 var formatting = addFormatting(node);
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)];
330 if(formatting.formattings.begin) {
331 $(node.contents()[0]).after(childParts);
333 node.prepend(childParts);
335 return formatting.parts;
337 append: function(params) {
338 if(params.tag !== 'span')
339 this.data('orig-end', undefined);
340 return manipulate(this, params, 'append');
342 prepend: function(params) {
343 return manipulate(this, params, 'prepend');
345 before: function(params) {
346 return manipulate(this, params, 'before');
349 after: function(params) {
350 return manipulate(this, params, 'after');
352 children: function() {
354 if(this instanceof DocumentTextElement)
358 var elementContent = this._container().contents();
360 elementContent.each(function(idx) {
361 var childElement = DocumentElement.fromHTMLElement(this, element.canvas);
362 if(childElement === undefined)
364 if(idx === 0 && elementContent.length > 1 && elementContent[1].nodeType === Node.ELEMENT_NODE && (childElement instanceof DocumentTextElement) && $.trim($(this).text()) === '')
366 if(idx > 0 && childElement instanceof DocumentTextElement) {
367 if(toret[toret.length-1] instanceof DocumentNodeElement && $.trim($(this).text()) === '')
370 toret.push(childElement);
374 childIndex: function(child) {
375 var children = this.children(),
377 children.forEach(function(c, idx) {
378 if(c.sameNode(child)) {
385 getWlxmlTag: function() {
386 return this._container().attr('wlxml-tag');
388 setWlxmlTag: function(tag) {
389 if(tag === this.getWlxmlTag())
392 this._container().attr('wlxml-tag', tag);
393 if(!this.__updatingWlxml)
394 this._updateWlxmlManager();
396 getWlxmlClass: function() {
397 var klass = this._container().attr('wlxml-class');
399 return klass.replace(/-/g, '.');
402 setWlxmlClass: function(klass) {
403 if(klass === this.getWlxmlClass())
406 this.getWlxmlMetaAttrs().forEach(function(attr) {
407 if(!classAttributes.hasMetaAttr(klass, attr.name))
408 this.dom().removeAttr('wlxml-meta-' + attr.name);
412 this._container().attr('wlxml-class', klass.replace(/\./g, '-'));
414 this._container().removeAttr('wlxml-class');
415 if(!this.__updatingWlxml)
416 this._updateWlxmlManager();
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;
427 _updateWlxmlManager: function() {
428 var manager = wlxmlManagers.getFor(this);
429 this.data('_wlxmlManager', manager);
433 if(what === 'list' && _.contains(['list.items', 'list.items.enum'], this.getWlxmlClass()))
438 getWlxmlMetaAttr: function(attr) {
439 return this.dom().attr('wlxml-meta-'+attr);
442 getWlxmlMetaAttrs: function() {
444 var attrList = classAttributes.getMetaAttrsList(this.getWlxmlClass());
445 attrList.all.forEach(function(attr) {
446 toret.push({name: attr.name, value: this.getWlxmlMetaAttr(attr.name) || ''});
451 setWlxmlMetaAttr: function(attr, value) {
452 this.dom().attr('wlxml-meta-'+attr, value);
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);
462 toggleHighlight: function(toggle) {
463 this._container().toggleClass('highlighted-element', toggle);
466 toggle: function(toggle) {
467 var mng = this.data('_wlxmlManager');
475 // DocumentNodeElement represents a text node from WLXML document rendered inside Canvas
476 var DocumentTextElement = function(htmlElement, canvas) {
477 DocumentElement.call(this, htmlElement, canvas);
480 $.extend(DocumentTextElement, {
481 createDOM: function(params) {
483 .attr('document-text-element', '')
484 .text(params.text || utils.unicode.ZWS);
487 create: function(params, canvas) {
488 return this.fromHTMLElement(this.createDOM(params)[0]);
491 fromHTMLElement: function(htmlElement, canvas) {
492 return new this(htmlElement, canvas);
494 isContentContainer: function(htmlElement) {
495 return htmlElement.nodeType === Node.TEXT_NODE && $(htmlElement).parent().is('[document-text-element]');
499 DocumentTextElement.prototype = new DocumentElement();
501 $.extend(DocumentTextElement.prototype, {
502 toXML: function(parent) {
503 return this.getText();
505 _setupDOMHandler: function(htmlElement) {
506 var $element = $(htmlElement);
507 if(htmlElement.nodeType === Node.TEXT_NODE)
508 this.$element = $element.parent();
510 this.$element = $element;
517 setText: function(text) {
518 this.dom().contents()[0].data = text;
520 appendText: function(text) {
521 this.dom().contents()[0].data += text;
523 prependText: function(text) {
524 this.dom().contents()[0].data = text + this.dom().contents()[0].data;
526 getText: function() {
527 return this.dom().text().replace(utils.unicode.ZWS, '');
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;
533 after: function(params) {
534 if(params instanceof DocumentTextElement || params.text)
537 if(params instanceof DocumentNodeElement) {
540 element = DocumentNodeElement.create(params, this.canvas);
542 this.dom().wrap('<div>');
543 this.dom().parent().after(element.dom());
547 before: function(params) {
548 if(params instanceof DocumentTextElement || params.text)
551 if(params instanceof DocumentNodeElement) {
554 element = DocumentNodeElement.create(params, this.canvas);
556 this.dom().wrap('<div>');
557 this.dom().parent().before(element.dom());
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}
571 return DocumentElement.prototype.wrapWithNodeElement.call(this, wlxmlNode);
575 var parent = this.parent(),
577 if(parent.children().length === 1) {
578 toret = parent.parent();
579 var grandParent = parent.parent();
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;
586 prev = (prev instanceof DocumentTextElement) ? prev : null;
587 next = (next instanceof DocumentTextElement) ? next : null;
590 prev.setText(prev.getText() + this.getText() + next.getText());
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);
606 split: function(params) {
607 var parentElement = this.parent(),
608 myIdx = parentElement.childIndex(this),
609 myCanvas = this.canvas,
611 succeedingChildren = [],
613 prefix = this.getText().substr(0, params.offset),
614 suffix = this.getText().substr(params.offset);
616 parentElement.children().forEach(function(child) {
618 succeedingChildren.push(child);
619 if(child.sameNode(thisElement))
623 if(prefix.length > 0)
624 this.setText(prefix);
628 var newElement = DocumentNodeElement.create({tag: parentElement.getWlxmlTag(), klass: parentElement.getWlxmlClass()}, myCanvas);
629 parentElement.after(newElement);
631 if(suffix.length > 0)
632 newElement.append({text: suffix});
633 succeedingChildren.forEach(function(child) {
634 newElement.append(child);
637 return {first: parentElement, second: newElement};
639 divide: function(params) {
640 var myText = this.getText();
642 if(params.offset === myText.length)
643 return this.after(params);
644 if(params.offset === 0)
645 return this.before(params);
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});
652 this.setText(lhsText);
653 this.after(newElement);
654 newElement.after(rhsTextElement);
658 toggleHighlight: function() {
659 // do nothing for now
664 DocumentElement: DocumentElement,
665 DocumentNodeElement: DocumentNodeElement,
666 DocumentTextElement: DocumentTextElement