6 'smartxml/transformations',
8 ], function($, _, Backbone, events, transformations, coreTransformations) {
14 var DocumentNode = function(nativeNode, document) {
16 throw new Error('undefined document for a node');
18 this.document = document;
19 this._setNativeNode(nativeNode);
23 $.extend(DocumentNode.prototype, {
25 transform: function(Transformation, args) {
26 var transformation = new Transformation(this.document, this, args);
27 return this.document.transform(transformation);
30 _setNativeNode: function(nativeNode) {
31 this.nativeNode = nativeNode;
32 this._$ = $(nativeNode);
36 var clone = this._$.clone(true, true),
38 clone.find('*').addBack().each(function() {
40 clonedData = $(this).data();
42 _.pairs(clonedData).forEach(function(pair) {
45 if(_.isFunction(value.clone)) {
46 clonedData[key] = value.clone(node.document.createDocumentNode(el));
50 return this.document.createDocumentNode(clone[0]);
53 getPath: function(ancestor) {
54 if(!(this.document.containsNode(this))) {
58 var nodePath = [this].concat(this.parents()),
60 ancestor = ancestor || this.document.root;
62 nodePath.some(function(node, i) {
63 if(node.sameNode(ancestor)) {
69 if(idx !== undefined) {
70 nodePath = nodePath.slice(0, idx);
72 toret = nodePath.map(function(node) {return node.getIndex(); });
78 return this.document.root.sameNode(this);
81 sameNode: function(otherNode) {
82 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
86 var parentNode = this.nativeNode.parentNode;
87 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
88 return this.document.createDocumentNode(parentNode);
94 var parent = this.parent(),
95 parents = parent ? parent.parents() : [];
97 parents.unshift(parent);
103 var myIdx = this.getIndex();
104 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
111 var myIdx = this.getIndex(),
112 parentContents = this.parent().contents();
113 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
116 isSurroundedByTextElements: function() {
117 var prev = this.prev(),
119 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
122 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
123 var node = (metaData && metaData.node) ? metaData.node : this,
124 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
125 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
126 if(type === 'nodeMoved') {
127 event.meta.parent = origParent;
129 this.document.trigger('change', event);
131 if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
132 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
133 this.document.trigger('change', event);
137 getNodeInsertion: function(node) {
138 return this.document.getNodeInsertion(node);
141 getIndex: function() {
145 return this.parent().indexOf(this);
150 var ElementNode = function(nativeNode, document) {
151 DocumentNode.call(this, nativeNode, document);
153 ElementNode.prototype = Object.create(DocumentNode.prototype);
155 $.extend(ElementNode.prototype, {
156 nodeType: Node.ELEMENT_NODE,
158 setData: function(key, value) {
159 if(value !== undefined) {
160 this._$.data(key, value);
162 this._$.removeData(_.keys(this._$.data()));
167 getData: function(key) {
169 return this._$.data(key);
171 return this._$.data();
174 getTagName: function() {
175 return this.nativeNode.tagName.toLowerCase();
178 contents: function(selector) {
180 document = this.document;
182 this._$.children(selector).each(function() {
183 toret.push(document.createDocumentNode(this));
186 this._$.contents().each(function() {
187 toret.push(document.createDocumentNode(this));
193 indexOf: function(node) {
194 return this._$.contents().index(node._$);
197 getAttr: function(name) {
198 return this._$.attr(name);
201 getAttrs: function() {
203 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
204 toret.push(this.nativeNode.attributes[i]);
209 containsNode: function(node) {
210 return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
214 var wrapper = $('<div>');
215 wrapper.append(this._getXMLDOMToDump());
216 return wrapper.html();
219 _getXMLDOMToDump: function() {
225 var TextNode = function(nativeNode, document) {
226 DocumentNode.call(this, nativeNode, document);
228 TextNode.prototype = Object.create(DocumentNode.prototype);
230 $.extend(TextNode.prototype, {
231 nodeType: Node.TEXT_NODE,
233 getText: function() {
234 return this.nativeNode.data;
237 triggerTextChangeEvent: function() {
238 var event = new events.ChangeEvent('nodeTextChange', {node: this});
239 this.document.trigger('change', event);
244 var parseXML = function(xml) {
245 var toret = $($.trim(xml));
247 throw new Error('Unable to parse XML: ' + xml);
253 var registerTransformation = function(desc, name, target) {
254 var Transformation = transformations.createContextTransformation(desc, name);
255 target[name] = function() {
257 args = Array.prototype.slice.call(arguments, 0);
258 return instance.transform(Transformation, args);
262 var registerMethod = function(methodName, method, target) {
263 if(target[methodName]) {
264 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
265 .replace('{target}', target)
266 .replace('{methodName}', methodName)
269 target[methodName] = method;
273 var Document = function(xml, extensions) {
276 this._currentTransaction = null;
277 this._transformationLevel = 0;
279 this._nodeMethods = {};
280 this._textNodeMethods = {};
281 this._elementNodeMethods = {};
282 this._nodeTransformations = {};
283 this._textNodeTransformations = {};
284 this._elementNodeTransformations = {};
286 this.registerExtension(coreTransformations);
288 (extensions || []).forEach(function(extension) {
289 this.registerExtension(extension);
294 $.extend(Document.prototype, Backbone.Events, {
295 ElementNodeFactory: ElementNode,
296 TextNodeFactory: TextNode,
298 createDocumentNode: function(from) {
299 if(!(from instanceof Node)) {
300 if(typeof from === 'string') {
301 from = parseXML(from);
302 this.normalizeXML(from);
304 if(from.text !== undefined) {
305 /* globals document */
306 from = document.createTextNode(from.text);
309 throw new Error('tagName missing');
311 var node = $('<' + from.tagName + '>');
313 _.keys(from.attrs || {}).forEach(function(key) {
314 node.attr(key, from.attrs[key]);
321 var Factory, typeMethods, typeTransformations;
322 if(from.nodeType === Node.TEXT_NODE) {
323 Factory = this.TextNodeFactory;
324 typeMethods = this._textNodeMethods;
325 typeTransformations = this._textNodeTransformations;
326 } else if(from.nodeType === Node.ELEMENT_NODE) {
327 Factory = this.ElementNodeFactory;
328 typeMethods = this._elementNodeMethods;
329 typeTransformations = this._elementNodeTransformations;
331 var toret = new Factory(from, this);
332 _.extend(toret, this._nodeMethods);
333 _.extend(toret, typeMethods);
335 _.extend(toret, this._nodeTransformations);
336 _.extend(toret, typeTransformations);
338 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
339 _.keys(toret.__super__).forEach(function(key) {
340 toret.__super__[key] = _.bind(toret.__super__[key], toret);
346 loadXML: function(xml, options) {
347 options = options || {};
348 this._defineDocumentProperties($(parseXML(xml)));
349 this.normalizeXML(this.dom);
350 if(!options.silent) {
351 this.trigger('contentSet');
355 normalizeXML: function(nativeNode) {
356 void(nativeNode); // noop
360 return this.root.toXML();
363 containsNode: function(node) {
364 return this.root && this.root.containsNode(node);
367 getSiblingParents: function(params) {
368 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
369 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
370 noSiblingParents = null;
372 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
373 return noSiblingParents;
376 var stop = Math.min(parents1.length, parents2.length),
378 for(i = 0; i < stop; i++) {
379 if(parents1[i].sameNode(parents2[i])) {
387 return {node1: parents1[i], node2: parents2[i]};
390 trigger: function() {
391 Backbone.Events.trigger.apply(this, arguments);
394 getNodeInsertion: function(node) {
396 if(node instanceof DocumentNode) {
397 insertion.ofNode = node;
398 insertion.insertsNew = !this.containsNode(node);
400 insertion.ofNode = this.createDocumentNode(node);
401 insertion.insertsNew = true;
406 registerMethod: function(methodName, method, dstName) {
410 documentNode: doc._nodeMethods,
411 textNode: doc._textNodeMethods,
412 elementNode: doc._elementNodeMethods
414 registerMethod(methodName, method, destination);
417 registerTransformation: function(desc, name, dstName) {
421 documentNode: doc._nodeTransformations,
422 textNode: doc._textNodeTransformations,
423 elementNode: doc._elementNodeTransformations
425 registerTransformation(desc, name, destination);
428 registerExtension: function(extension) {
431 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
432 var dstExtension = extension[dstName];
434 if(dstExtension.methods) {
435 _.pairs(dstExtension.methods).forEach(function(pair) {
436 var methodName = pair[0],
439 doc.registerMethod(methodName, method, dstName);
444 if(dstExtension.transformations) {
445 _.pairs(dstExtension.transformations).forEach(function(pair) {
448 doc.registerTransformation(desc, name, dstName);
455 ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
456 var hasChanged = false,
457 changeMonitor = function() {
461 this.on('change', changeMonitor);
462 action.call(context);
463 this.off('change', changeMonitor);
466 if(documentChangedHandler) {
467 documentChangedHandler.call(context);
470 if(documentUnchangedHandler) {
471 documentUnchangedHandler.call(context);
476 transform: function(Transformation, args) {
477 var toret, transformation;
479 if(!this._currentTransaction) {
480 return this.transaction(function() {
481 return this.transform(Transformation, args);
485 if(typeof Transformation === 'function') {
486 transformation = new Transformation(this, this, args);
488 transformation = Transformation;
491 this._transformationLevel++;
496 toret = transformation.run({beUndoable:this._transformationLevel === 1});
499 if(this._transformationLevel === 1 && !this._undoInProgress) {
500 this._currentTransaction.pushTransformation(transformation);
506 this._transformationLevel--;
509 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
513 var transaction = this.undoStack.pop(),
515 transformations, stopAt;
518 this._undoInProgress = true;
520 // We will modify this array in a minute so make sure we work on a copy.
521 transformations = transaction.transformations.slice(0);
523 if(transformations.length > 1) {
524 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
526 transformations.some(function(t, idx) {
527 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
532 if(stopAt !== undefined) {
533 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
534 transformations = transformations.slice(0, stopAt+1);
538 transformations.reverse();
539 transformations.forEach(function(t) {
543 this._undoInProgress = false;
544 this.redoStack.push(transaction);
548 var transaction = this.redoStack.pop();
550 this._transformationLevel++;
551 transaction.transformations.forEach(function(t) {
552 t.run({beUndoable: true});
554 this._transformationLevel--;
555 this.undoStack.push(transaction);
559 startTransaction: function(metadata) {
560 if(this._currentTransaction) {
561 throw new Error('Nested transactions not supported!');
563 this._currentTransaction = new Transaction([], metadata);
566 endTransaction: function() {
567 if(!this._currentTransaction) {
568 throw new Error('End of transaction requested, but there is no transaction in progress!');
570 if(this._currentTransaction.hasTransformations()) {
571 this.undoStack.push(this._currentTransaction);
573 this._currentTransaction = null;
576 transaction: function(callback, context, metadata) {
578 this.startTransaction(metadata);
579 toret = callback.call(context);
580 this.endTransaction();
584 getNodeByPath: function(path) {
585 var toret = this.root;
586 path.forEach(function(idx) {
587 toret = toret.contents()[idx];
592 _defineDocumentProperties: function($document) {
594 Object.defineProperty(doc, 'root', {get: function() {
598 return doc.createDocumentNode($document[0]);
599 }, configurable: true});
600 Object.defineProperty(doc, 'dom', {get: function() {
605 }, configurable: true});
609 var Transaction = function(transformations, metadata) {
610 this.transformations = transformations || [];
611 this.metadata = metadata;
613 $.extend(Transaction.prototype, {
614 pushTransformation: function(transformation) {
615 this.transformations.push(transformation);
617 hasTransformations: function() {
618 return this.transformations.length > 0;
624 documentFromXML: function(xml) {
625 var doc = new Document(xml);
629 elementNodeFromXML: function(xml) {
630 return this.documentFromXML(xml).root;
634 DocumentNode: DocumentNode,
635 ElementNode: ElementNode,