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;
21 this._setNativeNode(nativeNode);
25 $.extend(DocumentNode.prototype, {
27 getProperty: function(propName) {
28 var toret = this.object[propName];
29 if(toret && _.isFunction(toret)) {
30 toret = toret.call(this);
35 transform: function(Transformation, args) {
36 var transformation = new Transformation(this.document, this, args);
37 return this.document.transform(transformation);
40 _setNativeNode: function(nativeNode) {
41 this.nativeNode = nativeNode;
42 this._$ = $(nativeNode);
46 var clone = this._$.clone(true, true),
48 clone.find('*').addBack().each(function() {
50 clonedData = $(this).data();
52 _.pairs(clonedData).forEach(function(pair) {
55 if(_.isFunction(value.clone)) {
56 clonedData[key] = value.clone(node.document.createDocumentNode(el));
60 return this.document.createDocumentNode(clone[0]);
63 getPath: function(ancestor) {
64 if(!(this.document.containsNode(this))) {
68 var nodePath = [this].concat(this.parents()),
70 ancestor = ancestor || this.document.root;
72 nodePath.some(function(node, i) {
73 if(node.sameNode(ancestor)) {
79 if(idx !== undefined) {
80 nodePath = nodePath.slice(0, idx);
82 toret = nodePath.map(function(node) {return node.getIndex(); });
88 return this.document.root.sameNode(this);
91 isInDocument: function() {
92 return this.document.containsNode(this);
95 isSiblingOf: function(node) {
96 return node && this.parent().sameNode(node.parent());
99 sameNode: function(otherNode) {
100 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
104 var parentNode = this.nativeNode.parentNode;
105 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
106 return this.document.createDocumentNode(parentNode);
111 parents: function() {
112 var parent = this.parent(),
113 parents = parent ? parent.parents() : [];
115 parents.unshift(parent);
121 var myIdx = this.getIndex();
122 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
129 var myIdx = this.getIndex(),
130 parentContents = this.parent().contents();
131 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
134 isSurroundedByTextNodes: function() {
135 return this.isPrecededByTextNode() && this.isFollowedByTextNode();
138 isPrecededByTextNode: function() {
139 var prev = this.prev();
140 return prev && prev.nodeType === Node.TEXT_NODE;
143 isFollowedByTextNode: function() {
144 var next = this.next();
145 return next && next.nodeType === Node.TEXT_NODE;
148 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
149 var node = (metaData && metaData.node) ? metaData.node : this,
150 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
151 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
152 this.document.trigger('change', event);
154 if(type === 'nodeAdded' && !this.document.containsNode(this) && nodeWasContained) {
155 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
156 this.document.trigger('change', event);
160 getNodeInsertion: function(node) {
161 return this.document.getNodeInsertion(node);
164 getIndex: function() {
171 parent = this.parent();
172 return parent ? parent.indexOf(this) : undefined;
175 getNearestElementNode: function() {
176 return this.nodeType === Node.ELEMENT_NODE ? this : this.parent();
181 var ElementNode = function(nativeNode, document) {
182 DocumentNode.call(this, nativeNode, document);
184 ElementNode.prototype = Object.create(DocumentNode.prototype);
186 $.extend(ElementNode.prototype, {
187 nodeType: Node.ELEMENT_NODE,
189 setData: function(arg1, arg2) {
190 if(arguments.length === 2) {
191 if(_.isUndefined(arg2)) {
192 this._$.removeData(arg1);
194 this._$.data(arg1, arg2);
197 this._$.removeData(_.keys(this._$.data()));
202 getData: function(key) {
204 return this._$.data(key);
206 return this._$.data();
209 getTagName: function() {
210 return this.nativeNode.tagName.toLowerCase();
213 contents: function(selector) {
215 document = this.document;
217 this._$.children(selector).each(function() {
218 toret.push(document.createDocumentNode(this));
221 this._$.contents().each(function() {
222 toret.push(document.createDocumentNode(this));
228 indexOf: function(node) {
229 return this._$.contents().index(node._$);
232 getAttr: function(name) {
233 return this._$.attr(name);
236 getAttrs: function() {
238 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
239 toret.push(this.nativeNode.attributes[i]);
244 containsNode: function(node) {
245 return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
248 getLastTextNode: function() {
249 var contents = this.contents(),
252 contents.reverse().some(function(node) {
253 if(node.nodeType === Node.TEXT_NODE) {
257 toret = node.getLastTextNode();
265 var wrapper = $('<div>');
266 wrapper.append(this._getXMLDOMToDump());
267 return wrapper.html();
270 _getXMLDOMToDump: function() {
276 var TextNode = function(nativeNode, document) {
277 DocumentNode.call(this, nativeNode, document);
279 TextNode.prototype = Object.create(DocumentNode.prototype);
281 $.extend(TextNode.prototype, {
282 nodeType: Node.TEXT_NODE,
284 getText: function() {
285 return this.nativeNode.data;
289 containsNode: function() {
293 triggerTextChangeEvent: function() {
294 var event = new events.ChangeEvent('nodeTextChange', {node: this});
295 this.document.trigger('change', event);
300 var parseXML = function(xml) {
301 var toret = $($.trim(xml));
302 if(toret.length !== 1) {
303 throw new Error('Unable to parse XML: ' + xml);
309 var registerTransformation = function(desc, name, target) {
310 var Transformation = transformations.createContextTransformation(desc, name);
311 target[name] = function() {
313 args = Array.prototype.slice.call(arguments, 0);
314 return instance.transform(Transformation, args);
318 var registerMethod = function(methodName, method, target) {
319 if(target[methodName]) {
320 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
321 .replace('{target}', target)
322 .replace('{methodName}', methodName)
325 target[methodName] = method;
329 var Document = function(xml, extensions) {
332 this._currentTransaction = null;
333 this._transformationLevel = 0;
335 this._nodeMethods = {};
336 this._textNodeMethods = {};
337 this._elementNodeMethods = {};
338 this._nodeTransformations = {};
339 this._textNodeTransformations = {};
340 this._elementNodeTransformations = {};
342 this.registerExtension(coreTransformations);
344 (extensions || []).forEach(function(extension) {
345 this.registerExtension(extension);
350 $.extend(Document.prototype, Backbone.Events, fragments, {
351 ElementNodeFactory: ElementNode,
352 TextNodeFactory: TextNode,
354 createDocumentNode: function(from) {
355 if(!(from instanceof Node)) {
356 if(typeof from === 'string') {
357 from = parseXML(from);
358 this.normalizeXML(from);
360 if(from.text !== undefined) {
361 /* globals document */
362 from = document.createTextNode(from.text);
365 throw new Error('tagName missing');
367 var node = $('<' + from.tagName + '>');
369 _.keys(from.attrs || {}).forEach(function(key) {
370 node.attr(key, from.attrs[key]);
377 var Factory, typeMethods, typeTransformations;
378 if(from.nodeType === Node.TEXT_NODE) {
379 Factory = this.TextNodeFactory;
380 typeMethods = this._textNodeMethods;
381 typeTransformations = this._textNodeTransformations;
382 } else if(from.nodeType === Node.ELEMENT_NODE) {
383 Factory = this.ElementNodeFactory;
384 typeMethods = this._elementNodeMethods;
385 typeTransformations = this._elementNodeTransformations;
387 var toret = new Factory(from, this);
388 _.extend(toret, this._nodeMethods);
389 _.extend(toret, typeMethods);
391 _.extend(toret, this._nodeTransformations);
392 _.extend(toret, typeTransformations);
394 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
395 _.keys(toret.__super__).forEach(function(key) {
396 toret.__super__[key] = _.bind(toret.__super__[key], toret);
402 loadXML: function(xml, options) {
403 options = options || {};
404 this._defineDocumentProperties($(parseXML(xml)));
405 this.normalizeXML(this.dom);
406 if(!options.silent) {
407 this.trigger('contentSet');
411 normalizeXML: function(nativeNode) {
412 void(nativeNode); // noop
416 return this.root.toXML();
419 containsNode: function(node) {
420 return this.root && this.root.containsNode(node);
423 getSiblingParents: function(params) {
424 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
425 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
426 noSiblingParents = null;
428 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
429 return noSiblingParents;
432 var stop = Math.min(parents1.length, parents2.length),
434 for(i = 0; i < stop; i++) {
435 if(parents1[i].sameNode(parents2[i])) {
443 return {node1: parents1[i], node2: parents2[i]};
446 trigger: function() {
447 Backbone.Events.trigger.apply(this, arguments);
450 getNodeInsertion: function(node) {
452 if(node instanceof DocumentNode) {
453 insertion.ofNode = node;
454 insertion.insertsNew = !this.containsNode(node);
456 insertion.ofNode = this.createDocumentNode(node);
457 insertion.insertsNew = true;
462 registerMethod: function(methodName, method, dstName) {
466 documentNode: doc._nodeMethods,
467 textNode: doc._textNodeMethods,
468 elementNode: doc._elementNodeMethods
470 registerMethod(methodName, method, destination);
473 registerTransformation: function(desc, name, dstName) {
477 documentNode: doc._nodeTransformations,
478 textNode: doc._textNodeTransformations,
479 elementNode: doc._elementNodeTransformations
481 registerTransformation(desc, name, destination);
484 registerExtension: function(extension) {
487 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
488 var dstExtension = extension[dstName];
490 if(dstExtension.methods) {
491 _.pairs(dstExtension.methods).forEach(function(pair) {
492 var methodName = pair[0],
495 doc.registerMethod(methodName, method, dstName);
500 if(dstExtension.transformations) {
501 _.pairs(dstExtension.transformations).forEach(function(pair) {
504 doc.registerTransformation(desc, name, dstName);
511 ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
512 var hasChanged = false,
513 changeMonitor = function() {
517 this.on('change', changeMonitor);
518 action.call(context);
519 this.off('change', changeMonitor);
522 if(documentChangedHandler) {
523 documentChangedHandler.call(context);
526 if(documentUnchangedHandler) {
527 documentUnchangedHandler.call(context);
532 transform: function(Transformation, args) {
533 var toret, transformation;
535 if(!this._currentTransaction) {
536 return this.transaction(function() {
537 return this.transform(Transformation, args);
541 if(typeof Transformation === 'function') {
542 transformation = new Transformation(this, this, args);
544 transformation = Transformation;
547 this._transformationLevel++;
552 toret = transformation.run({beUndoable:this._transformationLevel === 1});
555 if(this._transformationLevel === 1 && !this._undoInProgress) {
556 this._currentTransaction.pushTransformation(transformation);
562 this._transformationLevel--;
565 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
569 var transaction = this.undoStack.pop(),
571 transformations, stopAt;
574 this._undoInProgress = true;
576 // We will modify this array in a minute so make sure we work on a copy.
577 transformations = transaction.transformations.slice(0);
579 if(transformations.length > 1) {
580 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
581 transformations.some(function(t, idx) {
582 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
587 if(stopAt !== undefined) {
588 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
589 transformations = transformations.slice(0, stopAt+1);
593 transformations.reverse();
594 transformations.forEach(function(t) {
598 this._undoInProgress = false;
599 this.redoStack.push(transaction);
600 this.trigger('operationEnd');
604 var transaction = this.redoStack.pop();
606 this._transformationLevel++;
607 transaction.transformations.forEach(function(t) {
608 t.run({beUndoable: true});
610 this._transformationLevel--;
611 this.undoStack.push(transaction);
612 this.trigger('operationEnd');
617 startTransaction: function(metadata) {
618 if(this._currentTransaction) {
619 throw new Error('Nested transactions not supported!');
621 this._rollbackBackup = this.root.clone();
622 this._currentTransaction = new Transaction([], metadata);
625 endTransaction: function() {
626 if(!this._currentTransaction) {
627 throw new Error('End of transaction requested, but there is no transaction in progress!');
629 if(this._currentTransaction.hasTransformations()) {
630 this.undoStack.push(this._currentTransaction);
631 this.trigger('operationEnd');
633 this._currentTransaction = null;
636 rollbackTransaction: function() {
637 if(!this._currentTransaction) {
638 throw new Error('Transaction rollback requested, but there is no transaction in progress!');
640 this.replaceRoot(this._rollbackBackup);
641 this._rollbackBackup = null;
642 this._currentTransaction = null;
643 this._transformationLevel = 0;
646 transaction: function(callback, params) {
648 params = params || {};
649 this.startTransaction(params.metadata);
651 toret = callback.call(params.context || this);
656 this.rollbackTransaction();
659 this.endTransaction();
661 params.success(toret);
666 getNodeByPath: function(path) {
667 var toret = this.root;
668 path.some(function(idx) {
669 toret = toret.contents()[idx];
677 _defineDocumentProperties: function($document) {
679 Object.defineProperty(doc, 'root', {get: function() {
683 return doc.createDocumentNode($document[0]);
684 }, configurable: true});
685 Object.defineProperty(doc, 'dom', {get: function() {
690 }, configurable: true});
693 createFragment: function(Type, params) {
694 if(!Type.prototype instanceof fragments.Fragment) {
695 throw new Error('Can\'t create a fragment: `Type` is not a valid Fragment');
697 return new Type(this, params);
701 var Transaction = function(transformations, metadata) {
702 this.transformations = transformations || [];
703 this.metadata = metadata;
705 $.extend(Transaction.prototype, {
706 pushTransformation: function(transformation) {
707 this.transformations.push(transformation);
709 hasTransformations: function() {
710 return this.transformations.length > 0;
716 documentFromXML: function(xml) {
717 var doc = new Document(xml);
721 elementNodeFromXML: function(xml) {
722 return this.documentFromXML(xml).root;
726 DocumentNode: DocumentNode,
727 ElementNode: ElementNode,