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 getLastTextNode: function() {
254 var contents = this.contents(),
257 contents.reverse().some(function(node) {
258 if(node.nodeType === Node.TEXT_NODE) {
262 toret = node.getLastTextNode();
270 var wrapper = $('<div>');
271 wrapper.append(this._getXMLDOMToDump());
272 return wrapper.html();
275 _getXMLDOMToDump: function() {
281 var TextNode = function(nativeNode, document) {
282 DocumentNode.call(this, nativeNode, document);
284 TextNode.prototype = Object.create(DocumentNode.prototype);
286 $.extend(TextNode.prototype, {
287 nodeType: Node.TEXT_NODE,
289 getText: function() {
290 return this.nativeNode.data;
294 containsNode: function() {
298 triggerTextChangeEvent: function() {
299 var event = new events.ChangeEvent('nodeTextChange', {node: this});
300 this.document.trigger('change', event);
305 var parseXML = function(xml) {
306 var toret = $($.trim(xml));
307 if(toret.length !== 1) {
308 throw new Error('Unable to parse XML: ' + xml);
314 var registerTransformation = function(desc, name, target) {
315 var Transformation = transformations.createContextTransformation(desc, name);
316 target[name] = function() {
318 args = Array.prototype.slice.call(arguments, 0);
319 return instance.transform(Transformation, args);
323 var registerMethod = function(methodName, method, target) {
324 if(target[methodName]) {
325 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
326 .replace('{target}', target)
327 .replace('{methodName}', methodName)
330 target[methodName] = method;
334 var Document = function(xml, extensions) {
337 this._currentTransaction = null;
338 this._transformationLevel = 0;
340 this._nodeMethods = {};
341 this._textNodeMethods = {};
342 this._elementNodeMethods = {};
343 this._nodeTransformations = {};
344 this._textNodeTransformations = {};
345 this._elementNodeTransformations = {};
347 this.registerExtension(coreTransformations);
349 (extensions || []).forEach(function(extension) {
350 this.registerExtension(extension);
355 $.extend(Document.prototype, Backbone.Events, fragments, {
356 ElementNodeFactory: ElementNode,
357 TextNodeFactory: TextNode,
359 createDocumentNode: function(from) {
362 if(from instanceof Node) {
363 cached = ($(from).data(privateKey) || {}).node;
364 if(cached instanceof DocumentNode) {
368 if(typeof from === 'string') {
369 from = parseXML(from);
370 this.normalizeXML(from);
372 if(from.text !== undefined) {
373 /* globals document */
374 from = document.createTextNode(from.text);
377 throw new Error('tagName missing');
379 var node = $('<' + from.tagName + '>');
381 _.keys(from.attrs || {}).forEach(function(key) {
382 node.attr(key, from.attrs[key]);
389 var Factory, typeMethods, typeTransformations;
390 if(from.nodeType === Node.TEXT_NODE) {
391 Factory = this.TextNodeFactory;
392 typeMethods = this._textNodeMethods;
393 typeTransformations = this._textNodeTransformations;
394 } else if(from.nodeType === Node.ELEMENT_NODE) {
395 Factory = this.ElementNodeFactory;
396 typeMethods = this._elementNodeMethods;
397 typeTransformations = this._elementNodeTransformations;
399 var toret = new Factory(from, this);
400 _.extend(toret, this._nodeMethods);
401 _.extend(toret, typeMethods);
403 _.extend(toret, this._nodeTransformations);
404 _.extend(toret, typeTransformations);
406 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
407 _.keys(toret.__super__).forEach(function(key) {
408 toret.__super__[key] = _.bind(toret.__super__[key], toret);
414 loadXML: function(xml, options) {
415 options = options || {};
416 this._defineDocumentProperties($(parseXML(xml)));
417 this.normalizeXML(this.dom);
418 if(!options.silent) {
419 this.trigger('contentSet');
423 normalizeXML: function(nativeNode) {
424 void(nativeNode); // noop
428 return this.root.toXML();
431 containsNode: function(node) {
432 return this.root && this.root.containsNode(node);
435 getSiblingParents: function(params) {
436 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
437 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
438 noSiblingParents = null;
440 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
441 return noSiblingParents;
444 var stop = Math.min(parents1.length, parents2.length),
446 for(i = 0; i < stop; i++) {
447 if(parents1[i].sameNode(parents2[i])) {
455 return {node1: parents1[i], node2: parents2[i]};
458 trigger: function() {
459 Backbone.Events.trigger.apply(this, arguments);
462 getNodeInsertion: function(node) {
464 if(node instanceof DocumentNode) {
465 insertion.ofNode = node;
466 insertion.insertsNew = !this.containsNode(node);
468 insertion.ofNode = this.createDocumentNode(node);
469 insertion.insertsNew = true;
474 registerMethod: function(methodName, method, dstName) {
478 documentNode: doc._nodeMethods,
479 textNode: doc._textNodeMethods,
480 elementNode: doc._elementNodeMethods
482 registerMethod(methodName, method, destination);
485 registerTransformation: function(desc, name, dstName) {
489 documentNode: doc._nodeTransformations,
490 textNode: doc._textNodeTransformations,
491 elementNode: doc._elementNodeTransformations
493 registerTransformation(desc, name, destination);
496 registerExtension: function(extension) {
499 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
500 var dstExtension = extension[dstName];
502 if(dstExtension.methods) {
503 _.pairs(dstExtension.methods).forEach(function(pair) {
504 var methodName = pair[0],
507 doc.registerMethod(methodName, method, dstName);
512 if(dstExtension.transformations) {
513 _.pairs(dstExtension.transformations).forEach(function(pair) {
516 doc.registerTransformation(desc, name, dstName);
523 ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
524 var hasChanged = false,
525 changeMonitor = function() {
529 this.on('change', changeMonitor);
530 action.call(context);
531 this.off('change', changeMonitor);
534 if(documentChangedHandler) {
535 documentChangedHandler.call(context);
538 if(documentUnchangedHandler) {
539 documentUnchangedHandler.call(context);
544 transform: function(Transformation, args) {
545 var toret, transformation;
547 if(!this._currentTransaction) {
548 return this.transaction(function() {
549 return this.transform(Transformation, args);
553 if(typeof Transformation === 'function') {
554 transformation = new Transformation(this, this, args);
556 transformation = Transformation;
559 this._transformationLevel++;
564 toret = transformation.run({beUndoable:this._transformationLevel === 1});
567 if(this._transformationLevel === 1 && !this._undoInProgress) {
568 this._currentTransaction.pushTransformation(transformation);
574 this._transformationLevel--;
577 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
581 var transaction = this.undoStack.pop(),
583 transformations, stopAt;
586 this._undoInProgress = true;
588 // We will modify this array in a minute so make sure we work on a copy.
589 transformations = transaction.transformations.slice(0);
591 if(transformations.length > 1) {
592 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
593 transformations.some(function(t, idx) {
594 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
599 if(stopAt !== undefined) {
600 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
601 transformations = transformations.slice(0, stopAt+1);
605 transformations.reverse();
606 transformations.forEach(function(t) {
610 this._undoInProgress = false;
611 this.redoStack.push(transaction);
612 this.trigger('operationEnd');
616 var transaction = this.redoStack.pop();
618 this._transformationLevel++;
619 transaction.transformations.forEach(function(t) {
620 t.run({beUndoable: true});
622 this._transformationLevel--;
623 this.undoStack.push(transaction);
624 this.trigger('operationEnd');
629 startTransaction: function(metadata) {
630 if(this._currentTransaction) {
631 throw new Error('Nested transactions not supported!');
633 this._rollbackBackup = this.root.clone();
634 this._currentTransaction = new Transaction([], metadata);
637 endTransaction: function() {
638 if(!this._currentTransaction) {
639 throw new Error('End of transaction requested, but there is no transaction in progress!');
641 if(this._currentTransaction.hasTransformations()) {
642 this.undoStack.push(this._currentTransaction);
643 this.trigger('operationEnd');
645 this._currentTransaction = null;
648 rollbackTransaction: function() {
649 if(!this._currentTransaction) {
650 throw new Error('Transaction rollback requested, but there is no transaction in progress!');
652 this.replaceRoot(this._rollbackBackup);
653 this._rollbackBackup = null;
654 this._currentTransaction = null;
655 this._transformationLevel = 0;
658 transaction: function(callback, params) {
660 params = params || {};
661 this.startTransaction(params.metadata);
663 toret = callback.call(params.context || this);
668 this.rollbackTransaction();
671 this.endTransaction();
673 params.success(toret);
678 getNodeByPath: function(path) {
679 var toret = this.root;
680 path.some(function(idx) {
681 toret = toret.contents()[idx];
689 _defineDocumentProperties: function($document) {
691 Object.defineProperty(doc, 'root', {get: function() {
695 return doc.createDocumentNode($document[0]);
696 }, configurable: true});
697 Object.defineProperty(doc, 'dom', {get: function() {
702 }, configurable: true});
705 createFragment: function(Type, params) {
706 if(!Type.prototype instanceof fragments.Fragment) {
707 throw new Error('Can\'t create a fragment: `Type` is not a valid Fragment');
709 return new Type(this, params);
713 var Transaction = function(transformations, metadata) {
714 this.transformations = transformations || [];
715 this.metadata = metadata;
717 $.extend(Transaction.prototype, {
718 pushTransformation: function(transformation) {
719 this.transformations.push(transformation);
721 hasTransformations: function() {
722 return this.transformations.length > 0;
728 documentFromXML: function(xml) {
729 var doc = new Document(xml);
733 elementNodeFromXML: function(xml) {
734 return this.documentFromXML(xml).root;
738 DocumentNode: DocumentNode,
739 ElementNode: ElementNode,