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 isSurroundedByTextElements: function() {
126 var prev = this.prev(),
128 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
131 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
132 var node = (metaData && metaData.node) ? metaData.node : this,
133 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
134 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
135 if(type === 'nodeMoved') {
136 event.meta.parent = origParent;
138 this.document.trigger('change', event);
140 if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
141 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
142 this.document.trigger('change', event);
146 getNodeInsertion: function(node) {
147 return this.document.getNodeInsertion(node);
150 getIndex: function() {
154 return this.parent().indexOf(this);
157 getNearestElementNode: function() {
158 return this.nodeType === Node.ELEMENT_NODE ? this : this.parent();
163 var ElementNode = function(nativeNode, document) {
164 DocumentNode.call(this, nativeNode, document);
166 ElementNode.prototype = Object.create(DocumentNode.prototype);
168 $.extend(ElementNode.prototype, {
169 nodeType: Node.ELEMENT_NODE,
171 setData: function(key, value) {
172 if(value !== undefined) {
173 this._$.data(key, value);
175 this._$.removeData(_.keys(this._$.data()));
180 getData: function(key) {
182 return this._$.data(key);
184 return this._$.data();
187 getTagName: function() {
188 return this.nativeNode.tagName.toLowerCase();
191 contents: function(selector) {
193 document = this.document;
195 this._$.children(selector).each(function() {
196 toret.push(document.createDocumentNode(this));
199 this._$.contents().each(function() {
200 toret.push(document.createDocumentNode(this));
206 indexOf: function(node) {
207 return this._$.contents().index(node._$);
210 getAttr: function(name) {
211 return this._$.attr(name);
214 getAttrs: function() {
216 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
217 toret.push(this.nativeNode.attributes[i]);
222 containsNode: function(node) {
223 return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
227 var wrapper = $('<div>');
228 wrapper.append(this._getXMLDOMToDump());
229 return wrapper.html();
232 _getXMLDOMToDump: function() {
238 var TextNode = function(nativeNode, document) {
239 DocumentNode.call(this, nativeNode, document);
241 TextNode.prototype = Object.create(DocumentNode.prototype);
243 $.extend(TextNode.prototype, {
244 nodeType: Node.TEXT_NODE,
246 getText: function() {
247 return this.nativeNode.data;
251 containsNode: function() {
255 triggerTextChangeEvent: function() {
256 var event = new events.ChangeEvent('nodeTextChange', {node: this});
257 this.document.trigger('change', event);
262 var parseXML = function(xml) {
263 var toret = $($.trim(xml));
265 throw new Error('Unable to parse XML: ' + xml);
271 var registerTransformation = function(desc, name, target) {
272 var Transformation = transformations.createContextTransformation(desc, name);
273 target[name] = function() {
275 args = Array.prototype.slice.call(arguments, 0);
276 return instance.transform(Transformation, args);
280 var registerMethod = function(methodName, method, target) {
281 if(target[methodName]) {
282 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
283 .replace('{target}', target)
284 .replace('{methodName}', methodName)
287 target[methodName] = method;
291 var Document = function(xml, extensions) {
294 this._currentTransaction = null;
295 this._transformationLevel = 0;
297 this._nodeMethods = {};
298 this._textNodeMethods = {};
299 this._elementNodeMethods = {};
300 this._nodeTransformations = {};
301 this._textNodeTransformations = {};
302 this._elementNodeTransformations = {};
304 this.registerExtension(coreTransformations);
306 (extensions || []).forEach(function(extension) {
307 this.registerExtension(extension);
312 $.extend(Document.prototype, Backbone.Events, fragments, {
313 ElementNodeFactory: ElementNode,
314 TextNodeFactory: TextNode,
316 createDocumentNode: function(from) {
317 if(!(from instanceof Node)) {
318 if(typeof from === 'string') {
319 from = parseXML(from);
320 this.normalizeXML(from);
322 if(from.text !== undefined) {
323 /* globals document */
324 from = document.createTextNode(from.text);
327 throw new Error('tagName missing');
329 var node = $('<' + from.tagName + '>');
331 _.keys(from.attrs || {}).forEach(function(key) {
332 node.attr(key, from.attrs[key]);
339 var Factory, typeMethods, typeTransformations;
340 if(from.nodeType === Node.TEXT_NODE) {
341 Factory = this.TextNodeFactory;
342 typeMethods = this._textNodeMethods;
343 typeTransformations = this._textNodeTransformations;
344 } else if(from.nodeType === Node.ELEMENT_NODE) {
345 Factory = this.ElementNodeFactory;
346 typeMethods = this._elementNodeMethods;
347 typeTransformations = this._elementNodeTransformations;
349 var toret = new Factory(from, this);
350 _.extend(toret, this._nodeMethods);
351 _.extend(toret, typeMethods);
353 _.extend(toret, this._nodeTransformations);
354 _.extend(toret, typeTransformations);
356 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
357 _.keys(toret.__super__).forEach(function(key) {
358 toret.__super__[key] = _.bind(toret.__super__[key], toret);
364 loadXML: function(xml, options) {
365 options = options || {};
366 this._defineDocumentProperties($(parseXML(xml)));
367 this.normalizeXML(this.dom);
368 if(!options.silent) {
369 this.trigger('contentSet');
373 normalizeXML: function(nativeNode) {
374 void(nativeNode); // noop
378 return this.root.toXML();
381 containsNode: function(node) {
382 return this.root && this.root.containsNode(node);
385 getSiblingParents: function(params) {
386 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
387 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
388 noSiblingParents = null;
390 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
391 return noSiblingParents;
394 var stop = Math.min(parents1.length, parents2.length),
396 for(i = 0; i < stop; i++) {
397 if(parents1[i].sameNode(parents2[i])) {
405 return {node1: parents1[i], node2: parents2[i]};
408 trigger: function() {
409 Backbone.Events.trigger.apply(this, arguments);
412 getNodeInsertion: function(node) {
414 if(node instanceof DocumentNode) {
415 insertion.ofNode = node;
416 insertion.insertsNew = !this.containsNode(node);
418 insertion.ofNode = this.createDocumentNode(node);
419 insertion.insertsNew = true;
424 registerMethod: function(methodName, method, dstName) {
428 documentNode: doc._nodeMethods,
429 textNode: doc._textNodeMethods,
430 elementNode: doc._elementNodeMethods
432 registerMethod(methodName, method, destination);
435 registerTransformation: function(desc, name, dstName) {
439 documentNode: doc._nodeTransformations,
440 textNode: doc._textNodeTransformations,
441 elementNode: doc._elementNodeTransformations
443 registerTransformation(desc, name, destination);
446 registerExtension: function(extension) {
449 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
450 var dstExtension = extension[dstName];
452 if(dstExtension.methods) {
453 _.pairs(dstExtension.methods).forEach(function(pair) {
454 var methodName = pair[0],
457 doc.registerMethod(methodName, method, dstName);
462 if(dstExtension.transformations) {
463 _.pairs(dstExtension.transformations).forEach(function(pair) {
466 doc.registerTransformation(desc, name, dstName);
473 ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
474 var hasChanged = false,
475 changeMonitor = function() {
479 this.on('change', changeMonitor);
480 action.call(context);
481 this.off('change', changeMonitor);
484 if(documentChangedHandler) {
485 documentChangedHandler.call(context);
488 if(documentUnchangedHandler) {
489 documentUnchangedHandler.call(context);
494 transform: function(Transformation, args) {
495 var toret, transformation;
497 if(!this._currentTransaction) {
498 return this.transaction(function() {
499 return this.transform(Transformation, args);
503 if(typeof Transformation === 'function') {
504 transformation = new Transformation(this, this, args);
506 transformation = Transformation;
509 this._transformationLevel++;
514 toret = transformation.run({beUndoable:this._transformationLevel === 1});
517 if(this._transformationLevel === 1 && !this._undoInProgress) {
518 this._currentTransaction.pushTransformation(transformation);
524 this._transformationLevel--;
527 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
531 var transaction = this.undoStack.pop(),
533 transformations, stopAt;
536 this._undoInProgress = true;
538 // We will modify this array in a minute so make sure we work on a copy.
539 transformations = transaction.transformations.slice(0);
541 if(transformations.length > 1) {
542 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
544 transformations.some(function(t, idx) {
545 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
550 if(stopAt !== undefined) {
551 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
552 transformations = transformations.slice(0, stopAt+1);
556 transformations.reverse();
557 transformations.forEach(function(t) {
561 this._undoInProgress = false;
562 this.redoStack.push(transaction);
563 this.trigger('operationEnd');
567 var transaction = this.redoStack.pop();
569 this._transformationLevel++;
570 transaction.transformations.forEach(function(t) {
571 t.run({beUndoable: true});
573 this._transformationLevel--;
574 this.undoStack.push(transaction);
575 this.trigger('operationEnd');
580 startTransaction: function(metadata) {
581 if(this._currentTransaction) {
582 throw new Error('Nested transactions not supported!');
584 this._rollbackBackup = this.root.clone();
585 this._currentTransaction = new Transaction([], metadata);
588 endTransaction: function() {
589 if(!this._currentTransaction) {
590 throw new Error('End of transaction requested, but there is no transaction in progress!');
592 if(this._currentTransaction.hasTransformations()) {
593 this.undoStack.push(this._currentTransaction);
594 this.trigger('operationEnd');
596 this._currentTransaction = null;
599 rollbackTransaction: function() {
600 if(!this._currentTransaction) {
601 throw new Error('Transaction rollback requested, but there is no transaction in progress!');
603 this.replaceRoot(this._rollbackBackup);
604 this._rollbackBackup = null;
605 this._currentTransaction = null;
606 this._transformationLevel = 0;
609 transaction: function(callback, params) {
611 params = params || {};
612 this.startTransaction(params.metadata);
614 toret = callback.call(params.context || this);
619 this.rollbackTransaction();
622 this.endTransaction();
624 params.success(toret);
629 getNodeByPath: function(path) {
630 var toret = this.root;
631 path.forEach(function(idx) {
632 toret = toret.contents()[idx];
637 _defineDocumentProperties: function($document) {
639 Object.defineProperty(doc, 'root', {get: function() {
643 return doc.createDocumentNode($document[0]);
644 }, configurable: true});
645 Object.defineProperty(doc, 'dom', {get: function() {
650 }, configurable: true});
653 createFragment: function(Type, params) {
654 if(!Type.prototype instanceof fragments.Fragment) {
655 throw new Error('Can\'t create a fragment: `Type` is not a valid Fragment');
657 return new Type(this, params);
661 var Transaction = function(transformations, metadata) {
662 this.transformations = transformations || [];
663 this.metadata = metadata;
665 $.extend(Transaction.prototype, {
666 pushTransformation: function(transformation) {
667 this.transformations.push(transformation);
669 hasTransformations: function() {
670 return this.transformations.length > 0;
676 documentFromXML: function(xml) {
677 var doc = new Document(xml);
681 elementNodeFromXML: function(xml) {
682 return this.documentFromXML(xml).root;
686 DocumentNode: DocumentNode,
687 ElementNode: ElementNode,