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);
283 nativeNode.__smartxmlTextNodeInstance = this;
285 TextNode.prototype = Object.create(DocumentNode.prototype);
287 $.extend(TextNode.prototype, {
288 nodeType: Node.TEXT_NODE,
290 getText: function() {
291 return this.nativeNode.data;
295 containsNode: function() {
299 triggerTextChangeEvent: function() {
300 var event = new events.ChangeEvent('nodeTextChange', {node: this});
301 this.document.trigger('change', event);
306 var parseXML = function(xml) {
307 var toret = $($.trim(xml));
308 if(toret.length !== 1) {
309 throw new Error('Unable to parse XML: ' + xml);
315 var registerTransformation = function(desc, name, target) {
316 var Transformation = transformations.createContextTransformation(desc, name);
317 target[name] = function() {
319 args = Array.prototype.slice.call(arguments, 0);
320 return instance.transform(Transformation, args);
324 var registerMethod = function(methodName, method, target) {
325 if(target[methodName]) {
326 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
327 .replace('{target}', target)
328 .replace('{methodName}', methodName)
331 target[methodName] = method;
335 var Document = function(xml, extensions) {
338 this._currentTransaction = null;
339 this._transformationLevel = 0;
341 this._nodeMethods = {};
342 this._textNodeMethods = {};
343 this._elementNodeMethods = {};
344 this._nodeTransformations = {};
345 this._textNodeTransformations = {};
346 this._elementNodeTransformations = {};
348 this.registerExtension(coreTransformations);
350 (extensions || []).forEach(function(extension) {
351 this.registerExtension(extension);
356 $.extend(Document.prototype, Backbone.Events, fragments, {
357 ElementNodeFactory: ElementNode,
358 TextNodeFactory: TextNode,
360 createDocumentNode: function(from) {
363 if(from instanceof Node) {
365 cached = from instanceof Text ? from.__smartxmlTextNodeInstance : ($(from).data(privateKey) || {}).node;
366 if(cached instanceof DocumentNode) {
370 if(typeof from === 'string') {
371 from = parseXML(from);
372 this.normalizeXML(from);
374 if(from.text !== undefined) {
375 /* globals document */
376 from = document.createTextNode(from.text);
379 throw new Error('tagName missing');
381 var node = $('<' + from.tagName + '>');
383 _.keys(from.attrs || {}).forEach(function(key) {
384 node.attr(key, from.attrs[key]);
391 var Factory, typeMethods, typeTransformations;
392 if(from.nodeType === Node.TEXT_NODE) {
393 Factory = this.TextNodeFactory;
394 typeMethods = this._textNodeMethods;
395 typeTransformations = this._textNodeTransformations;
396 } else if(from.nodeType === Node.ELEMENT_NODE) {
397 Factory = this.ElementNodeFactory;
398 typeMethods = this._elementNodeMethods;
399 typeTransformations = this._elementNodeTransformations;
401 var toret = new Factory(from, this);
402 _.extend(toret, this._nodeMethods);
403 _.extend(toret, typeMethods);
405 _.extend(toret, this._nodeTransformations);
406 _.extend(toret, typeTransformations);
408 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
409 _.keys(toret.__super__).forEach(function(key) {
410 toret.__super__[key] = _.bind(toret.__super__[key], toret);
416 loadXML: function(xml, options) {
417 options = options || {};
418 this._defineDocumentProperties($(parseXML(xml)));
419 this.normalizeXML(this.dom);
420 if(!options.silent) {
421 this.trigger('contentSet');
425 normalizeXML: function(nativeNode) {
426 void(nativeNode); // noop
430 return this.root.toXML();
433 containsNode: function(node) {
434 return this.root && this.root.containsNode(node);
437 getSiblingParents: function(params) {
438 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
439 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
440 noSiblingParents = null;
442 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
443 return noSiblingParents;
446 var stop = Math.min(parents1.length, parents2.length),
448 for(i = 0; i < stop; i++) {
449 if(parents1[i].sameNode(parents2[i])) {
457 return {node1: parents1[i], node2: parents2[i]};
460 trigger: function() {
461 Backbone.Events.trigger.apply(this, arguments);
464 getNodeInsertion: function(node) {
466 if(node instanceof DocumentNode) {
467 insertion.ofNode = node;
468 insertion.insertsNew = !this.containsNode(node);
470 insertion.ofNode = this.createDocumentNode(node);
471 insertion.insertsNew = true;
476 registerMethod: function(methodName, method, dstName) {
480 documentNode: doc._nodeMethods,
481 textNode: doc._textNodeMethods,
482 elementNode: doc._elementNodeMethods
484 registerMethod(methodName, method, destination);
487 registerTransformation: function(desc, name, dstName) {
491 documentNode: doc._nodeTransformations,
492 textNode: doc._textNodeTransformations,
493 elementNode: doc._elementNodeTransformations
495 registerTransformation(desc, name, destination);
498 registerExtension: function(extension) {
501 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
502 var dstExtension = extension[dstName];
504 if(dstExtension.methods) {
505 _.pairs(dstExtension.methods).forEach(function(pair) {
506 var methodName = pair[0],
509 doc.registerMethod(methodName, method, dstName);
514 if(dstExtension.transformations) {
515 _.pairs(dstExtension.transformations).forEach(function(pair) {
518 doc.registerTransformation(desc, name, dstName);
525 ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
526 var hasChanged = false,
527 changeMonitor = function() {
531 this.on('change', changeMonitor);
532 action.call(context);
533 this.off('change', changeMonitor);
536 if(documentChangedHandler) {
537 documentChangedHandler.call(context);
540 if(documentUnchangedHandler) {
541 documentUnchangedHandler.call(context);
546 transform: function(Transformation, args) {
547 var toret, transformation;
549 if(!this._currentTransaction) {
550 return this.transaction(function() {
551 return this.transform(Transformation, args);
555 if(typeof Transformation === 'function') {
556 transformation = new Transformation(this, this, args);
558 transformation = Transformation;
561 this._transformationLevel++;
566 toret = transformation.run({beUndoable:this._transformationLevel === 1});
569 if(this._transformationLevel === 1 && !this._undoInProgress) {
570 this._currentTransaction.pushTransformation(transformation);
576 this._transformationLevel--;
579 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
583 var transaction = this.undoStack.pop(),
585 transformations, stopAt;
588 this._undoInProgress = true;
590 // We will modify this array in a minute so make sure we work on a copy.
591 transformations = transaction.transformations.slice(0);
593 if(transformations.length > 1) {
594 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
595 transformations.some(function(t, idx) {
596 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
601 if(stopAt !== undefined) {
602 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
603 transformations = transformations.slice(0, stopAt+1);
607 transformations.reverse();
608 transformations.forEach(function(t) {
612 this._undoInProgress = false;
613 this.redoStack.push(transaction);
614 this.trigger('operationEnd');
618 var transaction = this.redoStack.pop();
620 this._transformationLevel++;
621 transaction.transformations.forEach(function(t) {
622 t.run({beUndoable: true});
624 this._transformationLevel--;
625 this.undoStack.push(transaction);
626 this.trigger('operationEnd');
631 startTransaction: function(metadata) {
632 if(this._currentTransaction) {
633 throw new Error('Nested transactions not supported!');
635 this._rollbackBackup = this.root.clone();
636 this._currentTransaction = new Transaction([], metadata);
639 endTransaction: function() {
640 if(!this._currentTransaction) {
641 throw new Error('End of transaction requested, but there is no transaction in progress!');
643 if(this._currentTransaction.hasTransformations()) {
644 this.undoStack.push(this._currentTransaction);
645 this.trigger('operationEnd');
647 this._currentTransaction = null;
650 rollbackTransaction: function() {
651 if(!this._currentTransaction) {
652 throw new Error('Transaction rollback requested, but there is no transaction in progress!');
654 this.replaceRoot(this._rollbackBackup);
655 this._rollbackBackup = null;
656 this._currentTransaction = null;
657 this._transformationLevel = 0;
660 transaction: function(callback, params) {
662 params = params || {};
663 this.startTransaction(params.metadata);
665 toret = callback.call(params.context || this);
670 this.rollbackTransaction();
673 this.endTransaction();
675 params.success(toret);
680 getNodeByPath: function(path) {
681 var toret = this.root;
682 path.some(function(idx) {
683 toret = toret.contents()[idx];
691 _defineDocumentProperties: function($document) {
693 Object.defineProperty(doc, 'root', {get: function() {
697 return doc.createDocumentNode($document[0]);
698 }, configurable: true});
699 Object.defineProperty(doc, 'dom', {get: function() {
704 }, configurable: true});
707 createFragment: function(Type, params) {
708 if(!Type.prototype instanceof fragments.Fragment) {
709 throw new Error('Can\'t create a fragment: `Type` is not a valid Fragment');
711 return new Type(this, params);
715 var Transaction = function(transformations, metadata) {
716 this.transformations = transformations || [];
717 this.metadata = metadata;
719 $.extend(Transaction.prototype, {
720 pushTransformation: function(transformation) {
721 this.transformations.push(transformation);
723 hasTransformations: function() {
724 return this.transformations.length > 0;
730 documentFromXML: function(xml) {
731 var doc = new Document(xml);
735 elementNodeFromXML: function(xml) {
736 return this.documentFromXML(xml).root;
740 DocumentNode: DocumentNode,
741 ElementNode: ElementNode,