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(name, args) {
42 var Transformation = this.transformations.get(name),
45 transformation = new Transformation(this.document, this, args);
47 return this.document.transform(transformation);
50 _setNativeNode: function(nativeNode) {
51 this.nativeNode = nativeNode;
52 this._$ = $(nativeNode);
56 var clone = this._$.clone(true, true);
57 // clone.find('*').addBack().each(function() {
59 // if(n.data('canvasElement')) {
60 // n.data('canvasElement', $.extend(true, {}, n.data('canvasElement')));
61 // n.data('canvasElement').$element = n.data('canvasElement').$element.clone(true, true);
64 return this.document.createDocumentNode(clone[0]);
67 getPath: function(ancestor) {
68 var nodePath = [this].concat(this.parents()),
70 ancestor = ancestor || this.document.root;
72 nodePath.some(function(node, i) {
73 if(node.sameNode(ancestor)) {
79 if(idx !== 'undefined') {
80 nodePath = nodePath.slice(0, idx);
82 toret = nodePath.map(function(node) {return node.getIndex(); });
88 return this.document.root.sameNode(this);
92 var parent = this.parent();
94 this.triggerChangeEvent('nodeDetached', {parent: parent});
98 replaceWith: function(node) {
101 return this.document.replaceRoot(node);
103 toret = this.after(node);
108 sameNode: function(otherNode) {
109 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
113 var parentNode = this.nativeNode.parentNode;
114 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
115 return this.document.createDocumentNode(parentNode);
120 parents: function() {
121 var parent = this.parent(),
122 parents = parent ? parent.parents() : [];
124 parents.unshift(parent);
130 var myIdx = this.getIndex();
131 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
138 var myIdx = this.getIndex(),
139 parentContents = this.parent().contents();
140 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
143 isSurroundedByTextElements: function() {
144 var prev = this.prev(),
146 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
149 after: INSERTION(function(nativeNode) {
150 return this._$.after(nativeNode);
153 before: INSERTION(function(nativeNode) {
154 return this._$.before(nativeNode);
157 wrapWith: function(node) {
158 var insertion = this.getNodeInsertion(node);
160 this.before(insertion.ofNode);
162 insertion.ofNode.append(this);
163 return insertion.ofNode;
167 * Removes parent of a node if node has no siblings.
173 var parent = this.parent(),
175 if(parent.contents().length === 1) {
176 grandParent = parent.parent();
177 parent.unwrapContent();
182 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
183 var node = (metaData && metaData.node) ? metaData.node : this,
184 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
185 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
186 this.document.trigger('change', event);
188 if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
189 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
190 this.document.trigger('change', event);
194 getNodeInsertion: function(node) {
195 return this.document.getNodeInsertion(node);
198 getIndex: function() {
202 return this.parent().indexOf(this);
206 var ElementNode = function(nativeNode, document) {
207 DocumentNode.call(this, nativeNode, document);
209 ElementNode.prototype = Object.create(DocumentNode.prototype);
211 $.extend(ElementNode.prototype, {
212 nodeType: Node.ELEMENT_NODE,
216 if(this.parent() && this.isSurroundedByTextElements()) {
218 this.prev().appendText(next.getText());
221 return DocumentNode.prototype.detach.call(this);
224 setData: function(key, value) {
225 if(value !== undefined) {
226 this._$.data(key, value);
228 this._$.removeData(_.keys(this._$.data()));
233 getData: function(key) {
235 return this._$.data(key);
237 return this._$.data();
240 getTagName: function() {
241 return this.nativeNode.tagName.toLowerCase();
244 contents: function(selector) {
246 document = this.document;
248 this._$.children(selector).each(function() {
249 toret.push(document.createDocumentNode(this));
252 this._$.contents().each(function() {
253 toret.push(document.createDocumentNode(this));
259 indexOf: function(node) {
260 return this._$.contents().index(node._$);
263 setTag: function(tagName) {
264 var node = this.document.createDocumentNode({tagName: tagName}),
265 oldTagName = this.getTagName(),
266 myContents = this._$.contents();
268 this.getAttrs().forEach(function(attribute) {
269 node.setAttr(attribute.name, attribute.value, true);
271 node.setData(this.getData());
273 if(this.sameNode(this.document.root)) {
274 defineDocumentProperties(this.document, node._$);
276 this._$.replaceWith(node._$);
277 this._setNativeNode(node._$[0]);
278 this._$.append(myContents);
279 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
282 getAttr: function(name) {
283 return this._$.attr(name);
286 setAttr: function(name, value, silent) {
287 var oldVal = this.getAttr(name);
288 this._$.attr(name, value);
290 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
294 getAttrs: function() {
296 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
297 toret.push(this.nativeNode.attributes[i]);
302 append: INSERTION(function(nativeNode) {
303 this._$.append(nativeNode);
306 prepend: INSERTION(function(nativeNode) {
307 this._$.prepend(nativeNode);
310 insertAtIndex: function(nativeNode, index) {
311 var contents = this.contents();
312 if(index < contents.length) {
313 return contents[index].before(nativeNode);
314 } else if(index === contents.length) {
315 return this.append(nativeNode);
319 unwrapContent: function() {
320 var parent = this.parent();
325 var myContents = this.contents(),
326 myIdx = parent.indexOf(this);
329 if(myContents.length === 0) {
330 return this.detach();
333 var prev = this.prev(),
335 moveLeftRange, moveRightRange, leftMerged;
337 if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
338 prev.appendText(myContents[0].getText());
339 myContents[0].detach();
340 moveLeftRange = true;
346 if(!(leftMerged && myContents.length === 1)) {
347 var lastContents = _.last(myContents);
348 if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
349 next.prependText(lastContents.getText());
350 lastContents.detach();
351 moveRightRange = true;
355 var childrenLength = this.contents().length;
356 this.contents().forEach(function(child) {
363 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
364 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
368 wrapText: function(params) {
369 return this.document._wrapText(_.extend({inside: this}, params));
373 var wrapper = $('<div>');
374 wrapper.append(this._getXMLDOMToDump());
375 return wrapper.html();
378 _getXMLDOMToDump: function() {
385 // todo - split+append
387 // ElementNode.prototype.transformations.register(transformations.createContextTransformation({
388 // name: 'smartxml.setAttr',
389 // impl: function(args) {
390 // this.setAttr(args.name, args.value);
392 // getChangeRoot: function() {
393 // return this.context;
397 // ElementNode.prototype.transformations.register(transformations.createContextTransformation({
398 // name: 'smartxml.setAttr2',
399 // impl: function(args) {
400 // this.prevAttr = this.getAttr(args.name);
401 // this.setAttr(args.name, args.value);
403 // undo: function(args) {
404 // this.setAttr(args.name, this.prevAttr);
408 // DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
409 // name: 'smartxml.wrapWith',
410 // getChangeRoot: function() {
411 // return this.context.parent();
413 // impl: function(args) {
414 // return this.wrapWith(args);
418 // DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
419 // name: 'smartxml.wrapText',
420 // getChangeRoot: function() {
421 // return this.context;
423 // impl: function(args) {
424 // return this.wrapText(args);
428 // DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
429 // name: 'smartxml.detach',
430 // getChangeRoot: function() {
431 // return this.context.parent();
433 // impl: function(args) {
434 // return this.detach();
440 var TextNode = function(nativeNode, document) {
441 DocumentNode.call(this, nativeNode, document);
443 TextNode.prototype = Object.create(DocumentNode.prototype);
445 $.extend(TextNode.prototype, {
446 nodeType: Node.TEXT_NODE,
448 getText: function() {
449 return this.nativeNode.data;
452 setText: function(text) {
453 //console.log('smartxml: ' + text);
454 this.nativeNode.data = text;
455 this.triggerTextChangeEvent();
458 appendText: function(text) {
459 this.nativeNode.data = this.nativeNode.data + text;
460 this.triggerTextChangeEvent();
463 prependText: function(text) {
464 this.nativeNode.data = text + this.nativeNode.data;
465 this.triggerTextChangeEvent();
468 wrapWith: function(desc) {
469 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
470 return this.document._wrapText({
471 inside: this.parent(),
472 textNodeIdx: this.parent().indexOf(this),
473 offsetStart: Math.min(desc.start, desc.end),
474 offsetEnd: Math.max(desc.start, desc.end),
475 _with: {tagName: desc.tagName, attrs: desc.attrs}
478 return DocumentNode.prototype.wrapWith.call(this, desc);
482 split: function(params) {
483 var parentElement = this.parent(),
485 succeedingChildren = [],
486 prefix = this.getText().substr(0, params.offset),
487 suffix = this.getText().substr(params.offset);
489 parentElement.contents().forEach(function(child) {
491 succeedingChildren.push(child);
493 if(child.sameNode(this)) {
498 if(prefix.length > 0) {
499 this.setText(prefix);
506 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
507 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
508 parentElement.after(newElement);
510 if(suffix.length > 0) {
511 newElement.append({text: suffix});
513 succeedingChildren.forEach(function(child) {
514 newElement.append(child);
517 return {first: parentElement, second: newElement};
520 triggerTextChangeEvent: function() {
521 var event = new events.ChangeEvent('nodeTextChange', {node: this});
522 this.document.trigger('change', event);
527 // TextNode.prototype.transformations.register(transformations.createContextTransformation({
528 // name: 'rng.breakContent',
529 // // impl: function(args) {
530 // // var node = this.context,
531 // // newNodes, emptyNode, emptyText;
532 // // newNodes = node.transform('smartxml.split', {offset: args.offset});
533 // // [newNodes.first, newNodes.second].some(function(newNode) {
534 // // if(!(newNode.contents().length)) {
535 // // newNode.transform('smartxml.append', {text: ''});
536 // // return true; // break
539 // // return _.extend(newNodes, {emptyText: emptyText});
541 // impl: function(args) {
543 // newNodes, emptyNode, emptyText;
544 // newNodes = node.split({offset: args.offset});
545 // [newNodes.first, newNodes.second].some(function(newNode) {
546 // if(!(newNode.contents().length)) {
547 // newNode.append({text: ''});
548 // return true; // break
551 // return _.extend(newNodes, {emptyText: emptyText});
553 // getChangeRoot: function() {
554 // return this.context.parent().parent();
556 // isAllowed: function(args) {
557 // var parent = this.parent();
558 // return !!(parent && parent.parent());
563 // ElementNode.prototype.transformations.register(transformations.createContextTransformation({
564 // name: 'smartxml.setText',
565 // impl: function(args) {
566 // this.setText(args.text);
568 // getChangeRoot: function() {
569 // return this.context;
574 var parseXML = function(xml) {
575 return $($.trim(xml))[0];
578 var Document = function(xml) {
582 this._transformationLevel = 0;
583 this.transformations = new transformations.TransformationStorage();
585 this._nodeMethods = {};
586 this._nodeTransformations = new transformations.TransformationStorage();
589 $.extend(Document.prototype, Backbone.Events, {
590 ElementNodeFactory: ElementNode,
591 TextNodeFactory: TextNode,
593 createDocumentNode: function(from) {
594 if(!(from instanceof Node)) {
595 if(from.text !== undefined) {
596 /* globals document */
597 from = document.createTextNode(from.text);
599 var node = $('<' + from.tagName + '>');
601 _.keys(from.attrs || {}).forEach(function(key) {
602 node.attr(key, from.attrs[key]);
609 if(from.nodeType === Node.TEXT_NODE) {
610 Factory = this.TextNodeFactory;
611 } else if(from.nodeType === Node.ELEMENT_NODE) {
612 Factory = this.ElementNodeFactory;
614 var toret = new Factory(from, this);
615 _.extend(toret, this._nodeMethods);
616 toret.transformations = this._nodeTransformations;
620 loadXML: function(xml, options) {
621 options = options || {};
622 defineDocumentProperties(this, $(parseXML(xml)));
623 if(!options.silent) {
624 this.trigger('contentSet');
629 return this.root.toXML();
632 containsNode: function(node) {
633 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
636 wrapNodes: function(params) {
637 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
638 throw new Error('Wrapping non-sibling nodes not supported.');
641 var parent = params.node1.parent(),
642 parentContents = parent.contents(),
643 wrapper = this.createDocumentNode({
644 tagName: params._with.tagName,
645 attrs: params._with.attrs}),
646 idx1 = parent.indexOf(params.node1),
647 idx2 = parent.indexOf(params.node2);
655 var insertingMethod, insertingTarget;
657 insertingMethod = 'prepend';
658 insertingTarget = parent;
660 insertingMethod = 'after';
661 insertingTarget = parentContents[idx1-1];
664 for(var i = idx1; i <= idx2; i++) {
665 wrapper.append(parentContents[i].detach());
668 insertingTarget[insertingMethod](wrapper);
672 getSiblingParents: function(params) {
673 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
674 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
675 noSiblingParents = null;
677 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
678 return noSiblingParents;
682 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
683 if(parents1[i].sameNode(parents2[i])) {
688 return {node1: parents1[i], node2: parents2[i]};
691 _wrapText: function(params) {
692 params = _.extend({textNodeIdx: 0}, params);
693 if(typeof params.textNodeIdx === 'number') {
694 params.textNodeIdx = [params.textNodeIdx];
697 var contentsInside = params.inside.contents(),
698 idx1 = Math.min.apply(Math, params.textNodeIdx),
699 idx2 = Math.max.apply(Math, params.textNodeIdx),
700 textNode1 = contentsInside[idx1],
701 textNode2 = contentsInside[idx2],
702 sameNode = textNode1.sameNode(textNode2),
703 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
704 prefixInside = textNode1.getText().substr(params.offsetStart),
705 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
706 suffixOutside = textNode2.getText().substr(params.offsetEnd)
709 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
710 throw new Error('Wrapping text in non-sibling text nodes not supported.');
713 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
714 textNode1.after(wrapperElement);
717 if(prefixOutside.length > 0) {
718 wrapperElement.before({text:prefixOutside});
721 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
722 wrapperElement.append({text: core});
725 if(prefixInside.length > 0) {
726 wrapperElement.append({text: prefixInside});
728 for(var i = idx1 + 1; i < idx2; i++) {
729 wrapperElement.append(contentsInside[i]);
731 if(suffixInside.length > 0) {
732 wrapperElement.append({text: suffixInside});
735 if(suffixOutside.length > 0) {
736 wrapperElement.after({text: suffixOutside});
738 return wrapperElement;
741 trigger: function() {
742 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
743 Backbone.Events.trigger.apply(this, arguments);
746 getNodeInsertion: function(node) {
748 if(node instanceof DocumentNode) {
749 insertion.ofNode = node;
750 insertion.insertsNew = !this.containsNode(node);
752 insertion.ofNode = this.createDocumentNode(node);
753 insertion.insertsNew = true;
758 replaceRoot: function(node) {
759 var insertion = this.getNodeInsertion(node);
761 defineDocumentProperties(this, insertion.ofNode._$);
762 insertion.ofNode.triggerChangeEvent('nodeAdded');
763 return insertion.ofNode;
766 registerMethod: function(methodName, method) {
767 if(this[methodName]) {
768 throw new Error('Cannot extend document with method name {methodName}. Name already exists.'
769 .replace('{methodName}', methodName)
772 this[methodName] = method;
775 registerTransformation: function(Transformation) {
776 return this.transformations.register(Transformation);
779 registerNodeMethod: function(methodName, method) {
780 if(this._nodeMethods[methodName]) {
781 throw new Error('Cannot extend document with method name {methodName}. Name already exists.'
782 .replace('{methodName}', methodName)
785 this._nodeMethods[methodName] = method;
788 registerNodeTransformation: function(Transformation) {
789 this._nodeTransformations.register(Transformation);
792 registerExtension: function(extension) {
795 existingPropertyNames = _.values(this);
797 ['document', 'documentNode'].forEach(function(dstName) {
798 var dstExtension = extension[dstName];
800 if(dstExtension.methods) {
801 _.pairs(dstExtension.methods).forEach(function(pair) {
802 var methodName = pair[0],
805 operation = {document: 'registerMethod', documentNode: 'registerNodeMethod'}[dstName];
806 doc[operation](methodName, method);
811 if(dstExtension.transformations) {
812 _.pairs(dstExtension.transformations).forEach(function(pair) {
816 operation = {document: 'registerTransformation', documentNode: 'registerNodeTransformation'}[dstName];
817 doc[operation](transformations.createContextTransformation(desc, name));
824 transform: function(transformation, args) {
825 //console.log('transform');
826 var Transformation, toret;
827 if(typeof transformation === 'string') {
828 Transformation = this.transformations.get(transformation);
830 transformation = new Transformation(this, this, args);
834 this._transformationLevel++;
835 toret = transformation.run();
836 if(this._transformationLevel === 1) {
837 this.undoStack.push(transformation);
839 this._transformationLevel--;
840 //console.log('clearing redo stack');
844 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
848 var transformation = this.undoStack.pop();
850 transformation.undo();
851 this.redoStack.push(transformation);
855 var transformation = this.redoStack.pop();
857 transformation.run();
858 this.undoStack.push(transformation);
862 getNodeByPath: function(path) {
863 var toret = this.root;
864 path.forEach(function(idx) {
865 toret = toret.contents()[idx];
871 var defineDocumentProperties = function(doc, $document) {
872 Object.defineProperty(doc, 'root', {get: function() {
873 return doc.createDocumentNode($document[0]);
874 }, configurable: true});
875 Object.defineProperty(doc, 'dom', {get: function() {
877 }, configurable: true});
880 // Document.prototype.transformations.register(transformations.createContextTransformation({
881 // name: 'smartxml.wrapNodes',
882 // // init: function() {
885 // // getChangeRoot: function() {
886 // // return this.context;
888 // impl: function(args) {
889 // this.wrapNodes(args);
896 documentFromXML: function(xml) {
897 return new Document(xml);
900 elementNodeFromXML: function(xml) {
901 return this.documentFromXML(xml).root;
905 DocumentNode: DocumentNode,
906 ElementNode: ElementNode,