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(key, value) {
180 if(value !== undefined) {
181 this._$.data(key, value);
183 this._$.removeData(_.keys(this._$.data()));
188 getData: function(key) {
190 return this._$.data(key);
192 return this._$.data();
195 getTagName: function() {
196 return this.nativeNode.tagName.toLowerCase();
199 contents: function(selector) {
201 document = this.document;
203 this._$.children(selector).each(function() {
204 toret.push(document.createDocumentNode(this));
207 this._$.contents().each(function() {
208 toret.push(document.createDocumentNode(this));
214 indexOf: function(node) {
215 return this._$.contents().index(node._$);
218 getAttr: function(name) {
219 return this._$.attr(name);
222 getAttrs: function() {
224 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
225 toret.push(this.nativeNode.attributes[i]);
230 containsNode: function(node) {
231 return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
234 getLastTextNode: function() {
235 var contents = this.contents(),
238 contents.reverse().some(function(node) {
239 if(node.nodeType === Node.TEXT_NODE) {
243 toret = node.getLastTextNode();
251 var wrapper = $('<div>');
252 wrapper.append(this._getXMLDOMToDump());
253 return wrapper.html();
256 _getXMLDOMToDump: function() {
262 var TextNode = function(nativeNode, document) {
263 DocumentNode.call(this, nativeNode, document);
265 TextNode.prototype = Object.create(DocumentNode.prototype);
267 $.extend(TextNode.prototype, {
268 nodeType: Node.TEXT_NODE,
270 getText: function() {
271 return this.nativeNode.data;
275 containsNode: function() {
279 triggerTextChangeEvent: function() {
280 var event = new events.ChangeEvent('nodeTextChange', {node: this});
281 this.document.trigger('change', event);
286 var parseXML = function(xml) {
287 var toret = $($.trim(xml));
289 throw new Error('Unable to parse XML: ' + xml);
295 var registerTransformation = function(desc, name, target) {
296 var Transformation = transformations.createContextTransformation(desc, name);
297 target[name] = function() {
299 args = Array.prototype.slice.call(arguments, 0);
300 return instance.transform(Transformation, args);
304 var registerMethod = function(methodName, method, target) {
305 if(target[methodName]) {
306 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
307 .replace('{target}', target)
308 .replace('{methodName}', methodName)
311 target[methodName] = method;
315 var Document = function(xml, extensions) {
318 this._currentTransaction = null;
319 this._transformationLevel = 0;
321 this._nodeMethods = {};
322 this._textNodeMethods = {};
323 this._elementNodeMethods = {};
324 this._nodeTransformations = {};
325 this._textNodeTransformations = {};
326 this._elementNodeTransformations = {};
328 this.registerExtension(coreTransformations);
330 (extensions || []).forEach(function(extension) {
331 this.registerExtension(extension);
336 $.extend(Document.prototype, Backbone.Events, fragments, {
337 ElementNodeFactory: ElementNode,
338 TextNodeFactory: TextNode,
340 createDocumentNode: function(from) {
341 if(!(from instanceof Node)) {
342 if(typeof from === 'string') {
343 from = parseXML(from);
344 this.normalizeXML(from);
346 if(from.text !== undefined) {
347 /* globals document */
348 from = document.createTextNode(from.text);
351 throw new Error('tagName missing');
353 var node = $('<' + from.tagName + '>');
355 _.keys(from.attrs || {}).forEach(function(key) {
356 node.attr(key, from.attrs[key]);
363 var Factory, typeMethods, typeTransformations;
364 if(from.nodeType === Node.TEXT_NODE) {
365 Factory = this.TextNodeFactory;
366 typeMethods = this._textNodeMethods;
367 typeTransformations = this._textNodeTransformations;
368 } else if(from.nodeType === Node.ELEMENT_NODE) {
369 Factory = this.ElementNodeFactory;
370 typeMethods = this._elementNodeMethods;
371 typeTransformations = this._elementNodeTransformations;
373 var toret = new Factory(from, this);
374 _.extend(toret, this._nodeMethods);
375 _.extend(toret, typeMethods);
377 _.extend(toret, this._nodeTransformations);
378 _.extend(toret, typeTransformations);
380 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
381 _.keys(toret.__super__).forEach(function(key) {
382 toret.__super__[key] = _.bind(toret.__super__[key], toret);
388 loadXML: function(xml, options) {
389 options = options || {};
390 this._defineDocumentProperties($(parseXML(xml)));
391 this.normalizeXML(this.dom);
392 if(!options.silent) {
393 this.trigger('contentSet');
397 normalizeXML: function(nativeNode) {
398 void(nativeNode); // noop
402 return this.root.toXML();
405 containsNode: function(node) {
406 return this.root && this.root.containsNode(node);
409 getSiblingParents: function(params) {
410 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
411 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
412 noSiblingParents = null;
414 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
415 return noSiblingParents;
418 var stop = Math.min(parents1.length, parents2.length),
420 for(i = 0; i < stop; i++) {
421 if(parents1[i].sameNode(parents2[i])) {
429 return {node1: parents1[i], node2: parents2[i]};
432 trigger: function() {
433 Backbone.Events.trigger.apply(this, arguments);
436 getNodeInsertion: function(node) {
438 if(node instanceof DocumentNode) {
439 insertion.ofNode = node;
440 insertion.insertsNew = !this.containsNode(node);
442 insertion.ofNode = this.createDocumentNode(node);
443 insertion.insertsNew = true;
448 registerMethod: function(methodName, method, dstName) {
452 documentNode: doc._nodeMethods,
453 textNode: doc._textNodeMethods,
454 elementNode: doc._elementNodeMethods
456 registerMethod(methodName, method, destination);
459 registerTransformation: function(desc, name, dstName) {
463 documentNode: doc._nodeTransformations,
464 textNode: doc._textNodeTransformations,
465 elementNode: doc._elementNodeTransformations
467 registerTransformation(desc, name, destination);
470 registerExtension: function(extension) {
473 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
474 var dstExtension = extension[dstName];
476 if(dstExtension.methods) {
477 _.pairs(dstExtension.methods).forEach(function(pair) {
478 var methodName = pair[0],
481 doc.registerMethod(methodName, method, dstName);
486 if(dstExtension.transformations) {
487 _.pairs(dstExtension.transformations).forEach(function(pair) {
490 doc.registerTransformation(desc, name, dstName);
497 ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
498 var hasChanged = false,
499 changeMonitor = function() {
503 this.on('change', changeMonitor);
504 action.call(context);
505 this.off('change', changeMonitor);
508 if(documentChangedHandler) {
509 documentChangedHandler.call(context);
512 if(documentUnchangedHandler) {
513 documentUnchangedHandler.call(context);
518 transform: function(Transformation, args) {
519 var toret, transformation;
521 if(!this._currentTransaction) {
522 return this.transaction(function() {
523 return this.transform(Transformation, args);
527 if(typeof Transformation === 'function') {
528 transformation = new Transformation(this, this, args);
530 transformation = Transformation;
533 this._transformationLevel++;
538 toret = transformation.run({beUndoable:this._transformationLevel === 1});
541 if(this._transformationLevel === 1 && !this._undoInProgress) {
542 this._currentTransaction.pushTransformation(transformation);
548 this._transformationLevel--;
551 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
555 var transaction = this.undoStack.pop(),
557 transformations, stopAt;
560 this._undoInProgress = true;
562 // We will modify this array in a minute so make sure we work on a copy.
563 transformations = transaction.transformations.slice(0);
565 if(transformations.length > 1) {
566 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
568 transformations.some(function(t, idx) {
569 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
574 if(stopAt !== undefined) {
575 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
576 transformations = transformations.slice(0, stopAt+1);
580 transformations.reverse();
581 transformations.forEach(function(t) {
585 this._undoInProgress = false;
586 this.redoStack.push(transaction);
587 this.trigger('operationEnd');
591 var transaction = this.redoStack.pop();
593 this._transformationLevel++;
594 transaction.transformations.forEach(function(t) {
595 t.run({beUndoable: true});
597 this._transformationLevel--;
598 this.undoStack.push(transaction);
599 this.trigger('operationEnd');
604 startTransaction: function(metadata) {
605 if(this._currentTransaction) {
606 throw new Error('Nested transactions not supported!');
608 this._rollbackBackup = this.root.clone();
609 this._currentTransaction = new Transaction([], metadata);
612 endTransaction: function() {
613 if(!this._currentTransaction) {
614 throw new Error('End of transaction requested, but there is no transaction in progress!');
616 if(this._currentTransaction.hasTransformations()) {
617 this.undoStack.push(this._currentTransaction);
618 this.trigger('operationEnd');
620 this._currentTransaction = null;
623 rollbackTransaction: function() {
624 if(!this._currentTransaction) {
625 throw new Error('Transaction rollback requested, but there is no transaction in progress!');
627 this.replaceRoot(this._rollbackBackup);
628 this._rollbackBackup = null;
629 this._currentTransaction = null;
630 this._transformationLevel = 0;
633 transaction: function(callback, params) {
635 params = params || {};
636 this.startTransaction(params.metadata);
638 toret = callback.call(params.context || this);
643 this.rollbackTransaction();
646 this.endTransaction();
648 params.success(toret);
653 getNodeByPath: function(path) {
654 var toret = this.root;
655 path.forEach(function(idx) {
656 toret = toret.contents()[idx];
661 _defineDocumentProperties: function($document) {
663 Object.defineProperty(doc, 'root', {get: function() {
667 return doc.createDocumentNode($document[0]);
668 }, configurable: true});
669 Object.defineProperty(doc, 'dom', {get: function() {
674 }, configurable: true});
677 createFragment: function(Type, params) {
678 if(!Type.prototype instanceof fragments.Fragment) {
679 throw new Error('Can\'t create a fragment: `Type` is not a valid Fragment');
681 return new Type(this, params);
685 var Transaction = function(transformations, metadata) {
686 this.transformations = transformations || [];
687 this.metadata = metadata;
689 $.extend(Transaction.prototype, {
690 pushTransformation: function(transformation) {
691 this.transformations.push(transformation);
693 hasTransformations: function() {
694 return this.transformations.length > 0;
700 documentFromXML: function(xml) {
701 var doc = new Document(xml);
705 elementNodeFromXML: function(xml) {
706 return this.documentFromXML(xml).root;
710 DocumentNode: DocumentNode,
711 ElementNode: ElementNode,