6 'smartxml/transformations'
7 ], function($, _, Backbone, events, transformations) {
12 var TEXT_NODE = Node.TEXT_NODE;
15 var INSERTION = function(implementation) {
16 var toret = function(node) {
17 var insertion = this.getNodeInsertion(node),
18 nodeWasContained = this.document.containsNode(insertion.ofNode),
20 if(!(this.document.containsNode(this))) {
21 nodeParent = insertion.ofNode.parent();
23 implementation.call(this, insertion.ofNode.nativeNode);
24 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode}, nodeParent, nodeWasContained);
25 return insertion.ofNode;
30 var DocumentNode = function(nativeNode, document) {
32 throw new Error('undefined document for a node');
34 this.document = document;
35 this._setNativeNode(nativeNode);
39 $.extend(DocumentNode.prototype, {
41 transform: function(Transformation, args) {
42 var transformation = new Transformation(this.document, this, args);
43 return this.document.transform(transformation);
46 _setNativeNode: function(nativeNode) {
47 this.nativeNode = nativeNode;
48 this._$ = $(nativeNode);
52 var clone = this._$.clone(true, true);
53 // clone.find('*').addBack().each(function() {
55 // if(n.data('canvasElement')) {
56 // n.data('canvasElement', $.extend(true, {}, n.data('canvasElement')));
57 // n.data('canvasElement').$element = n.data('canvasElement').$element.clone(true, true);
60 return this.document.createDocumentNode(clone[0]);
63 getPath: function(ancestor) {
64 var nodePath = [this].concat(this.parents()),
66 ancestor = ancestor || this.document.root;
68 nodePath.some(function(node, i) {
69 if(node.sameNode(ancestor)) {
75 if(idx !== 'undefined') {
76 nodePath = nodePath.slice(0, idx);
78 toret = nodePath.map(function(node) {return node.getIndex(); });
84 return this.document.root.sameNode(this);
88 var parent = this.parent();
90 this.triggerChangeEvent('nodeDetached', {parent: parent});
94 replaceWith: function(node) {
97 return this.document.replaceRoot(node);
99 toret = this.after(node);
104 sameNode: function(otherNode) {
105 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
109 var parentNode = this.nativeNode.parentNode;
110 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
111 return this.document.createDocumentNode(parentNode);
116 parents: function() {
117 var parent = this.parent(),
118 parents = parent ? parent.parents() : [];
120 parents.unshift(parent);
126 var myIdx = this.getIndex();
127 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
134 var myIdx = this.getIndex(),
135 parentContents = this.parent().contents();
136 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
139 isSurroundedByTextElements: function() {
140 var prev = this.prev(),
142 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
145 after: INSERTION(function(nativeNode) {
146 return this._$.after(nativeNode);
149 before: INSERTION(function(nativeNode) {
150 return this._$.before(nativeNode);
153 wrapWith: function(node) {
154 var insertion = this.getNodeInsertion(node);
156 this.before(insertion.ofNode);
158 insertion.ofNode.append(this);
159 return insertion.ofNode;
163 * Removes parent of a node if node has no siblings.
169 var parent = this.parent(),
171 if(parent.contents().length === 1) {
172 grandParent = parent.parent();
173 parent.unwrapContent();
178 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
179 var node = (metaData && metaData.node) ? metaData.node : this,
180 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
181 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
182 this.document.trigger('change', event);
184 if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
185 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
186 this.document.trigger('change', event);
190 getNodeInsertion: function(node) {
191 return this.document.getNodeInsertion(node);
194 getIndex: function() {
198 return this.parent().indexOf(this);
202 var ElementNode = function(nativeNode, document) {
203 DocumentNode.call(this, nativeNode, document);
205 ElementNode.prototype = Object.create(DocumentNode.prototype);
207 $.extend(ElementNode.prototype, {
208 nodeType: Node.ELEMENT_NODE,
212 if(this.parent() && this.isSurroundedByTextElements()) {
214 this.prev().appendText(next.getText());
217 return DocumentNode.prototype.detach.call(this);
220 setData: function(key, value) {
221 if(value !== undefined) {
222 this._$.data(key, value);
224 this._$.removeData(_.keys(this._$.data()));
229 getData: function(key) {
231 return this._$.data(key);
233 return this._$.data();
236 getTagName: function() {
237 return this.nativeNode.tagName.toLowerCase();
240 contents: function(selector) {
242 document = this.document;
244 this._$.children(selector).each(function() {
245 toret.push(document.createDocumentNode(this));
248 this._$.contents().each(function() {
249 toret.push(document.createDocumentNode(this));
255 indexOf: function(node) {
256 return this._$.contents().index(node._$);
259 setTag: function(tagName) {
260 var node = this.document.createDocumentNode({tagName: tagName}),
261 oldTagName = this.getTagName(),
262 myContents = this._$.contents();
264 this.getAttrs().forEach(function(attribute) {
265 node.setAttr(attribute.name, attribute.value, true);
267 node.setData(this.getData());
269 if(this.sameNode(this.document.root)) {
270 defineDocumentProperties(this.document, node._$);
272 this._$.replaceWith(node._$);
273 this._setNativeNode(node._$[0]);
274 this._$.append(myContents);
275 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
278 getAttr: function(name) {
279 return this._$.attr(name);
282 setAttr: function(name, value, silent) {
283 var oldVal = this.getAttr(name);
284 this._$.attr(name, value);
286 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
290 getAttrs: function() {
292 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
293 toret.push(this.nativeNode.attributes[i]);
298 append: INSERTION(function(nativeNode) {
299 this._$.append(nativeNode);
302 prepend: INSERTION(function(nativeNode) {
303 this._$.prepend(nativeNode);
306 insertAtIndex: function(nativeNode, index) {
307 var contents = this.contents();
308 if(index < contents.length) {
309 return contents[index].before(nativeNode);
310 } else if(index === contents.length) {
311 return this.append(nativeNode);
315 unwrapContent: function() {
316 var parent = this.parent();
321 var myContents = this.contents(),
322 myIdx = parent.indexOf(this);
325 if(myContents.length === 0) {
326 return this.detach();
329 var prev = this.prev(),
331 moveLeftRange, moveRightRange, leftMerged;
333 if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
334 prev.appendText(myContents[0].getText());
335 myContents[0].detach();
336 moveLeftRange = true;
342 if(!(leftMerged && myContents.length === 1)) {
343 var lastContents = _.last(myContents);
344 if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
345 next.prependText(lastContents.getText());
346 lastContents.detach();
347 moveRightRange = true;
351 var childrenLength = this.contents().length;
352 this.contents().forEach(function(child) {
359 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
360 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
364 wrapText: function(params) {
365 return this.document._wrapText(_.extend({inside: this}, params));
369 var wrapper = $('<div>');
370 wrapper.append(this._getXMLDOMToDump());
371 return wrapper.html();
374 _getXMLDOMToDump: function() {
379 var TextNode = function(nativeNode, document) {
380 DocumentNode.call(this, nativeNode, document);
382 TextNode.prototype = Object.create(DocumentNode.prototype);
384 $.extend(TextNode.prototype, {
385 nodeType: Node.TEXT_NODE,
387 getText: function() {
388 return this.nativeNode.data;
391 setText: function(text) {
392 //console.log('smartxml: ' + text);
393 this.nativeNode.data = text;
394 this.triggerTextChangeEvent();
397 appendText: function(text) {
398 this.nativeNode.data = this.nativeNode.data + text;
399 this.triggerTextChangeEvent();
402 prependText: function(text) {
403 this.nativeNode.data = text + this.nativeNode.data;
404 this.triggerTextChangeEvent();
407 wrapWith: function(desc) {
408 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
409 return this.document._wrapText({
410 inside: this.parent(),
411 textNodeIdx: this.parent().indexOf(this),
412 offsetStart: Math.min(desc.start, desc.end),
413 offsetEnd: Math.max(desc.start, desc.end),
414 _with: {tagName: desc.tagName, attrs: desc.attrs}
417 return DocumentNode.prototype.wrapWith.call(this, desc);
421 split: function(params) {
422 var parentElement = this.parent(),
424 succeedingChildren = [],
425 prefix = this.getText().substr(0, params.offset),
426 suffix = this.getText().substr(params.offset);
428 parentElement.contents().forEach(function(child) {
430 succeedingChildren.push(child);
432 if(child.sameNode(this)) {
437 if(prefix.length > 0) {
438 this.setText(prefix);
445 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
446 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
447 parentElement.after(newElement);
449 if(suffix.length > 0) {
450 newElement.append({text: suffix});
452 succeedingChildren.forEach(function(child) {
453 newElement.append(child);
456 return {first: parentElement, second: newElement};
459 triggerTextChangeEvent: function() {
460 var event = new events.ChangeEvent('nodeTextChange', {node: this});
461 this.document.trigger('change', event);
466 var parseXML = function(xml) {
467 return $($.trim(xml))[0];
470 var registerTransformation = function(desc, name, target) {
471 var Transformation = transformations.createContextTransformation(desc, name);
472 target[name] = function(args) {
474 return instance.transform(Transformation, args);
478 var registerMethod = function(methodName, method, target) {
479 if(target[methodName]) {
480 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
481 .replace('{target}', target)
482 .replace('{methodName}', methodName)
485 target[methodName] = method;
489 var Document = function(xml) {
493 this._transformationLevel = 0;
495 this._nodeMethods = {};
496 this._textNodeMethods = {};
497 this._elementNodeMethods = {};
498 this._nodeTransformations = {};
501 $.extend(Document.prototype, Backbone.Events, {
502 ElementNodeFactory: ElementNode,
503 TextNodeFactory: TextNode,
505 createDocumentNode: function(from) {
506 if(!(from instanceof Node)) {
507 if(from.text !== undefined) {
508 /* globals document */
509 from = document.createTextNode(from.text);
511 var node = $('<' + from.tagName + '>');
513 _.keys(from.attrs || {}).forEach(function(key) {
514 node.attr(key, from.attrs[key]);
520 var Factory, typeMethods;
521 if(from.nodeType === Node.TEXT_NODE) {
522 Factory = this.TextNodeFactory;
523 typeMethods = this._textNodeMethods;
524 } else if(from.nodeType === Node.ELEMENT_NODE) {
525 Factory = this.ElementNodeFactory;
526 typeMethods = this._elementNodeMethods;
528 var toret = new Factory(from, this);
529 _.extend(toret, this._nodeMethods);
530 _.extend(toret, typeMethods);
531 _.extend(toret, this._nodeTransformations);
535 loadXML: function(xml, options) {
536 options = options || {};
537 defineDocumentProperties(this, $(parseXML(xml)));
538 if(!options.silent) {
539 this.trigger('contentSet');
544 return this.root.toXML();
547 containsNode: function(node) {
548 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
551 wrapNodes: function(params) {
552 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
553 throw new Error('Wrapping non-sibling nodes not supported.');
556 var parent = params.node1.parent(),
557 parentContents = parent.contents(),
558 wrapper = this.createDocumentNode({
559 tagName: params._with.tagName,
560 attrs: params._with.attrs}),
561 idx1 = parent.indexOf(params.node1),
562 idx2 = parent.indexOf(params.node2);
570 var insertingMethod, insertingTarget;
572 insertingMethod = 'prepend';
573 insertingTarget = parent;
575 insertingMethod = 'after';
576 insertingTarget = parentContents[idx1-1];
579 for(var i = idx1; i <= idx2; i++) {
580 wrapper.append(parentContents[i].detach());
583 insertingTarget[insertingMethod](wrapper);
587 getSiblingParents: function(params) {
588 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
589 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
590 noSiblingParents = null;
592 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
593 return noSiblingParents;
597 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
598 if(parents1[i].sameNode(parents2[i])) {
603 return {node1: parents1[i], node2: parents2[i]};
606 _wrapText: function(params) {
607 params = _.extend({textNodeIdx: 0}, params);
608 if(typeof params.textNodeIdx === 'number') {
609 params.textNodeIdx = [params.textNodeIdx];
612 var contentsInside = params.inside.contents(),
613 idx1 = Math.min.apply(Math, params.textNodeIdx),
614 idx2 = Math.max.apply(Math, params.textNodeIdx),
615 textNode1 = contentsInside[idx1],
616 textNode2 = contentsInside[idx2],
617 sameNode = textNode1.sameNode(textNode2),
618 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
619 prefixInside = textNode1.getText().substr(params.offsetStart),
620 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
621 suffixOutside = textNode2.getText().substr(params.offsetEnd)
624 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
625 throw new Error('Wrapping text in non-sibling text nodes not supported.');
628 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
629 textNode1.after(wrapperElement);
632 if(prefixOutside.length > 0) {
633 wrapperElement.before({text:prefixOutside});
636 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
637 wrapperElement.append({text: core});
640 if(prefixInside.length > 0) {
641 wrapperElement.append({text: prefixInside});
643 for(var i = idx1 + 1; i < idx2; i++) {
644 wrapperElement.append(contentsInside[i]);
646 if(suffixInside.length > 0) {
647 wrapperElement.append({text: suffixInside});
650 if(suffixOutside.length > 0) {
651 wrapperElement.after({text: suffixOutside});
653 return wrapperElement;
656 trigger: function() {
657 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
658 Backbone.Events.trigger.apply(this, arguments);
661 getNodeInsertion: function(node) {
663 if(node instanceof DocumentNode) {
664 insertion.ofNode = node;
665 insertion.insertsNew = !this.containsNode(node);
667 insertion.ofNode = this.createDocumentNode(node);
668 insertion.insertsNew = true;
673 replaceRoot: function(node) {
674 var insertion = this.getNodeInsertion(node);
676 defineDocumentProperties(this, insertion.ofNode._$);
677 insertion.ofNode.triggerChangeEvent('nodeAdded');
678 return insertion.ofNode;
681 registerMethod: function(methodName, method, dstName) {
685 documentNode: doc._nodeMethods,
686 textNode: doc._textNodeMethods,
687 elementNode: doc._elementNodeMethods
689 registerMethod(methodName, method, destination);
692 registerDocumentTransformation: function(desc, name) {
693 registerTransformation(desc, name, this);
696 registerNodeTransformation: function(desc, name) {
697 registerTransformation(desc, name, this._nodeTransformations);
700 registerExtension: function(extension) {
703 existingPropertyNames = _.values(this);
705 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
706 var dstExtension = extension[dstName];
708 if(dstExtension.methods) {
709 _.pairs(dstExtension.methods).forEach(function(pair) {
710 var methodName = pair[0],
713 doc.registerMethod(methodName, method, dstName);
718 if(dstExtension.transformations) {
719 _.pairs(dstExtension.transformations).forEach(function(pair) {
723 operation = {document: 'registerDocumentTransformation', documentNode: 'registerNodeTransformation'}[dstName];
724 doc[operation](desc, name);
731 transform: function(Transformation, args) {
732 //console.log('transform');
733 var toret, transformation;
735 if(typeof Transformation === 'function') {
736 transformation = new Transformation(this, this, args);
738 transformation = Transformation;
741 this._transformationLevel++;
742 toret = transformation.run();
743 if(this._transformationLevel === 1) {
744 this.undoStack.push(transformation);
746 this._transformationLevel--;
747 //console.log('clearing redo stack');
751 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
755 var transformation = this.undoStack.pop();
757 transformation.undo();
758 this.redoStack.push(transformation);
762 var transformation = this.redoStack.pop();
764 transformation.run();
765 this.undoStack.push(transformation);
769 getNodeByPath: function(path) {
770 var toret = this.root;
771 path.forEach(function(idx) {
772 toret = toret.contents()[idx];
778 var defineDocumentProperties = function(doc, $document) {
779 Object.defineProperty(doc, 'root', {get: function() {
780 return doc.createDocumentNode($document[0]);
781 }, configurable: true});
782 Object.defineProperty(doc, 'dom', {get: function() {
784 }, configurable: true});
789 documentFromXML: function(xml) {
790 return new Document(xml);
793 elementNodeFromXML: function(xml) {
794 return this.documentFromXML(xml).root;
798 DocumentNode: DocumentNode,
799 ElementNode: ElementNode,