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 isSiblingOf: function(node) {
83 return node && this.parent().sameNode(node.parent());
86 sameNode: function(otherNode) {
87 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
91 var parentNode = this.nativeNode.parentNode;
92 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
93 return this.document.createDocumentNode(parentNode);
99 var parent = this.parent(),
100 parents = parent ? parent.parents() : [];
102 parents.unshift(parent);
108 var myIdx = this.getIndex();
109 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
116 var myIdx = this.getIndex(),
117 parentContents = this.parent().contents();
118 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
121 isSurroundedByTextElements: function() {
122 var prev = this.prev(),
124 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
127 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
128 var node = (metaData && metaData.node) ? metaData.node : this,
129 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
130 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
131 if(type === 'nodeMoved') {
132 event.meta.parent = origParent;
134 this.document.trigger('change', event);
136 if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
137 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
138 this.document.trigger('change', event);
142 getNodeInsertion: function(node) {
143 return this.document.getNodeInsertion(node);
146 getIndex: function() {
150 return this.parent().indexOf(this);
153 getNearestElementNode: function() {
154 return this.nodeType === Node.ELEMENT_NODE ? this : this.parent();
159 var ElementNode = function(nativeNode, document) {
160 DocumentNode.call(this, nativeNode, document);
162 ElementNode.prototype = Object.create(DocumentNode.prototype);
164 $.extend(ElementNode.prototype, {
165 nodeType: Node.ELEMENT_NODE,
167 setData: function(key, value) {
168 if(value !== undefined) {
169 this._$.data(key, value);
171 this._$.removeData(_.keys(this._$.data()));
176 getData: function(key) {
178 return this._$.data(key);
180 return this._$.data();
183 getTagName: function() {
184 return this.nativeNode.tagName.toLowerCase();
187 contents: function(selector) {
189 document = this.document;
191 this._$.children(selector).each(function() {
192 toret.push(document.createDocumentNode(this));
195 this._$.contents().each(function() {
196 toret.push(document.createDocumentNode(this));
202 indexOf: function(node) {
203 return this._$.contents().index(node._$);
206 getAttr: function(name) {
207 return this._$.attr(name);
210 getAttrs: function() {
212 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
213 toret.push(this.nativeNode.attributes[i]);
218 containsNode: function(node) {
219 return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
223 var wrapper = $('<div>');
224 wrapper.append(this._getXMLDOMToDump());
225 return wrapper.html();
228 _getXMLDOMToDump: function() {
234 var TextNode = function(nativeNode, document) {
235 DocumentNode.call(this, nativeNode, document);
237 TextNode.prototype = Object.create(DocumentNode.prototype);
239 $.extend(TextNode.prototype, {
240 nodeType: Node.TEXT_NODE,
242 getText: function() {
243 return this.nativeNode.data;
246 triggerTextChangeEvent: function() {
247 var event = new events.ChangeEvent('nodeTextChange', {node: this});
248 this.document.trigger('change', event);
253 var parseXML = function(xml) {
254 var toret = $($.trim(xml));
256 throw new Error('Unable to parse XML: ' + xml);
262 var registerTransformation = function(desc, name, target) {
263 var Transformation = transformations.createContextTransformation(desc, name);
264 target[name] = function() {
266 args = Array.prototype.slice.call(arguments, 0);
267 return instance.transform(Transformation, args);
271 var registerMethod = function(methodName, method, target) {
272 if(target[methodName]) {
273 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
274 .replace('{target}', target)
275 .replace('{methodName}', methodName)
278 target[methodName] = method;
282 var Document = function(xml, extensions) {
285 this._currentTransaction = null;
286 this._transformationLevel = 0;
288 this._nodeMethods = {};
289 this._textNodeMethods = {};
290 this._elementNodeMethods = {};
291 this._nodeTransformations = {};
292 this._textNodeTransformations = {};
293 this._elementNodeTransformations = {};
295 this.registerExtension(coreTransformations);
297 (extensions || []).forEach(function(extension) {
298 this.registerExtension(extension);
303 $.extend(Document.prototype, Backbone.Events, fragments, {
304 ElementNodeFactory: ElementNode,
305 TextNodeFactory: TextNode,
307 createDocumentNode: function(from) {
308 if(!(from instanceof Node)) {
309 if(typeof from === 'string') {
310 from = parseXML(from);
311 this.normalizeXML(from);
313 if(from.text !== undefined) {
314 /* globals document */
315 from = document.createTextNode(from.text);
318 throw new Error('tagName missing');
320 var node = $('<' + from.tagName + '>');
322 _.keys(from.attrs || {}).forEach(function(key) {
323 node.attr(key, from.attrs[key]);
330 var Factory, typeMethods, typeTransformations;
331 if(from.nodeType === Node.TEXT_NODE) {
332 Factory = this.TextNodeFactory;
333 typeMethods = this._textNodeMethods;
334 typeTransformations = this._textNodeTransformations;
335 } else if(from.nodeType === Node.ELEMENT_NODE) {
336 Factory = this.ElementNodeFactory;
337 typeMethods = this._elementNodeMethods;
338 typeTransformations = this._elementNodeTransformations;
340 var toret = new Factory(from, this);
341 _.extend(toret, this._nodeMethods);
342 _.extend(toret, typeMethods);
344 _.extend(toret, this._nodeTransformations);
345 _.extend(toret, typeTransformations);
347 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
348 _.keys(toret.__super__).forEach(function(key) {
349 toret.__super__[key] = _.bind(toret.__super__[key], toret);
355 loadXML: function(xml, options) {
356 options = options || {};
357 this._defineDocumentProperties($(parseXML(xml)));
358 this.normalizeXML(this.dom);
359 if(!options.silent) {
360 this.trigger('contentSet');
364 normalizeXML: function(nativeNode) {
365 void(nativeNode); // noop
369 return this.root.toXML();
372 containsNode: function(node) {
373 return this.root && this.root.containsNode(node);
376 getSiblingParents: function(params) {
377 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
378 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
379 noSiblingParents = null;
381 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
382 return noSiblingParents;
385 var stop = Math.min(parents1.length, parents2.length),
387 for(i = 0; i < stop; i++) {
388 if(parents1[i].sameNode(parents2[i])) {
396 return {node1: parents1[i], node2: parents2[i]};
399 trigger: function() {
400 Backbone.Events.trigger.apply(this, arguments);
403 getNodeInsertion: function(node) {
405 if(node instanceof DocumentNode) {
406 insertion.ofNode = node;
407 insertion.insertsNew = !this.containsNode(node);
409 insertion.ofNode = this.createDocumentNode(node);
410 insertion.insertsNew = true;
415 registerMethod: function(methodName, method, dstName) {
419 documentNode: doc._nodeMethods,
420 textNode: doc._textNodeMethods,
421 elementNode: doc._elementNodeMethods
423 registerMethod(methodName, method, destination);
426 registerTransformation: function(desc, name, dstName) {
430 documentNode: doc._nodeTransformations,
431 textNode: doc._textNodeTransformations,
432 elementNode: doc._elementNodeTransformations
434 registerTransformation(desc, name, destination);
437 registerExtension: function(extension) {
440 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
441 var dstExtension = extension[dstName];
443 if(dstExtension.methods) {
444 _.pairs(dstExtension.methods).forEach(function(pair) {
445 var methodName = pair[0],
448 doc.registerMethod(methodName, method, dstName);
453 if(dstExtension.transformations) {
454 _.pairs(dstExtension.transformations).forEach(function(pair) {
457 doc.registerTransformation(desc, name, dstName);
464 ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
465 var hasChanged = false,
466 changeMonitor = function() {
470 this.on('change', changeMonitor);
471 action.call(context);
472 this.off('change', changeMonitor);
475 if(documentChangedHandler) {
476 documentChangedHandler.call(context);
479 if(documentUnchangedHandler) {
480 documentUnchangedHandler.call(context);
485 transform: function(Transformation, args) {
486 var toret, transformation;
488 if(!this._currentTransaction) {
489 return this.transaction(function() {
490 return this.transform(Transformation, args);
494 if(typeof Transformation === 'function') {
495 transformation = new Transformation(this, this, args);
497 transformation = Transformation;
500 this._transformationLevel++;
505 toret = transformation.run({beUndoable:this._transformationLevel === 1});
508 if(this._transformationLevel === 1 && !this._undoInProgress) {
509 this._currentTransaction.pushTransformation(transformation);
515 this._transformationLevel--;
518 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
522 var transaction = this.undoStack.pop(),
524 transformations, stopAt;
527 this._undoInProgress = true;
529 // We will modify this array in a minute so make sure we work on a copy.
530 transformations = transaction.transformations.slice(0);
532 if(transformations.length > 1) {
533 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
535 transformations.some(function(t, idx) {
536 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
541 if(stopAt !== undefined) {
542 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
543 transformations = transformations.slice(0, stopAt+1);
547 transformations.reverse();
548 transformations.forEach(function(t) {
552 this._undoInProgress = false;
553 this.redoStack.push(transaction);
554 this.trigger('operationEnd');
558 var transaction = this.redoStack.pop();
560 this._transformationLevel++;
561 transaction.transformations.forEach(function(t) {
562 t.run({beUndoable: true});
564 this._transformationLevel--;
565 this.undoStack.push(transaction);
566 this.trigger('operationEnd');
571 startTransaction: function(metadata) {
572 if(this._currentTransaction) {
573 throw new Error('Nested transactions not supported!');
575 this._rollbackBackup = this.root.clone();
576 this._currentTransaction = new Transaction([], metadata);
579 endTransaction: function() {
580 if(!this._currentTransaction) {
581 throw new Error('End of transaction requested, but there is no transaction in progress!');
583 if(this._currentTransaction.hasTransformations()) {
584 this.undoStack.push(this._currentTransaction);
585 this.trigger('operationEnd');
587 this._currentTransaction = null;
590 rollbackTransaction: function() {
591 if(!this._currentTransaction) {
592 throw new Error('Transaction rollback requested, but there is no transaction in progress!');
594 this.replaceRoot(this._rollbackBackup);
595 this._rollbackBackup = null;
596 this._currentTransaction = null;
597 this._transformationLevel = 0;
600 transaction: function(callback, params) {
602 params = params || {};
603 this.startTransaction(params.metadata);
605 toret = callback.call(params.context || this);
610 this.rollbackTransaction();
613 this.endTransaction();
615 params.success(toret);
620 getNodeByPath: function(path) {
621 var toret = this.root;
622 path.forEach(function(idx) {
623 toret = toret.contents()[idx];
628 _defineDocumentProperties: function($document) {
630 Object.defineProperty(doc, 'root', {get: function() {
634 return doc.createDocumentNode($document[0]);
635 }, configurable: true});
636 Object.defineProperty(doc, 'dom', {get: function() {
641 }, configurable: true});
644 createFragment: function(Type, params) {
645 if(!Type.prototype instanceof fragments.Fragment) {
646 throw new Error('Can\'t create a fragment: `Type` is not a valid Fragment');
648 return new Type(this, params);
652 var Transaction = function(transformations, metadata) {
653 this.transformations = transformations || [];
654 this.metadata = metadata;
656 $.extend(Transaction.prototype, {
657 pushTransformation: function(transformation) {
658 this.transformations.push(transformation);
660 hasTransformations: function() {
661 return this.transformations.length > 0;
667 documentFromXML: function(xml) {
668 var doc = new Document(xml);
672 elementNodeFromXML: function(xml) {
673 return this.documentFromXML(xml).root;
677 DocumentNode: DocumentNode,
678 ElementNode: ElementNode,