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);
37 return this.document.createDocumentNode(clone[0]);
40 getPath: function(ancestor) {
41 if(!(this.document.containsNode(this))) {
45 var nodePath = [this].concat(this.parents()),
47 ancestor = ancestor || this.document.root;
49 nodePath.some(function(node, i) {
50 if(node.sameNode(ancestor)) {
56 if(idx !== 'undefined') {
57 nodePath = nodePath.slice(0, idx);
59 toret = nodePath.map(function(node) {return node.getIndex(); });
65 return this.document.root.sameNode(this);
68 sameNode: function(otherNode) {
69 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
73 var parentNode = this.nativeNode.parentNode;
74 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
75 return this.document.createDocumentNode(parentNode);
81 var parent = this.parent(),
82 parents = parent ? parent.parents() : [];
84 parents.unshift(parent);
90 var myIdx = this.getIndex();
91 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
98 var myIdx = this.getIndex(),
99 parentContents = this.parent().contents();
100 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
103 isSurroundedByTextElements: function() {
104 var prev = this.prev(),
106 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
109 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
110 var node = (metaData && metaData.node) ? metaData.node : this,
111 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
112 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
113 this.document.trigger('change', event);
115 if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
116 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
117 this.document.trigger('change', event);
121 getNodeInsertion: function(node) {
122 return this.document.getNodeInsertion(node);
125 getIndex: function() {
129 return this.parent().indexOf(this);
134 var ElementNode = function(nativeNode, document) {
135 DocumentNode.call(this, nativeNode, document);
137 ElementNode.prototype = Object.create(DocumentNode.prototype);
139 $.extend(ElementNode.prototype, {
140 nodeType: Node.ELEMENT_NODE,
142 setData: function(key, value) {
143 if(value !== undefined) {
144 this._$.data(key, value);
146 this._$.removeData(_.keys(this._$.data()));
151 getData: function(key) {
153 return this._$.data(key);
155 return this._$.data();
158 getTagName: function() {
159 return this.nativeNode.tagName.toLowerCase();
162 contents: function(selector) {
164 document = this.document;
166 this._$.children(selector).each(function() {
167 toret.push(document.createDocumentNode(this));
170 this._$.contents().each(function() {
171 toret.push(document.createDocumentNode(this));
177 indexOf: function(node) {
178 return this._$.contents().index(node._$);
181 getAttr: function(name) {
182 return this._$.attr(name);
185 getAttrs: function() {
187 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
188 toret.push(this.nativeNode.attributes[i]);
194 var wrapper = $('<div>');
195 wrapper.append(this._getXMLDOMToDump());
196 return wrapper.html();
199 _getXMLDOMToDump: function() {
205 var TextNode = function(nativeNode, document) {
206 DocumentNode.call(this, nativeNode, document);
208 TextNode.prototype = Object.create(DocumentNode.prototype);
210 $.extend(TextNode.prototype, {
211 nodeType: Node.TEXT_NODE,
213 getText: function() {
214 return this.nativeNode.data;
217 triggerTextChangeEvent: function() {
218 var event = new events.ChangeEvent('nodeTextChange', {node: this});
219 this.document.trigger('change', event);
224 var parseXML = function(xml) {
225 return $($.trim(xml))[0];
228 var registerTransformation = function(desc, name, target) {
229 var Transformation = transformations.createContextTransformation(desc, name);
230 target[name] = function() {
232 args = Array.prototype.slice.call(arguments, 0);
233 return instance.transform(Transformation, args);
237 var registerMethod = function(methodName, method, target) {
238 if(target[methodName]) {
239 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
240 .replace('{target}', target)
241 .replace('{methodName}', methodName)
244 target[methodName] = method;
248 var Document = function(xml) {
252 this._transactionStack = [];
253 this._transformationLevel = 0;
255 this._nodeMethods = {};
256 this._textNodeMethods = {};
257 this._elementNodeMethods = {};
258 this._nodeTransformations = {};
259 this._textNodeTransformations = {};
260 this._elementNodeTransformations = {};
262 this.registerExtension(coreTransformations);
265 $.extend(Document.prototype, Backbone.Events, {
266 ElementNodeFactory: ElementNode,
267 TextNodeFactory: TextNode,
269 createDocumentNode: function(from) {
270 if(!(from instanceof Node)) {
271 if(from.text !== undefined) {
272 /* globals document */
273 from = document.createTextNode(from.text);
275 var node = $('<' + from.tagName + '>');
277 _.keys(from.attrs || {}).forEach(function(key) {
278 node.attr(key, from.attrs[key]);
284 var Factory, typeMethods, typeTransformations;
285 if(from.nodeType === Node.TEXT_NODE) {
286 Factory = this.TextNodeFactory;
287 typeMethods = this._textNodeMethods;
288 typeTransformations = this._textNodeTransformations;
289 } else if(from.nodeType === Node.ELEMENT_NODE) {
290 Factory = this.ElementNodeFactory;
291 typeMethods = this._elementNodeMethods;
292 typeTransformations = this._elementNodeTransformations;
294 var toret = new Factory(from, this);
295 _.extend(toret, this._nodeMethods);
296 _.extend(toret, typeMethods);
298 _.extend(toret, this._nodeTransformations);
299 _.extend(toret, typeTransformations);
301 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
302 _.keys(toret.__super__).forEach(function(key) {
303 toret.__super__[key] = _.bind(toret.__super__[key], toret);
309 loadXML: function(xml, options) {
310 options = options || {};
311 this._defineDocumentProperties($(parseXML(xml)));
312 if(!options.silent) {
313 this.trigger('contentSet');
318 return this.root.toXML();
321 containsNode: function(node) {
322 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
325 getSiblingParents: function(params) {
326 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
327 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
328 noSiblingParents = null;
330 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
331 return noSiblingParents;
335 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
336 if(parents1[i].sameNode(parents2[i])) {
341 return {node1: parents1[i], node2: parents2[i]};
344 trigger: function() {
345 Backbone.Events.trigger.apply(this, arguments);
348 getNodeInsertion: function(node) {
350 if(node instanceof DocumentNode) {
351 insertion.ofNode = node;
352 insertion.insertsNew = !this.containsNode(node);
354 insertion.ofNode = this.createDocumentNode(node);
355 insertion.insertsNew = true;
360 registerMethod: function(methodName, method, dstName) {
364 documentNode: doc._nodeMethods,
365 textNode: doc._textNodeMethods,
366 elementNode: doc._elementNodeMethods
368 registerMethod(methodName, method, destination);
371 registerTransformation: function(desc, name, dstName) {
375 documentNode: doc._nodeTransformations,
376 textNode: doc._textNodeTransformations,
377 elementNode: doc._elementNodeTransformations
379 registerTransformation(desc, name, destination);
382 registerExtension: function(extension) {
385 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
386 var dstExtension = extension[dstName];
388 if(dstExtension.methods) {
389 _.pairs(dstExtension.methods).forEach(function(pair) {
390 var methodName = pair[0],
393 doc.registerMethod(methodName, method, dstName);
398 if(dstExtension.transformations) {
399 _.pairs(dstExtension.transformations).forEach(function(pair) {
402 doc.registerTransformation(desc, name, dstName);
409 transform: function(Transformation, args) {
410 var toret, transformation;
412 if(typeof Transformation === 'function') {
413 transformation = new Transformation(this, this, args);
415 transformation = Transformation;
418 this._transformationLevel++;
419 toret = transformation.run({beUndoable:this._transformationLevel === 1});
420 if(this._transformationLevel === 1 && !this._undoInProgress) {
421 if(this._transactionInProgress) {
422 this._transactionStack.push(transformation);
424 this.undoStack.push(transformation);
427 if(!this._undoInProgress && this._transformationLevel === 1) {
430 this._transformationLevel--;
433 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
437 var transformationObject = this.undoStack.pop(),
439 transformations, stopAt;
441 if(transformationObject) {
442 this._undoInProgress = true;
444 if(_.isArray(transformationObject)) {
445 // We will modify this array in a minute so make sure we work on a copy.
446 transformations = transformationObject.slice(0);
448 // Lets normalize single transformation to a transaction containing one transformation.
449 transformations = [transformationObject];
452 if(transformations.length > 1) {
453 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
455 transformations.some(function(t, idx) {
456 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
461 if(stopAt !== undefined) {
462 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
463 transformations = transformations.slice(0, stopAt+1);
467 transformations.reverse();
468 transformations.forEach(function(t) {
472 this._undoInProgress = false;
473 this.redoStack.push(transformationObject);
477 var transformationObject = this.redoStack.pop(),
479 if(transformationObject) {
480 this._transformationLevel++;
481 transformations = _.isArray(transformationObject) ? transformationObject : [transformationObject];
482 transformations.forEach(function(t) {
483 t.run({beUndoable: true});
485 this._transformationLevel--;
486 this.undoStack.push(transformationObject);
490 startTransaction: function() {
491 if(this._transactionInProgress) {
492 throw new Error('Nested transactions not supported!');
494 this._transactionInProgress = true;
497 endTransaction: function() {
498 if(!this._transactionInProgress) {
499 throw new Error('End of transaction requested, but there is no transaction in progress!');
501 this._transactionInProgress = false;
502 this.undoStack.push(this._transactionStack);
503 this._transactionStack = [];
506 getNodeByPath: function(path) {
507 var toret = this.root;
508 path.forEach(function(idx) {
509 toret = toret.contents()[idx];
514 _defineDocumentProperties: function($document) {
516 Object.defineProperty(doc, 'root', {get: function() {
517 return doc.createDocumentNode($document[0]);
518 }, configurable: true});
519 Object.defineProperty(doc, 'dom', {get: function() {
521 }, configurable: true});
527 documentFromXML: function(xml) {
528 var doc = new Document(xml);
532 elementNodeFromXML: function(xml) {
533 return this.documentFromXML(xml).root;
537 DocumentNode: DocumentNode,
538 ElementNode: ElementNode,