6 'smartxml/transformations',
9 ], function($, _, Backbone, events, transformations, coreTransformations, fragments) {
15 var privateKey = '_smartxml';
17 var DocumentNode = function(nativeNode, document) {
19 throw new Error('undefined document for a node');
21 this.document = document;
23 this._setNativeNode(nativeNode);
27 $.extend(DocumentNode.prototype, {
29 getProperty: function(propName) {
30 var toret = this.object[propName];
31 if(toret && _.isFunction(toret)) {
32 toret = toret.call(this);
37 transform: function(Transformation, args) {
38 var transformation = new Transformation(this.document, this, args);
39 return this.document.transform(transformation);
42 _setNativeNode: function(nativeNode) {
43 this.nativeNode = nativeNode;
44 this._$ = $(nativeNode);
48 var clone = this._$.clone(true, true),
50 clone.find('*').addBack().each(function() {
52 clonedData = $(this).data();
53 $(el).removeData(privateKey);
54 _.pairs(clonedData).forEach(function(pair) {
57 if(_.isFunction(value.clone)) {
58 clonedData[key] = value.clone(node.document.createDocumentNode(el));
62 return this.document.createDocumentNode(clone[0]);
65 getPath: function(ancestor) {
66 if(!(this.document.containsNode(this))) {
70 var nodePath = [this].concat(this.parents()),
72 ancestor = ancestor || this.document.root;
74 nodePath.some(function(node, i) {
75 if(node.sameNode(ancestor)) {
81 if(idx !== undefined) {
82 nodePath = nodePath.slice(0, idx);
84 toret = nodePath.map(function(node) {return node.getIndex(); });
90 return this.document.root.sameNode(this);
93 isInDocument: function() {
94 return this.document.containsNode(this);
97 isSiblingOf: function(node) {
98 return node && this.parent().sameNode(node.parent());
101 sameNode: function(otherNode) {
102 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
106 var parentNode = this.nativeNode.parentNode;
107 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
108 return this.document.createDocumentNode(parentNode);
113 parents: function() {
114 var parent = this.parent(),
115 parents = parent ? parent.parents() : [];
117 parents.unshift(parent);
123 var myIdx = this.getIndex();
124 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
131 var myIdx = this.getIndex(),
132 parentContents = this.parent().contents();
133 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
136 isSurroundedByTextNodes: function() {
137 return this.isPrecededByTextNode() && this.isFollowedByTextNode();
140 isPrecededByTextNode: function() {
141 var prev = this.prev();
142 return prev && prev.nodeType === Node.TEXT_NODE;
145 isFollowedByTextNode: function() {
146 var next = this.next();
147 return next && next.nodeType === Node.TEXT_NODE;
150 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
151 var node = (metaData && metaData.node) ? metaData.node : this,
152 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
153 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
154 this.document.trigger('change', event);
156 if(type === 'nodeAdded' && !this.document.containsNode(this) && nodeWasContained) {
157 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
158 this.document.trigger('change', event);
162 getNodeInsertion: function(node) {
163 return this.document.getNodeInsertion(node);
166 getIndex: function() {
173 parent = this.parent();
174 return parent ? parent.indexOf(this) : undefined;
177 getNearestElementNode: function() {
178 return this.nodeType === Node.ELEMENT_NODE ? this : this.parent();
183 var ElementNode = function(nativeNode, document) {
184 DocumentNode.call(this, nativeNode, document);
185 $(nativeNode).data(privateKey, {node: this});
187 ElementNode.prototype = Object.create(DocumentNode.prototype);
189 $.extend(ElementNode.prototype, {
190 nodeType: Node.ELEMENT_NODE,
192 setData: function(arg1, arg2) {
193 if(arguments.length === 2) {
194 if(_.isUndefined(arg2)) {
195 this._$.removeData(arg1);
197 this._$.data(arg1, arg2);
200 this._$.removeData(_.keys(this._$.data()));
205 getData: function(key) {
207 return this._$.data(key);
209 var toret = _.clone(this._$.data());
210 delete toret[privateKey];
214 getTagName: function() {
215 return this.nativeNode.tagName.toLowerCase();
218 contents: function(selector) {
220 document = this.document;
222 this._$.children(selector).each(function() {
223 toret.push(document.createDocumentNode(this));
226 this._$.contents().each(function() {
227 toret.push(document.createDocumentNode(this));
233 indexOf: function(node) {
234 return this._$.contents().index(node._$);
237 getAttr: function(name) {
238 return this._$.attr(name);
241 getAttrs: function() {
243 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
244 toret.push(this.nativeNode.attributes[i]);
249 containsNode: function(node) {
250 return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
253 getFirstTextNode: function() {
254 return this._getTextNode('first');
257 getLastTextNode: function() {
258 return this._getTextNode('last');
261 _getTextNode: function(which) {
262 var contents = this.contents(),
264 if(which === 'last') {
265 contents = contents.reverse();
267 contents.some(function(node) {
268 if(node.nodeType === Node.TEXT_NODE) {
272 toret = node.getLastTextNode();
280 var wrapper = $('<div>');
281 wrapper.append(this._getXMLDOMToDump());
282 return wrapper.html();
285 _getXMLDOMToDump: function() {
291 var TextNode = function(nativeNode, document) {
292 DocumentNode.call(this, nativeNode, document);
293 this._data = Object.create({});
294 nativeNode.__smartxmlTextNodeInstance = this;
296 TextNode.prototype = Object.create(DocumentNode.prototype);
298 $.extend(TextNode.prototype, {
299 nodeType: Node.TEXT_NODE,
301 setData: function(arg1, arg2) {
302 if(arguments.length === 2) {
303 if(_.isUndefined(arg2)) {
304 delete this._data[arg1];
306 this._data[arg1] = arg2;
309 this._data = _.extend({}, arg1);
313 getData: function(key) {
315 return this._data[key];
320 getText: function() {
321 return this.nativeNode.data;
325 containsNode: function() {
329 triggerTextChangeEvent: function() {
330 var event = new events.ChangeEvent('nodeTextChange', {node: this});
331 this.document.trigger('change', event);
336 var parseXML = function(xml) {
337 var toret = $($.trim(xml));
338 if(toret.length !== 1) {
339 throw new Error('Unable to parse XML: ' + xml);
345 var registerTransformation = function(desc, name, target) {
346 var Transformation = transformations.createContextTransformation(desc, name);
347 target[name] = function() {
349 args = Array.prototype.slice.call(arguments, 0);
350 return instance.transform(Transformation, args);
354 var registerMethod = function(methodName, method, target) {
355 if(target[methodName]) {
356 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
357 .replace('{target}', target)
358 .replace('{methodName}', methodName)
361 target[methodName] = method;
365 var Document = function(xml, extensions) {
368 this._currentTransaction = null;
369 this._transformationLevel = 0;
371 this._nodeMethods = {};
372 this._textNodeMethods = {};
373 this._elementNodeMethods = {};
374 this._nodeTransformations = {};
375 this._textNodeTransformations = {};
376 this._elementNodeTransformations = {};
378 this.registerExtension(coreTransformations);
380 (extensions || []).forEach(function(extension) {
381 this.registerExtension(extension);
386 $.extend(Document.prototype, Backbone.Events, fragments, {
387 ElementNodeFactory: ElementNode,
388 TextNodeFactory: TextNode,
390 createDocumentNode: function(from) {
393 if(from instanceof Node) {
395 cached = from instanceof Text ? from.__smartxmlTextNodeInstance : ($(from).data(privateKey) || {}).node;
396 if(cached instanceof DocumentNode) {
400 if(typeof from === 'string') {
401 from = parseXML(from);
402 this.normalizeXML(from);
404 if(from.text !== undefined) {
405 /* globals document */
406 from = document.createTextNode(from.text);
409 throw new Error('tagName missing');
411 var node = $('<' + from.tagName + '>');
413 _.keys(from.attrs || {}).forEach(function(key) {
414 node.attr(key, from.attrs[key]);
421 var Factory, typeMethods, typeTransformations;
422 if(from.nodeType === Node.TEXT_NODE) {
423 Factory = this.TextNodeFactory;
424 typeMethods = this._textNodeMethods;
425 typeTransformations = this._textNodeTransformations;
426 } else if(from.nodeType === Node.ELEMENT_NODE) {
427 Factory = this.ElementNodeFactory;
428 typeMethods = this._elementNodeMethods;
429 typeTransformations = this._elementNodeTransformations;
431 var toret = new Factory(from, this);
432 _.extend(toret, this._nodeMethods);
433 _.extend(toret, typeMethods);
435 _.extend(toret, this._nodeTransformations);
436 _.extend(toret, typeTransformations);
438 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
439 _.keys(toret.__super__).forEach(function(key) {
440 toret.__super__[key] = _.bind(toret.__super__[key], toret);
446 loadXML: function(xml, options) {
447 options = options || {};
448 this._defineDocumentProperties($(parseXML(xml)));
449 this.normalizeXML(this.dom);
450 if(!options.silent) {
451 this.trigger('contentSet');
455 normalizeXML: function(nativeNode) {
456 void(nativeNode); // noop
460 return this.root.toXML();
463 containsNode: function(node) {
464 return this.root && this.root.containsNode(node);
467 getSiblingParents: function(params) {
468 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
469 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
470 noSiblingParents = null;
472 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
473 return noSiblingParents;
476 var stop = Math.min(parents1.length, parents2.length),
478 for(i = 0; i < stop; i++) {
479 if(parents1[i].sameNode(parents2[i])) {
487 return {node1: parents1[i], node2: parents2[i]};
490 trigger: function() {
491 Backbone.Events.trigger.apply(this, arguments);
494 getNodeInsertion: function(node) {
496 if(node instanceof DocumentNode) {
497 insertion.ofNode = node;
498 insertion.insertsNew = !this.containsNode(node);
500 insertion.ofNode = this.createDocumentNode(node);
501 insertion.insertsNew = true;
506 registerMethod: function(methodName, method, dstName) {
510 documentNode: doc._nodeMethods,
511 textNode: doc._textNodeMethods,
512 elementNode: doc._elementNodeMethods
514 registerMethod(methodName, method, destination);
517 registerTransformation: function(desc, name, dstName) {
521 documentNode: doc._nodeTransformations,
522 textNode: doc._textNodeTransformations,
523 elementNode: doc._elementNodeTransformations
525 registerTransformation(desc, name, destination);
528 registerExtension: function(extension) {
531 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
532 var dstExtension = extension[dstName];
534 if(dstExtension.methods) {
535 _.pairs(dstExtension.methods).forEach(function(pair) {
536 var methodName = pair[0],
539 doc.registerMethod(methodName, method, dstName);
544 if(dstExtension.transformations) {
545 _.pairs(dstExtension.transformations).forEach(function(pair) {
548 doc.registerTransformation(desc, name, dstName);
555 ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
556 var hasChanged = false,
557 changeMonitor = function() {
561 this.on('change', changeMonitor);
562 action.call(context);
563 this.off('change', changeMonitor);
566 if(documentChangedHandler) {
567 documentChangedHandler.call(context);
570 if(documentUnchangedHandler) {
571 documentUnchangedHandler.call(context);
576 transform: function(Transformation, args) {
577 var toret, transformation;
579 if(!this._currentTransaction) {
580 return this.transaction(function() {
581 return this.transform(Transformation, args);
585 if(typeof Transformation === 'function') {
586 transformation = new Transformation(this, this, args);
588 transformation = Transformation;
591 this._transformationLevel++;
596 toret = transformation.run({beUndoable:this._transformationLevel === 1});
599 if(this._transformationLevel === 1 && !this._undoInProgress) {
600 this._currentTransaction.pushTransformation(transformation);
606 this._transformationLevel--;
609 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
613 var transaction = this.undoStack.pop(),
615 transformations, stopAt;
618 this._undoInProgress = true;
620 // We will modify this array in a minute so make sure we work on a copy.
621 transformations = transaction.transformations.slice(0);
623 if(transformations.length > 1) {
624 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
625 transformations.some(function(t, idx) {
626 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
631 if(stopAt !== undefined) {
632 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
633 transformations = transformations.slice(0, stopAt+1);
637 transformations.reverse();
638 transformations.forEach(function(t) {
642 this._undoInProgress = false;
643 this.redoStack.push(transaction);
644 this.trigger('operationEnd');
648 var transaction = this.redoStack.pop();
650 this._transformationLevel++;
651 transaction.transformations.forEach(function(t) {
652 t.run({beUndoable: true});
654 this._transformationLevel--;
655 this.undoStack.push(transaction);
656 this.trigger('operationEnd');
661 startTransaction: function(metadata) {
662 if(this._currentTransaction) {
663 throw new Error('Nested transactions not supported!');
665 this._rollbackBackup = this.root.clone();
666 this._currentTransaction = new Transaction([], metadata);
669 endTransaction: function() {
670 if(!this._currentTransaction) {
671 throw new Error('End of transaction requested, but there is no transaction in progress!');
673 if(this._currentTransaction.hasTransformations()) {
674 this.undoStack.push(this._currentTransaction);
675 this.trigger('operationEnd');
677 this._currentTransaction = null;
680 rollbackTransaction: function() {
681 if(!this._currentTransaction) {
682 throw new Error('Transaction rollback requested, but there is no transaction in progress!');
684 this.replaceRoot(this._rollbackBackup);
685 this._rollbackBackup = null;
686 this._currentTransaction = null;
687 this._transformationLevel = 0;
690 transaction: function(callback, params) {
692 params = params || {};
693 this.startTransaction(params.metadata);
695 toret = callback.call(params.context || this);
700 this.rollbackTransaction();
703 this.endTransaction();
705 params.success(toret);
710 getNodeByPath: function(path) {
711 var toret = this.root;
712 path.some(function(idx) {
713 toret = toret.contents()[idx];
721 _defineDocumentProperties: function($document) {
723 Object.defineProperty(doc, 'root', {get: function() {
727 return doc.createDocumentNode($document[0]);
728 }, configurable: true});
729 Object.defineProperty(doc, 'dom', {get: function() {
734 }, configurable: true});
737 createFragment: function(Type, params) {
738 if(!Type.prototype instanceof fragments.Fragment) {
739 throw new Error('Can\'t create a fragment: `Type` is not a valid Fragment');
741 return new Type(this, params);
745 var Transaction = function(transformations, metadata) {
746 this.transformations = transformations || [];
747 this.metadata = metadata;
749 $.extend(Transaction.prototype, {
750 pushTransformation: function(transformation) {
751 this.transformations.push(transformation);
753 hasTransformations: function() {
754 return this.transformations.length > 0;
760 documentFromXML: function(xml) {
761 var doc = new Document(xml);
765 elementNodeFromXML: function(xml) {
766 return this.documentFromXML(xml).root;
770 DocumentNode: DocumentNode,
771 ElementNode: ElementNode,