6 'smartxml/transformations',
9 ], function($, _, Backbone, events, transformations, coreTransformations, fragments) {
15 var DocumentNode = function(nativeNode, document) {
17 throw new Error('undefined document for a node');
19 this.document = document;
20 this._setNativeNode(nativeNode);
24 $.extend(DocumentNode.prototype, {
26 transform: function(Transformation, args) {
27 var transformation = new Transformation(this.document, this, args);
28 return this.document.transform(transformation);
31 _setNativeNode: function(nativeNode) {
32 this.nativeNode = nativeNode;
33 this._$ = $(nativeNode);
37 var clone = this._$.clone(true, true),
39 clone.find('*').addBack().each(function() {
41 clonedData = $(this).data();
43 _.pairs(clonedData).forEach(function(pair) {
46 if(_.isFunction(value.clone)) {
47 clonedData[key] = value.clone(node.document.createDocumentNode(el));
51 return this.document.createDocumentNode(clone[0]);
54 getPath: function(ancestor) {
55 if(!(this.document.containsNode(this))) {
59 var nodePath = [this].concat(this.parents()),
61 ancestor = ancestor || this.document.root;
63 nodePath.some(function(node, i) {
64 if(node.sameNode(ancestor)) {
70 if(idx !== undefined) {
71 nodePath = nodePath.slice(0, idx);
73 toret = nodePath.map(function(node) {return node.getIndex(); });
79 return this.document.root.sameNode(this);
82 isInDocument: function() {
83 return this.document.containsNode(this);
86 isSiblingOf: function(node) {
87 return node && this.parent().sameNode(node.parent());
90 sameNode: function(otherNode) {
91 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
95 var parentNode = this.nativeNode.parentNode;
96 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
97 return this.document.createDocumentNode(parentNode);
102 parents: function() {
103 var parent = this.parent(),
104 parents = parent ? parent.parents() : [];
106 parents.unshift(parent);
112 var myIdx = this.getIndex();
113 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
120 var myIdx = this.getIndex(),
121 parentContents = this.parent().contents();
122 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
125 isSurroundedByTextNodes: function() {
126 return this.isPrecededByTextNode() && this.isFollowedByTextNode();
129 isPrecededByTextNode: function() {
130 var prev = this.prev();
131 return prev && prev.nodeType === Node.TEXT_NODE;
134 isFollowedByTextNode: function() {
135 var next = this.next();
136 return next && next.nodeType === Node.TEXT_NODE;
139 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
140 var node = (metaData && metaData.node) ? metaData.node : this,
141 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
142 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
143 if(type === 'nodeMoved') {
144 event.meta.parent = origParent;
146 this.document.trigger('change', event);
148 if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
149 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
150 this.document.trigger('change', event);
154 getNodeInsertion: function(node) {
155 return this.document.getNodeInsertion(node);
158 getIndex: function() {
162 return this.parent().indexOf(this);
165 getNearestElementNode: function() {
166 return this.nodeType === Node.ELEMENT_NODE ? this : this.parent();
171 var ElementNode = function(nativeNode, document) {
172 DocumentNode.call(this, nativeNode, document);
174 ElementNode.prototype = Object.create(DocumentNode.prototype);
176 $.extend(ElementNode.prototype, {
177 nodeType: Node.ELEMENT_NODE,
179 setData: function(arg1, arg2) {
180 if(arguments.length === 2) {
181 if(_.isUndefined(arg2)) {
182 this._$.removeData(arg1);
184 this._$.data(arg1, arg2);
187 this._$.removeData(_.keys(this._$.data()));
192 getData: function(key) {
194 return this._$.data(key);
196 return this._$.data();
199 getTagName: function() {
200 return this.nativeNode.tagName.toLowerCase();
203 contents: function(selector) {
205 document = this.document;
207 this._$.children(selector).each(function() {
208 toret.push(document.createDocumentNode(this));
211 this._$.contents().each(function() {
212 toret.push(document.createDocumentNode(this));
218 indexOf: function(node) {
219 return this._$.contents().index(node._$);
222 getAttr: function(name) {
223 return this._$.attr(name);
226 getAttrs: function() {
228 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
229 toret.push(this.nativeNode.attributes[i]);
234 containsNode: function(node) {
235 return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
238 getLastTextNode: function() {
239 var contents = this.contents(),
242 contents.reverse().some(function(node) {
243 if(node.nodeType === Node.TEXT_NODE) {
247 toret = node.getLastTextNode();
255 var wrapper = $('<div>');
256 wrapper.append(this._getXMLDOMToDump());
257 return wrapper.html();
260 _getXMLDOMToDump: function() {
266 var TextNode = function(nativeNode, document) {
267 DocumentNode.call(this, nativeNode, document);
269 TextNode.prototype = Object.create(DocumentNode.prototype);
271 $.extend(TextNode.prototype, {
272 nodeType: Node.TEXT_NODE,
274 getText: function() {
275 return this.nativeNode.data;
279 containsNode: function() {
283 triggerTextChangeEvent: function() {
284 var event = new events.ChangeEvent('nodeTextChange', {node: this});
285 this.document.trigger('change', event);
290 var parseXML = function(xml) {
291 var toret = $($.trim(xml));
293 throw new Error('Unable to parse XML: ' + xml);
299 var registerTransformation = function(desc, name, target) {
300 var Transformation = transformations.createContextTransformation(desc, name);
301 target[name] = function() {
303 args = Array.prototype.slice.call(arguments, 0);
304 return instance.transform(Transformation, args);
308 var registerMethod = function(methodName, method, target) {
309 if(target[methodName]) {
310 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
311 .replace('{target}', target)
312 .replace('{methodName}', methodName)
315 target[methodName] = method;
319 var Document = function(xml, extensions) {
322 this._currentTransaction = null;
323 this._transformationLevel = 0;
325 this._nodeMethods = {};
326 this._textNodeMethods = {};
327 this._elementNodeMethods = {};
328 this._nodeTransformations = {};
329 this._textNodeTransformations = {};
330 this._elementNodeTransformations = {};
332 this.registerExtension(coreTransformations);
334 (extensions || []).forEach(function(extension) {
335 this.registerExtension(extension);
340 $.extend(Document.prototype, Backbone.Events, fragments, {
341 ElementNodeFactory: ElementNode,
342 TextNodeFactory: TextNode,
344 createDocumentNode: function(from) {
345 if(!(from instanceof Node)) {
346 if(typeof from === 'string') {
347 from = parseXML(from);
348 this.normalizeXML(from);
350 if(from.text !== undefined) {
351 /* globals document */
352 from = document.createTextNode(from.text);
355 throw new Error('tagName missing');
357 var node = $('<' + from.tagName + '>');
359 _.keys(from.attrs || {}).forEach(function(key) {
360 node.attr(key, from.attrs[key]);
367 var Factory, typeMethods, typeTransformations;
368 if(from.nodeType === Node.TEXT_NODE) {
369 Factory = this.TextNodeFactory;
370 typeMethods = this._textNodeMethods;
371 typeTransformations = this._textNodeTransformations;
372 } else if(from.nodeType === Node.ELEMENT_NODE) {
373 Factory = this.ElementNodeFactory;
374 typeMethods = this._elementNodeMethods;
375 typeTransformations = this._elementNodeTransformations;
377 var toret = new Factory(from, this);
378 _.extend(toret, this._nodeMethods);
379 _.extend(toret, typeMethods);
381 _.extend(toret, this._nodeTransformations);
382 _.extend(toret, typeTransformations);
384 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
385 _.keys(toret.__super__).forEach(function(key) {
386 toret.__super__[key] = _.bind(toret.__super__[key], toret);
392 loadXML: function(xml, options) {
393 options = options || {};
394 this._defineDocumentProperties($(parseXML(xml)));
395 this.normalizeXML(this.dom);
396 if(!options.silent) {
397 this.trigger('contentSet');
401 normalizeXML: function(nativeNode) {
402 void(nativeNode); // noop
406 return this.root.toXML();
409 containsNode: function(node) {
410 return this.root && this.root.containsNode(node);
413 getSiblingParents: function(params) {
414 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
415 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
416 noSiblingParents = null;
418 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
419 return noSiblingParents;
422 var stop = Math.min(parents1.length, parents2.length),
424 for(i = 0; i < stop; i++) {
425 if(parents1[i].sameNode(parents2[i])) {
433 return {node1: parents1[i], node2: parents2[i]};
436 trigger: function() {
437 Backbone.Events.trigger.apply(this, arguments);
440 getNodeInsertion: function(node) {
442 if(node instanceof DocumentNode) {
443 insertion.ofNode = node;
444 insertion.insertsNew = !this.containsNode(node);
446 insertion.ofNode = this.createDocumentNode(node);
447 insertion.insertsNew = true;
452 registerMethod: function(methodName, method, dstName) {
456 documentNode: doc._nodeMethods,
457 textNode: doc._textNodeMethods,
458 elementNode: doc._elementNodeMethods
460 registerMethod(methodName, method, destination);
463 registerTransformation: function(desc, name, dstName) {
467 documentNode: doc._nodeTransformations,
468 textNode: doc._textNodeTransformations,
469 elementNode: doc._elementNodeTransformations
471 registerTransformation(desc, name, destination);
474 registerExtension: function(extension) {
477 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
478 var dstExtension = extension[dstName];
480 if(dstExtension.methods) {
481 _.pairs(dstExtension.methods).forEach(function(pair) {
482 var methodName = pair[0],
485 doc.registerMethod(methodName, method, dstName);
490 if(dstExtension.transformations) {
491 _.pairs(dstExtension.transformations).forEach(function(pair) {
494 doc.registerTransformation(desc, name, dstName);
501 ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
502 var hasChanged = false,
503 changeMonitor = function() {
507 this.on('change', changeMonitor);
508 action.call(context);
509 this.off('change', changeMonitor);
512 if(documentChangedHandler) {
513 documentChangedHandler.call(context);
516 if(documentUnchangedHandler) {
517 documentUnchangedHandler.call(context);
522 transform: function(Transformation, args) {
523 var toret, transformation;
525 if(!this._currentTransaction) {
526 return this.transaction(function() {
527 return this.transform(Transformation, args);
531 if(typeof Transformation === 'function') {
532 transformation = new Transformation(this, this, args);
534 transformation = Transformation;
537 this._transformationLevel++;
542 toret = transformation.run({beUndoable:this._transformationLevel === 1});
545 if(this._transformationLevel === 1 && !this._undoInProgress) {
546 this._currentTransaction.pushTransformation(transformation);
552 this._transformationLevel--;
555 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
559 var transaction = this.undoStack.pop(),
561 transformations, stopAt;
564 this._undoInProgress = true;
566 // We will modify this array in a minute so make sure we work on a copy.
567 transformations = transaction.transformations.slice(0);
569 if(transformations.length > 1) {
570 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
572 transformations.some(function(t, idx) {
573 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
578 if(stopAt !== undefined) {
579 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
580 transformations = transformations.slice(0, stopAt+1);
584 transformations.reverse();
585 transformations.forEach(function(t) {
589 this._undoInProgress = false;
590 this.redoStack.push(transaction);
591 this.trigger('operationEnd');
595 var transaction = this.redoStack.pop();
597 this._transformationLevel++;
598 transaction.transformations.forEach(function(t) {
599 t.run({beUndoable: true});
601 this._transformationLevel--;
602 this.undoStack.push(transaction);
603 this.trigger('operationEnd');
608 startTransaction: function(metadata) {
609 if(this._currentTransaction) {
610 throw new Error('Nested transactions not supported!');
612 this._rollbackBackup = this.root.clone();
613 this._currentTransaction = new Transaction([], metadata);
616 endTransaction: function() {
617 if(!this._currentTransaction) {
618 throw new Error('End of transaction requested, but there is no transaction in progress!');
620 if(this._currentTransaction.hasTransformations()) {
621 this.undoStack.push(this._currentTransaction);
622 this.trigger('operationEnd');
624 this._currentTransaction = null;
627 rollbackTransaction: function() {
628 if(!this._currentTransaction) {
629 throw new Error('Transaction rollback requested, but there is no transaction in progress!');
631 this.replaceRoot(this._rollbackBackup);
632 this._rollbackBackup = null;
633 this._currentTransaction = null;
634 this._transformationLevel = 0;
637 transaction: function(callback, params) {
639 params = params || {};
640 this.startTransaction(params.metadata);
642 toret = callback.call(params.context || this);
647 this.rollbackTransaction();
650 this.endTransaction();
652 params.success(toret);
657 getNodeByPath: function(path) {
658 var toret = this.root;
659 path.forEach(function(idx) {
660 toret = toret.contents()[idx];
665 _defineDocumentProperties: function($document) {
667 Object.defineProperty(doc, 'root', {get: function() {
671 return doc.createDocumentNode($document[0]);
672 }, configurable: true});
673 Object.defineProperty(doc, 'dom', {get: function() {
678 }, configurable: true});
681 createFragment: function(Type, params) {
682 if(!Type.prototype instanceof fragments.Fragment) {
683 throw new Error('Can\'t create a fragment: `Type` is not a valid Fragment');
685 return new Type(this, params);
689 var Transaction = function(transformations, metadata) {
690 this.transformations = transformations || [];
691 this.metadata = metadata;
693 $.extend(Transaction.prototype, {
694 pushTransformation: function(transformation) {
695 this.transformations.push(transformation);
697 hasTransformations: function() {
698 return this.transformations.length > 0;
704 documentFromXML: function(xml) {
705 var doc = new Document(xml);
709 elementNodeFromXML: function(xml) {
710 return this.documentFromXML(xml).root;
714 DocumentNode: DocumentNode,
715 ElementNode: ElementNode,