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 isSiblingOf: function(node) {
82 return node && this.parent().sameNode(node.parent());
85 sameNode: function(otherNode) {
86 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
90 var parentNode = this.nativeNode.parentNode;
91 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
92 return this.document.createDocumentNode(parentNode);
98 var parent = this.parent(),
99 parents = parent ? parent.parents() : [];
101 parents.unshift(parent);
107 var myIdx = this.getIndex();
108 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
115 var myIdx = this.getIndex(),
116 parentContents = this.parent().contents();
117 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
120 isSurroundedByTextElements: function() {
121 var prev = this.prev(),
123 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
126 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
127 var node = (metaData && metaData.node) ? metaData.node : this,
128 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
129 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
130 if(type === 'nodeMoved') {
131 event.meta.parent = origParent;
133 this.document.trigger('change', event);
135 if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
136 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
137 this.document.trigger('change', event);
141 getNodeInsertion: function(node) {
142 return this.document.getNodeInsertion(node);
145 getIndex: function() {
149 return this.parent().indexOf(this);
152 getNearestElementNode: function() {
153 return this.nodeType === Node.ELEMENT_NODE ? this : this.parent();
158 var ElementNode = function(nativeNode, document) {
159 DocumentNode.call(this, nativeNode, document);
161 ElementNode.prototype = Object.create(DocumentNode.prototype);
163 $.extend(ElementNode.prototype, {
164 nodeType: Node.ELEMENT_NODE,
166 setData: function(key, value) {
167 if(value !== undefined) {
168 this._$.data(key, value);
170 this._$.removeData(_.keys(this._$.data()));
175 getData: function(key) {
177 return this._$.data(key);
179 return this._$.data();
182 getTagName: function() {
183 return this.nativeNode.tagName.toLowerCase();
186 contents: function(selector) {
188 document = this.document;
190 this._$.children(selector).each(function() {
191 toret.push(document.createDocumentNode(this));
194 this._$.contents().each(function() {
195 toret.push(document.createDocumentNode(this));
201 indexOf: function(node) {
202 return this._$.contents().index(node._$);
205 getAttr: function(name) {
206 return this._$.attr(name);
209 getAttrs: function() {
211 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
212 toret.push(this.nativeNode.attributes[i]);
217 containsNode: function(node) {
218 return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
222 var wrapper = $('<div>');
223 wrapper.append(this._getXMLDOMToDump());
224 return wrapper.html();
227 _getXMLDOMToDump: function() {
233 var TextNode = function(nativeNode, document) {
234 DocumentNode.call(this, nativeNode, document);
236 TextNode.prototype = Object.create(DocumentNode.prototype);
238 $.extend(TextNode.prototype, {
239 nodeType: Node.TEXT_NODE,
241 getText: function() {
242 return this.nativeNode.data;
245 triggerTextChangeEvent: function() {
246 var event = new events.ChangeEvent('nodeTextChange', {node: this});
247 this.document.trigger('change', event);
252 var parseXML = function(xml) {
253 var toret = $($.trim(xml));
255 throw new Error('Unable to parse XML: ' + xml);
261 var registerTransformation = function(desc, name, target) {
262 var Transformation = transformations.createContextTransformation(desc, name);
263 target[name] = function() {
265 args = Array.prototype.slice.call(arguments, 0);
266 return instance.transform(Transformation, args);
270 var registerMethod = function(methodName, method, target) {
271 if(target[methodName]) {
272 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
273 .replace('{target}', target)
274 .replace('{methodName}', methodName)
277 target[methodName] = method;
281 var Document = function(xml, extensions) {
284 this._currentTransaction = null;
285 this._transformationLevel = 0;
287 this._nodeMethods = {};
288 this._textNodeMethods = {};
289 this._elementNodeMethods = {};
290 this._nodeTransformations = {};
291 this._textNodeTransformations = {};
292 this._elementNodeTransformations = {};
294 this.registerExtension(coreTransformations);
296 (extensions || []).forEach(function(extension) {
297 this.registerExtension(extension);
302 $.extend(Document.prototype, Backbone.Events, {
303 ElementNodeFactory: ElementNode,
304 TextNodeFactory: TextNode,
306 createDocumentNode: function(from) {
307 if(!(from instanceof Node)) {
308 if(typeof from === 'string') {
309 from = parseXML(from);
310 this.normalizeXML(from);
312 if(from.text !== undefined) {
313 /* globals document */
314 from = document.createTextNode(from.text);
317 throw new Error('tagName missing');
319 var node = $('<' + from.tagName + '>');
321 _.keys(from.attrs || {}).forEach(function(key) {
322 node.attr(key, from.attrs[key]);
329 var Factory, typeMethods, typeTransformations;
330 if(from.nodeType === Node.TEXT_NODE) {
331 Factory = this.TextNodeFactory;
332 typeMethods = this._textNodeMethods;
333 typeTransformations = this._textNodeTransformations;
334 } else if(from.nodeType === Node.ELEMENT_NODE) {
335 Factory = this.ElementNodeFactory;
336 typeMethods = this._elementNodeMethods;
337 typeTransformations = this._elementNodeTransformations;
339 var toret = new Factory(from, this);
340 _.extend(toret, this._nodeMethods);
341 _.extend(toret, typeMethods);
343 _.extend(toret, this._nodeTransformations);
344 _.extend(toret, typeTransformations);
346 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
347 _.keys(toret.__super__).forEach(function(key) {
348 toret.__super__[key] = _.bind(toret.__super__[key], toret);
354 loadXML: function(xml, options) {
355 options = options || {};
356 this._defineDocumentProperties($(parseXML(xml)));
357 this.normalizeXML(this.dom);
358 if(!options.silent) {
359 this.trigger('contentSet');
363 normalizeXML: function(nativeNode) {
364 void(nativeNode); // noop
368 return this.root.toXML();
371 containsNode: function(node) {
372 return this.root && this.root.containsNode(node);
375 getSiblingParents: function(params) {
376 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
377 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
378 noSiblingParents = null;
380 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
381 return noSiblingParents;
384 var stop = Math.min(parents1.length, parents2.length),
386 for(i = 0; i < stop; i++) {
387 if(parents1[i].sameNode(parents2[i])) {
395 return {node1: parents1[i], node2: parents2[i]};
398 trigger: function() {
399 Backbone.Events.trigger.apply(this, arguments);
402 getNodeInsertion: function(node) {
404 if(node instanceof DocumentNode) {
405 insertion.ofNode = node;
406 insertion.insertsNew = !this.containsNode(node);
408 insertion.ofNode = this.createDocumentNode(node);
409 insertion.insertsNew = true;
414 registerMethod: function(methodName, method, dstName) {
418 documentNode: doc._nodeMethods,
419 textNode: doc._textNodeMethods,
420 elementNode: doc._elementNodeMethods
422 registerMethod(methodName, method, destination);
425 registerTransformation: function(desc, name, dstName) {
429 documentNode: doc._nodeTransformations,
430 textNode: doc._textNodeTransformations,
431 elementNode: doc._elementNodeTransformations
433 registerTransformation(desc, name, destination);
436 registerExtension: function(extension) {
439 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
440 var dstExtension = extension[dstName];
442 if(dstExtension.methods) {
443 _.pairs(dstExtension.methods).forEach(function(pair) {
444 var methodName = pair[0],
447 doc.registerMethod(methodName, method, dstName);
452 if(dstExtension.transformations) {
453 _.pairs(dstExtension.transformations).forEach(function(pair) {
456 doc.registerTransformation(desc, name, dstName);
463 ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
464 var hasChanged = false,
465 changeMonitor = function() {
469 this.on('change', changeMonitor);
470 action.call(context);
471 this.off('change', changeMonitor);
474 if(documentChangedHandler) {
475 documentChangedHandler.call(context);
478 if(documentUnchangedHandler) {
479 documentUnchangedHandler.call(context);
484 transform: function(Transformation, args) {
485 var toret, transformation;
487 if(!this._currentTransaction) {
488 return this.transaction(function() {
489 return this.transform(Transformation, args);
493 if(typeof Transformation === 'function') {
494 transformation = new Transformation(this, this, args);
496 transformation = Transformation;
499 this._transformationLevel++;
504 toret = transformation.run({beUndoable:this._transformationLevel === 1});
507 if(this._transformationLevel === 1 && !this._undoInProgress) {
508 this._currentTransaction.pushTransformation(transformation);
514 this._transformationLevel--;
517 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
521 var transaction = this.undoStack.pop(),
523 transformations, stopAt;
526 this._undoInProgress = true;
528 // We will modify this array in a minute so make sure we work on a copy.
529 transformations = transaction.transformations.slice(0);
531 if(transformations.length > 1) {
532 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
534 transformations.some(function(t, idx) {
535 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
540 if(stopAt !== undefined) {
541 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
542 transformations = transformations.slice(0, stopAt+1);
546 transformations.reverse();
547 transformations.forEach(function(t) {
551 this._undoInProgress = false;
552 this.redoStack.push(transaction);
553 this.trigger('operationEnd');
557 var transaction = this.redoStack.pop();
559 this._transformationLevel++;
560 transaction.transformations.forEach(function(t) {
561 t.run({beUndoable: true});
563 this._transformationLevel--;
564 this.undoStack.push(transaction);
565 this.trigger('operationEnd');
570 startTransaction: function(metadata) {
571 if(this._currentTransaction) {
572 throw new Error('Nested transactions not supported!');
574 this._rollbackBackup = this.root.clone();
575 this._currentTransaction = new Transaction([], metadata);
578 endTransaction: function() {
579 if(!this._currentTransaction) {
580 throw new Error('End of transaction requested, but there is no transaction in progress!');
582 if(this._currentTransaction.hasTransformations()) {
583 this.undoStack.push(this._currentTransaction);
584 this.trigger('operationEnd');
586 this._currentTransaction = null;
589 rollbackTransaction: function() {
590 if(!this._currentTransaction) {
591 throw new Error('Transaction rollback requested, but there is no transaction in progress!');
593 this.replaceRoot(this._rollbackBackup);
594 this._rollbackBackup = null;
595 this._currentTransaction = null;
596 this._transformationLevel = 0;
599 transaction: function(callback, params) {
601 params = params || {};
602 this.startTransaction(params.metadata);
604 toret = callback.call(params.context || this);
609 this.rollbackTransaction();
612 this.endTransaction();
614 params.success(toret);
619 getNodeByPath: function(path) {
620 var toret = this.root;
621 path.forEach(function(idx) {
622 toret = toret.contents()[idx];
627 _defineDocumentProperties: function($document) {
629 Object.defineProperty(doc, 'root', {get: function() {
633 return doc.createDocumentNode($document[0]);
634 }, configurable: true});
635 Object.defineProperty(doc, 'dom', {get: function() {
640 }, configurable: true});
644 var Transaction = function(transformations, metadata) {
645 this.transformations = transformations || [];
646 this.metadata = metadata;
648 $.extend(Transaction.prototype, {
649 pushTransformation: function(transformation) {
650 this.transformations.push(transformation);
652 hasTransformations: function() {
653 return this.transformations.length > 0;
659 documentFromXML: function(xml) {
660 var doc = new Document(xml);
664 elementNodeFromXML: function(xml) {
665 return this.documentFromXML(xml).root;
669 DocumentNode: DocumentNode,
670 ElementNode: ElementNode,