6 'smartxml/transformations',
8 ], function($, _, Backbone, events, transformations, coreTransformations) {
14 var DocumentNode = function(nativeNode, document) {
16 throw new Error('undefined document for a node');
18 this.document = document;
19 this._setNativeNode(nativeNode);
23 $.extend(DocumentNode.prototype, {
25 transform: function(Transformation, args) {
26 var transformation = new Transformation(this.document, this, args);
27 return this.document.transform(transformation);
30 _setNativeNode: function(nativeNode) {
31 this.nativeNode = nativeNode;
32 this._$ = $(nativeNode);
36 var clone = this._$.clone(true, true),
38 clone.find('*').addBack().each(function() {
40 clonedData = $(this).data();
42 _.pairs(clonedData).forEach(function(pair) {
45 if(_.isFunction(value.clone)) {
46 clonedData[key] = value.clone(node.document.createDocumentNode(el));
50 return this.document.createDocumentNode(clone[0]);
53 getPath: function(ancestor) {
54 if(!(this.document.containsNode(this))) {
58 var nodePath = [this].concat(this.parents()),
60 ancestor = ancestor || this.document.root;
62 nodePath.some(function(node, i) {
63 if(node.sameNode(ancestor)) {
69 if(idx !== undefined) {
70 nodePath = nodePath.slice(0, idx);
72 toret = nodePath.map(function(node) {return node.getIndex(); });
78 return this.document.root.sameNode(this);
81 sameNode: function(otherNode) {
82 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
86 var parentNode = this.nativeNode.parentNode;
87 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
88 return this.document.createDocumentNode(parentNode);
94 var parent = this.parent(),
95 parents = parent ? parent.parents() : [];
97 parents.unshift(parent);
103 var myIdx = this.getIndex();
104 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
111 var myIdx = this.getIndex(),
112 parentContents = this.parent().contents();
113 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
116 isSurroundedByTextElements: function() {
117 var prev = this.prev(),
119 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
122 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
123 var node = (metaData && metaData.node) ? metaData.node : this,
124 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
125 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
126 if(type === 'nodeMoved') {
127 event.meta.parent = origParent;
129 this.document.trigger('change', event);
131 if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
132 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
133 this.document.trigger('change', event);
137 getNodeInsertion: function(node) {
138 return this.document.getNodeInsertion(node);
141 getIndex: function() {
145 return this.parent().indexOf(this);
150 var ElementNode = function(nativeNode, document) {
151 DocumentNode.call(this, nativeNode, document);
153 ElementNode.prototype = Object.create(DocumentNode.prototype);
155 $.extend(ElementNode.prototype, {
156 nodeType: Node.ELEMENT_NODE,
158 setData: function(key, value) {
159 if(value !== undefined) {
160 this._$.data(key, value);
162 this._$.removeData(_.keys(this._$.data()));
167 getData: function(key) {
169 return this._$.data(key);
171 return this._$.data();
174 getTagName: function() {
175 return this.nativeNode.tagName.toLowerCase();
178 contents: function(selector) {
180 document = this.document;
182 this._$.children(selector).each(function() {
183 toret.push(document.createDocumentNode(this));
186 this._$.contents().each(function() {
187 toret.push(document.createDocumentNode(this));
193 indexOf: function(node) {
194 return this._$.contents().index(node._$);
197 getAttr: function(name) {
198 return this._$.attr(name);
201 getAttrs: function() {
203 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
204 toret.push(this.nativeNode.attributes[i]);
209 containsNode: function(node) {
210 return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
214 var wrapper = $('<div>');
215 wrapper.append(this._getXMLDOMToDump());
216 return wrapper.html();
219 _getXMLDOMToDump: function() {
225 var TextNode = function(nativeNode, document) {
226 DocumentNode.call(this, nativeNode, document);
228 TextNode.prototype = Object.create(DocumentNode.prototype);
230 $.extend(TextNode.prototype, {
231 nodeType: Node.TEXT_NODE,
233 getText: function() {
234 return this.nativeNode.data;
237 triggerTextChangeEvent: function() {
238 var event = new events.ChangeEvent('nodeTextChange', {node: this});
239 this.document.trigger('change', event);
244 var parseXML = function(xml) {
245 var toret = $($.trim(xml));
247 throw new Error('Unable to parse XML: ' + xml);
253 var registerTransformation = function(desc, name, target) {
254 var Transformation = transformations.createContextTransformation(desc, name);
255 target[name] = function() {
257 args = Array.prototype.slice.call(arguments, 0);
258 return instance.transform(Transformation, args);
262 var registerMethod = function(methodName, method, target) {
263 if(target[methodName]) {
264 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
265 .replace('{target}', target)
266 .replace('{methodName}', methodName)
269 target[methodName] = method;
273 var Document = function(xml, extensions) {
276 this._transactionStack = [];
277 this._transformationLevel = 0;
279 this._nodeMethods = {};
280 this._textNodeMethods = {};
281 this._elementNodeMethods = {};
282 this._nodeTransformations = {};
283 this._textNodeTransformations = {};
284 this._elementNodeTransformations = {};
286 this.registerExtension(coreTransformations);
288 (extensions || []).forEach(function(extension) {
289 this.registerExtension(extension);
294 $.extend(Document.prototype, Backbone.Events, {
295 ElementNodeFactory: ElementNode,
296 TextNodeFactory: TextNode,
298 createDocumentNode: function(from) {
299 if(!(from instanceof Node)) {
300 if(typeof from === 'string') {
301 from = parseXML(from);
302 this.normalizeXML(from);
304 if(from.text !== undefined) {
305 /* globals document */
306 from = document.createTextNode(from.text);
309 throw new Error('tagName missing');
311 var node = $('<' + from.tagName + '>');
313 _.keys(from.attrs || {}).forEach(function(key) {
314 node.attr(key, from.attrs[key]);
321 var Factory, typeMethods, typeTransformations;
322 if(from.nodeType === Node.TEXT_NODE) {
323 Factory = this.TextNodeFactory;
324 typeMethods = this._textNodeMethods;
325 typeTransformations = this._textNodeTransformations;
326 } else if(from.nodeType === Node.ELEMENT_NODE) {
327 Factory = this.ElementNodeFactory;
328 typeMethods = this._elementNodeMethods;
329 typeTransformations = this._elementNodeTransformations;
331 var toret = new Factory(from, this);
332 _.extend(toret, this._nodeMethods);
333 _.extend(toret, typeMethods);
335 _.extend(toret, this._nodeTransformations);
336 _.extend(toret, typeTransformations);
338 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
339 _.keys(toret.__super__).forEach(function(key) {
340 toret.__super__[key] = _.bind(toret.__super__[key], toret);
346 loadXML: function(xml, options) {
347 options = options || {};
348 this._defineDocumentProperties($(parseXML(xml)));
349 this.normalizeXML(this.dom);
350 if(!options.silent) {
351 this.trigger('contentSet');
355 normalizeXML: function(nativeNode) {
356 void(nativeNode); // noop
360 return this.root.toXML();
363 containsNode: function(node) {
364 return this.root && this.root.containsNode(node);
367 getSiblingParents: function(params) {
368 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
369 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
370 noSiblingParents = null;
372 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
373 return noSiblingParents;
377 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
378 if(parents1[i].sameNode(parents2[i])) {
383 return {node1: parents1[i], node2: parents2[i]};
386 trigger: function() {
387 Backbone.Events.trigger.apply(this, arguments);
390 getNodeInsertion: function(node) {
392 if(node instanceof DocumentNode) {
393 insertion.ofNode = node;
394 insertion.insertsNew = !this.containsNode(node);
396 insertion.ofNode = this.createDocumentNode(node);
397 insertion.insertsNew = true;
402 registerMethod: function(methodName, method, dstName) {
406 documentNode: doc._nodeMethods,
407 textNode: doc._textNodeMethods,
408 elementNode: doc._elementNodeMethods
410 registerMethod(methodName, method, destination);
413 registerTransformation: function(desc, name, dstName) {
417 documentNode: doc._nodeTransformations,
418 textNode: doc._textNodeTransformations,
419 elementNode: doc._elementNodeTransformations
421 registerTransformation(desc, name, destination);
424 registerExtension: function(extension) {
427 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
428 var dstExtension = extension[dstName];
430 if(dstExtension.methods) {
431 _.pairs(dstExtension.methods).forEach(function(pair) {
432 var methodName = pair[0],
435 doc.registerMethod(methodName, method, dstName);
440 if(dstExtension.transformations) {
441 _.pairs(dstExtension.transformations).forEach(function(pair) {
444 doc.registerTransformation(desc, name, dstName);
451 ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
452 var hasChanged = false,
453 changeMonitor = function() {
457 this.on('change', changeMonitor);
458 action.call(context);
459 this.off('change', changeMonitor);
462 if(documentChangedHandler) {
463 documentChangedHandler.call(context);
466 if(documentUnchangedHandler) {
467 documentUnchangedHandler.call(context);
472 transform: function(Transformation, args) {
473 var toret, transformation;
475 if(typeof Transformation === 'function') {
476 transformation = new Transformation(this, this, args);
478 transformation = Transformation;
481 this._transformationLevel++;
486 toret = transformation.run({beUndoable:this._transformationLevel === 1});
489 if(this._transformationLevel === 1 && !this._undoInProgress) {
490 if(this._transactionInProgress) {
491 this._transactionStack.push(transformation);
493 this.undoStack.push(transformation);
496 if(!this._undoInProgress && this._transformationLevel === 1) {
502 this._transformationLevel--;
505 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
509 var transformationObject = this.undoStack.pop(),
511 transformations, stopAt;
513 if(transformationObject) {
514 this._undoInProgress = true;
516 if(_.isArray(transformationObject)) {
517 // We will modify this array in a minute so make sure we work on a copy.
518 transformations = transformationObject.slice(0);
520 // Lets normalize single transformation to a transaction containing one transformation.
521 transformations = [transformationObject];
524 if(transformations.length > 1) {
525 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
527 transformations.some(function(t, idx) {
528 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
533 if(stopAt !== undefined) {
534 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
535 transformations = transformations.slice(0, stopAt+1);
539 transformations.reverse();
540 transformations.forEach(function(t) {
544 this._undoInProgress = false;
545 this.redoStack.push(transformationObject);
549 var transformationObject = this.redoStack.pop(),
551 if(transformationObject) {
552 this._transformationLevel++;
553 transformations = _.isArray(transformationObject) ? transformationObject : [transformationObject];
554 transformations.forEach(function(t) {
555 t.run({beUndoable: true});
557 this._transformationLevel--;
558 this.undoStack.push(transformationObject);
562 startTransaction: function() {
563 if(this._transactionInProgress) {
564 throw new Error('Nested transactions not supported!');
566 this._transactionInProgress = true;
569 endTransaction: function() {
570 if(!this._transactionInProgress) {
571 throw new Error('End of transaction requested, but there is no transaction in progress!');
573 this._transactionInProgress = false;
574 if(this._transactionStack.length) {
575 this.undoStack.push(this._transactionStack);
576 this._transactionStack = [];
580 transaction: function(callback, context) {
581 this.startTransaction();
582 callback.call(context);
583 this.endTransaction();
586 getNodeByPath: function(path) {
587 var toret = this.root;
588 path.forEach(function(idx) {
589 toret = toret.contents()[idx];
594 _defineDocumentProperties: function($document) {
596 Object.defineProperty(doc, 'root', {get: function() {
597 return doc.createDocumentNode($document[0]);
598 }, configurable: true});
599 Object.defineProperty(doc, 'dom', {get: function() {
601 }, configurable: true});
607 documentFromXML: function(xml) {
608 var doc = new Document(xml);
612 elementNodeFromXML: function(xml) {
613 return this.documentFromXML(xml).root;
617 DocumentNode: DocumentNode,
618 ElementNode: ElementNode,