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 this.document.trigger('change', event);
145 if(type === 'nodeAdded' && !this.document.containsNode(this) && nodeWasContained) {
146 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
147 this.document.trigger('change', event);
151 getNodeInsertion: function(node) {
152 return this.document.getNodeInsertion(node);
155 getIndex: function() {
159 return this.parent().indexOf(this);
162 getNearestElementNode: function() {
163 return this.nodeType === Node.ELEMENT_NODE ? this : this.parent();
168 var ElementNode = function(nativeNode, document) {
169 DocumentNode.call(this, nativeNode, document);
171 ElementNode.prototype = Object.create(DocumentNode.prototype);
173 $.extend(ElementNode.prototype, {
174 nodeType: Node.ELEMENT_NODE,
176 setData: function(arg1, arg2) {
177 if(arguments.length === 2) {
178 if(_.isUndefined(arg2)) {
179 this._$.removeData(arg1);
181 this._$.data(arg1, arg2);
184 this._$.removeData(_.keys(this._$.data()));
189 getData: function(key) {
191 return this._$.data(key);
193 return this._$.data();
196 getTagName: function() {
197 return this.nativeNode.tagName.toLowerCase();
200 contents: function(selector) {
202 document = this.document;
204 this._$.children(selector).each(function() {
205 toret.push(document.createDocumentNode(this));
208 this._$.contents().each(function() {
209 toret.push(document.createDocumentNode(this));
215 indexOf: function(node) {
216 return this._$.contents().index(node._$);
219 getAttr: function(name) {
220 return this._$.attr(name);
223 getAttrs: function() {
225 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
226 toret.push(this.nativeNode.attributes[i]);
231 containsNode: function(node) {
232 return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
235 getLastTextNode: function() {
236 var contents = this.contents(),
239 contents.reverse().some(function(node) {
240 if(node.nodeType === Node.TEXT_NODE) {
244 toret = node.getLastTextNode();
252 var wrapper = $('<div>');
253 wrapper.append(this._getXMLDOMToDump());
254 return wrapper.html();
257 _getXMLDOMToDump: function() {
263 var TextNode = function(nativeNode, document) {
264 DocumentNode.call(this, nativeNode, document);
266 TextNode.prototype = Object.create(DocumentNode.prototype);
268 $.extend(TextNode.prototype, {
269 nodeType: Node.TEXT_NODE,
271 getText: function() {
272 return this.nativeNode.data;
276 containsNode: function() {
280 triggerTextChangeEvent: function() {
281 var event = new events.ChangeEvent('nodeTextChange', {node: this});
282 this.document.trigger('change', event);
287 var parseXML = function(xml) {
288 var toret = $($.trim(xml));
290 throw new Error('Unable to parse XML: ' + xml);
296 var registerTransformation = function(desc, name, target) {
297 var Transformation = transformations.createContextTransformation(desc, name);
298 target[name] = function() {
300 args = Array.prototype.slice.call(arguments, 0);
301 return instance.transform(Transformation, args);
305 var registerMethod = function(methodName, method, target) {
306 if(target[methodName]) {
307 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
308 .replace('{target}', target)
309 .replace('{methodName}', methodName)
312 target[methodName] = method;
316 var Document = function(xml, extensions) {
319 this._currentTransaction = null;
320 this._transformationLevel = 0;
322 this._nodeMethods = {};
323 this._textNodeMethods = {};
324 this._elementNodeMethods = {};
325 this._nodeTransformations = {};
326 this._textNodeTransformations = {};
327 this._elementNodeTransformations = {};
329 this.registerExtension(coreTransformations);
331 (extensions || []).forEach(function(extension) {
332 this.registerExtension(extension);
337 $.extend(Document.prototype, Backbone.Events, fragments, {
338 ElementNodeFactory: ElementNode,
339 TextNodeFactory: TextNode,
341 createDocumentNode: function(from) {
342 if(!(from instanceof Node)) {
343 if(typeof from === 'string') {
344 from = parseXML(from);
345 this.normalizeXML(from);
347 if(from.text !== undefined) {
348 /* globals document */
349 from = document.createTextNode(from.text);
352 throw new Error('tagName missing');
354 var node = $('<' + from.tagName + '>');
356 _.keys(from.attrs || {}).forEach(function(key) {
357 node.attr(key, from.attrs[key]);
364 var Factory, typeMethods, typeTransformations;
365 if(from.nodeType === Node.TEXT_NODE) {
366 Factory = this.TextNodeFactory;
367 typeMethods = this._textNodeMethods;
368 typeTransformations = this._textNodeTransformations;
369 } else if(from.nodeType === Node.ELEMENT_NODE) {
370 Factory = this.ElementNodeFactory;
371 typeMethods = this._elementNodeMethods;
372 typeTransformations = this._elementNodeTransformations;
374 var toret = new Factory(from, this);
375 _.extend(toret, this._nodeMethods);
376 _.extend(toret, typeMethods);
378 _.extend(toret, this._nodeTransformations);
379 _.extend(toret, typeTransformations);
381 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
382 _.keys(toret.__super__).forEach(function(key) {
383 toret.__super__[key] = _.bind(toret.__super__[key], toret);
389 loadXML: function(xml, options) {
390 options = options || {};
391 this._defineDocumentProperties($(parseXML(xml)));
392 this.normalizeXML(this.dom);
393 if(!options.silent) {
394 this.trigger('contentSet');
398 normalizeXML: function(nativeNode) {
399 void(nativeNode); // noop
403 return this.root.toXML();
406 containsNode: function(node) {
407 return this.root && this.root.containsNode(node);
410 getSiblingParents: function(params) {
411 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
412 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
413 noSiblingParents = null;
415 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
416 return noSiblingParents;
419 var stop = Math.min(parents1.length, parents2.length),
421 for(i = 0; i < stop; i++) {
422 if(parents1[i].sameNode(parents2[i])) {
430 return {node1: parents1[i], node2: parents2[i]};
433 trigger: function() {
434 Backbone.Events.trigger.apply(this, arguments);
437 getNodeInsertion: function(node) {
439 if(node instanceof DocumentNode) {
440 insertion.ofNode = node;
441 insertion.insertsNew = !this.containsNode(node);
443 insertion.ofNode = this.createDocumentNode(node);
444 insertion.insertsNew = true;
449 registerMethod: function(methodName, method, dstName) {
453 documentNode: doc._nodeMethods,
454 textNode: doc._textNodeMethods,
455 elementNode: doc._elementNodeMethods
457 registerMethod(methodName, method, destination);
460 registerTransformation: function(desc, name, dstName) {
464 documentNode: doc._nodeTransformations,
465 textNode: doc._textNodeTransformations,
466 elementNode: doc._elementNodeTransformations
468 registerTransformation(desc, name, destination);
471 registerExtension: function(extension) {
474 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
475 var dstExtension = extension[dstName];
477 if(dstExtension.methods) {
478 _.pairs(dstExtension.methods).forEach(function(pair) {
479 var methodName = pair[0],
482 doc.registerMethod(methodName, method, dstName);
487 if(dstExtension.transformations) {
488 _.pairs(dstExtension.transformations).forEach(function(pair) {
491 doc.registerTransformation(desc, name, dstName);
498 ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
499 var hasChanged = false,
500 changeMonitor = function() {
504 this.on('change', changeMonitor);
505 action.call(context);
506 this.off('change', changeMonitor);
509 if(documentChangedHandler) {
510 documentChangedHandler.call(context);
513 if(documentUnchangedHandler) {
514 documentUnchangedHandler.call(context);
519 transform: function(Transformation, args) {
520 var toret, transformation;
522 if(!this._currentTransaction) {
523 return this.transaction(function() {
524 return this.transform(Transformation, args);
528 if(typeof Transformation === 'function') {
529 transformation = new Transformation(this, this, args);
531 transformation = Transformation;
534 this._transformationLevel++;
539 toret = transformation.run({beUndoable:this._transformationLevel === 1});
542 if(this._transformationLevel === 1 && !this._undoInProgress) {
543 this._currentTransaction.pushTransformation(transformation);
549 this._transformationLevel--;
552 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
556 var transaction = this.undoStack.pop(),
558 transformations, stopAt;
561 this._undoInProgress = true;
563 // We will modify this array in a minute so make sure we work on a copy.
564 transformations = transaction.transformations.slice(0);
566 if(transformations.length > 1) {
567 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
569 transformations.some(function(t, idx) {
570 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
575 if(stopAt !== undefined) {
576 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
577 transformations = transformations.slice(0, stopAt+1);
581 transformations.reverse();
582 transformations.forEach(function(t) {
586 this._undoInProgress = false;
587 this.redoStack.push(transaction);
588 this.trigger('operationEnd');
592 var transaction = this.redoStack.pop();
594 this._transformationLevel++;
595 transaction.transformations.forEach(function(t) {
596 t.run({beUndoable: true});
598 this._transformationLevel--;
599 this.undoStack.push(transaction);
600 this.trigger('operationEnd');
605 startTransaction: function(metadata) {
606 if(this._currentTransaction) {
607 throw new Error('Nested transactions not supported!');
609 this._rollbackBackup = this.root.clone();
610 this._currentTransaction = new Transaction([], metadata);
613 endTransaction: function() {
614 if(!this._currentTransaction) {
615 throw new Error('End of transaction requested, but there is no transaction in progress!');
617 if(this._currentTransaction.hasTransformations()) {
618 this.undoStack.push(this._currentTransaction);
619 this.trigger('operationEnd');
621 this._currentTransaction = null;
624 rollbackTransaction: function() {
625 if(!this._currentTransaction) {
626 throw new Error('Transaction rollback requested, but there is no transaction in progress!');
628 this.replaceRoot(this._rollbackBackup);
629 this._rollbackBackup = null;
630 this._currentTransaction = null;
631 this._transformationLevel = 0;
634 transaction: function(callback, params) {
636 params = params || {};
637 this.startTransaction(params.metadata);
639 toret = callback.call(params.context || this);
644 this.rollbackTransaction();
647 this.endTransaction();
649 params.success(toret);
654 getNodeByPath: function(path) {
655 var toret = this.root;
656 path.forEach(function(idx) {
657 toret = toret.contents()[idx];
662 _defineDocumentProperties: function($document) {
664 Object.defineProperty(doc, 'root', {get: function() {
668 return doc.createDocumentNode($document[0]);
669 }, configurable: true});
670 Object.defineProperty(doc, 'dom', {get: function() {
675 }, configurable: true});
678 createFragment: function(Type, params) {
679 if(!Type.prototype instanceof fragments.Fragment) {
680 throw new Error('Can\'t create a fragment: `Type` is not a valid Fragment');
682 return new Type(this, params);
686 var Transaction = function(transformations, metadata) {
687 this.transformations = transformations || [];
688 this.metadata = metadata;
690 $.extend(Transaction.prototype, {
691 pushTransformation: function(transformation) {
692 this.transformations.push(transformation);
694 hasTransformations: function() {
695 return this.transformations.length > 0;
701 documentFromXML: function(xml) {
702 var doc = new Document(xml);
706 elementNodeFromXML: function(xml) {
707 return this.documentFromXML(xml).root;
711 DocumentNode: DocumentNode,
712 ElementNode: ElementNode,