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() {
168 return this.parent().indexOf(this);
171 getNearestElementNode: function() {
172 return this.nodeType === Node.ELEMENT_NODE ? this : this.parent();
177 var ElementNode = function(nativeNode, document) {
178 DocumentNode.call(this, nativeNode, document);
180 ElementNode.prototype = Object.create(DocumentNode.prototype);
182 $.extend(ElementNode.prototype, {
183 nodeType: Node.ELEMENT_NODE,
185 setData: function(arg1, arg2) {
186 if(arguments.length === 2) {
187 if(_.isUndefined(arg2)) {
188 this._$.removeData(arg1);
190 this._$.data(arg1, arg2);
193 this._$.removeData(_.keys(this._$.data()));
198 getData: function(key) {
200 return this._$.data(key);
202 return this._$.data();
205 getTagName: function() {
206 return this.nativeNode.tagName.toLowerCase();
209 contents: function(selector) {
211 document = this.document;
213 this._$.children(selector).each(function() {
214 toret.push(document.createDocumentNode(this));
217 this._$.contents().each(function() {
218 toret.push(document.createDocumentNode(this));
224 indexOf: function(node) {
225 return this._$.contents().index(node._$);
228 getAttr: function(name) {
229 return this._$.attr(name);
232 getAttrs: function() {
234 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
235 toret.push(this.nativeNode.attributes[i]);
240 containsNode: function(node) {
241 return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
244 getLastTextNode: function() {
245 var contents = this.contents(),
248 contents.reverse().some(function(node) {
249 if(node.nodeType === Node.TEXT_NODE) {
253 toret = node.getLastTextNode();
261 var wrapper = $('<div>');
262 wrapper.append(this._getXMLDOMToDump());
263 return wrapper.html();
266 _getXMLDOMToDump: function() {
272 var TextNode = function(nativeNode, document) {
273 DocumentNode.call(this, nativeNode, document);
275 TextNode.prototype = Object.create(DocumentNode.prototype);
277 $.extend(TextNode.prototype, {
278 nodeType: Node.TEXT_NODE,
280 getText: function() {
281 return this.nativeNode.data;
285 containsNode: function() {
289 triggerTextChangeEvent: function() {
290 var event = new events.ChangeEvent('nodeTextChange', {node: this});
291 this.document.trigger('change', event);
296 var parseXML = function(xml) {
297 var toret = $($.trim(xml));
299 throw new Error('Unable to parse XML: ' + xml);
305 var registerTransformation = function(desc, name, target) {
306 var Transformation = transformations.createContextTransformation(desc, name);
307 target[name] = function() {
309 args = Array.prototype.slice.call(arguments, 0);
310 return instance.transform(Transformation, args);
314 var registerMethod = function(methodName, method, target) {
315 if(target[methodName]) {
316 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
317 .replace('{target}', target)
318 .replace('{methodName}', methodName)
321 target[methodName] = method;
325 var Document = function(xml, extensions) {
328 this._currentTransaction = null;
329 this._transformationLevel = 0;
331 this._nodeMethods = {};
332 this._textNodeMethods = {};
333 this._elementNodeMethods = {};
334 this._nodeTransformations = {};
335 this._textNodeTransformations = {};
336 this._elementNodeTransformations = {};
338 this.registerExtension(coreTransformations);
340 (extensions || []).forEach(function(extension) {
341 this.registerExtension(extension);
346 $.extend(Document.prototype, Backbone.Events, fragments, {
347 ElementNodeFactory: ElementNode,
348 TextNodeFactory: TextNode,
350 createDocumentNode: function(from) {
351 if(!(from instanceof Node)) {
352 if(typeof from === 'string') {
353 from = parseXML(from);
354 this.normalizeXML(from);
356 if(from.text !== undefined) {
357 /* globals document */
358 from = document.createTextNode(from.text);
361 throw new Error('tagName missing');
363 var node = $('<' + from.tagName + '>');
365 _.keys(from.attrs || {}).forEach(function(key) {
366 node.attr(key, from.attrs[key]);
373 var Factory, typeMethods, typeTransformations;
374 if(from.nodeType === Node.TEXT_NODE) {
375 Factory = this.TextNodeFactory;
376 typeMethods = this._textNodeMethods;
377 typeTransformations = this._textNodeTransformations;
378 } else if(from.nodeType === Node.ELEMENT_NODE) {
379 Factory = this.ElementNodeFactory;
380 typeMethods = this._elementNodeMethods;
381 typeTransformations = this._elementNodeTransformations;
383 var toret = new Factory(from, this);
384 _.extend(toret, this._nodeMethods);
385 _.extend(toret, typeMethods);
387 _.extend(toret, this._nodeTransformations);
388 _.extend(toret, typeTransformations);
390 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
391 _.keys(toret.__super__).forEach(function(key) {
392 toret.__super__[key] = _.bind(toret.__super__[key], toret);
398 loadXML: function(xml, options) {
399 options = options || {};
400 this._defineDocumentProperties($(parseXML(xml)));
401 this.normalizeXML(this.dom);
402 if(!options.silent) {
403 this.trigger('contentSet');
407 normalizeXML: function(nativeNode) {
408 void(nativeNode); // noop
412 return this.root.toXML();
415 containsNode: function(node) {
416 return this.root && this.root.containsNode(node);
419 getSiblingParents: function(params) {
420 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
421 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
422 noSiblingParents = null;
424 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
425 return noSiblingParents;
428 var stop = Math.min(parents1.length, parents2.length),
430 for(i = 0; i < stop; i++) {
431 if(parents1[i].sameNode(parents2[i])) {
439 return {node1: parents1[i], node2: parents2[i]};
442 trigger: function() {
443 Backbone.Events.trigger.apply(this, arguments);
446 getNodeInsertion: function(node) {
448 if(node instanceof DocumentNode) {
449 insertion.ofNode = node;
450 insertion.insertsNew = !this.containsNode(node);
452 insertion.ofNode = this.createDocumentNode(node);
453 insertion.insertsNew = true;
458 registerMethod: function(methodName, method, dstName) {
462 documentNode: doc._nodeMethods,
463 textNode: doc._textNodeMethods,
464 elementNode: doc._elementNodeMethods
466 registerMethod(methodName, method, destination);
469 registerTransformation: function(desc, name, dstName) {
473 documentNode: doc._nodeTransformations,
474 textNode: doc._textNodeTransformations,
475 elementNode: doc._elementNodeTransformations
477 registerTransformation(desc, name, destination);
480 registerExtension: function(extension) {
483 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
484 var dstExtension = extension[dstName];
486 if(dstExtension.methods) {
487 _.pairs(dstExtension.methods).forEach(function(pair) {
488 var methodName = pair[0],
491 doc.registerMethod(methodName, method, dstName);
496 if(dstExtension.transformations) {
497 _.pairs(dstExtension.transformations).forEach(function(pair) {
500 doc.registerTransformation(desc, name, dstName);
507 ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
508 var hasChanged = false,
509 changeMonitor = function() {
513 this.on('change', changeMonitor);
514 action.call(context);
515 this.off('change', changeMonitor);
518 if(documentChangedHandler) {
519 documentChangedHandler.call(context);
522 if(documentUnchangedHandler) {
523 documentUnchangedHandler.call(context);
528 transform: function(Transformation, args) {
529 var toret, transformation;
531 if(!this._currentTransaction) {
532 return this.transaction(function() {
533 return this.transform(Transformation, args);
537 if(typeof Transformation === 'function') {
538 transformation = new Transformation(this, this, args);
540 transformation = Transformation;
543 this._transformationLevel++;
548 toret = transformation.run({beUndoable:this._transformationLevel === 1});
551 if(this._transformationLevel === 1 && !this._undoInProgress) {
552 this._currentTransaction.pushTransformation(transformation);
558 this._transformationLevel--;
561 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
565 var transaction = this.undoStack.pop(),
567 transformations, stopAt;
570 this._undoInProgress = true;
572 // We will modify this array in a minute so make sure we work on a copy.
573 transformations = transaction.transformations.slice(0);
575 if(transformations.length > 1) {
576 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
578 transformations.some(function(t, idx) {
579 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
584 if(stopAt !== undefined) {
585 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
586 transformations = transformations.slice(0, stopAt+1);
590 transformations.reverse();
591 transformations.forEach(function(t) {
595 this._undoInProgress = false;
596 this.redoStack.push(transaction);
597 this.trigger('operationEnd');
601 var transaction = this.redoStack.pop();
603 this._transformationLevel++;
604 transaction.transformations.forEach(function(t) {
605 t.run({beUndoable: true});
607 this._transformationLevel--;
608 this.undoStack.push(transaction);
609 this.trigger('operationEnd');
614 startTransaction: function(metadata) {
615 if(this._currentTransaction) {
616 throw new Error('Nested transactions not supported!');
618 this._rollbackBackup = this.root.clone();
619 this._currentTransaction = new Transaction([], metadata);
622 endTransaction: function() {
623 if(!this._currentTransaction) {
624 throw new Error('End of transaction requested, but there is no transaction in progress!');
626 if(this._currentTransaction.hasTransformations()) {
627 this.undoStack.push(this._currentTransaction);
628 this.trigger('operationEnd');
630 this._currentTransaction = null;
633 rollbackTransaction: function() {
634 if(!this._currentTransaction) {
635 throw new Error('Transaction rollback requested, but there is no transaction in progress!');
637 this.replaceRoot(this._rollbackBackup);
638 this._rollbackBackup = null;
639 this._currentTransaction = null;
640 this._transformationLevel = 0;
643 transaction: function(callback, params) {
645 params = params || {};
646 this.startTransaction(params.metadata);
648 toret = callback.call(params.context || this);
653 this.rollbackTransaction();
656 this.endTransaction();
658 params.success(toret);
663 getNodeByPath: function(path) {
664 var toret = this.root;
665 path.forEach(function(idx) {
666 toret = toret.contents()[idx];
671 _defineDocumentProperties: function($document) {
673 Object.defineProperty(doc, 'root', {get: function() {
677 return doc.createDocumentNode($document[0]);
678 }, configurable: true});
679 Object.defineProperty(doc, 'dom', {get: function() {
684 }, configurable: true});
687 createFragment: function(Type, params) {
688 if(!Type.prototype instanceof fragments.Fragment) {
689 throw new Error('Can\'t create a fragment: `Type` is not a valid Fragment');
691 return new Type(this, params);
695 var Transaction = function(transformations, metadata) {
696 this.transformations = transformations || [];
697 this.metadata = metadata;
699 $.extend(Transaction.prototype, {
700 pushTransformation: function(transformation) {
701 this.transformations.push(transformation);
703 hasTransformations: function() {
704 return this.transformations.length > 0;
710 documentFromXML: function(xml) {
711 var doc = new Document(xml);
715 elementNodeFromXML: function(xml) {
716 return this.documentFromXML(xml).root;
720 DocumentNode: DocumentNode,
721 ElementNode: ElementNode,