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 clone.find('*').addBack().each(function() {
38 var clonedData = $(this).data();
39 _.pairs(clonedData).forEach(function(pair) {
42 if(_.isFunction(value.clone)) {
43 clonedData[key] = value.clone();
47 return this.document.createDocumentNode(clone[0]);
50 getPath: function(ancestor) {
51 if(!(this.document.containsNode(this))) {
55 var nodePath = [this].concat(this.parents()),
57 ancestor = ancestor || this.document.root;
59 nodePath.some(function(node, i) {
60 if(node.sameNode(ancestor)) {
66 if(idx !== 'undefined') {
67 nodePath = nodePath.slice(0, idx);
69 toret = nodePath.map(function(node) {return node.getIndex(); });
75 return this.document.root.sameNode(this);
78 sameNode: function(otherNode) {
79 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
83 var parentNode = this.nativeNode.parentNode;
84 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
85 return this.document.createDocumentNode(parentNode);
91 var parent = this.parent(),
92 parents = parent ? parent.parents() : [];
94 parents.unshift(parent);
100 var myIdx = this.getIndex();
101 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
108 var myIdx = this.getIndex(),
109 parentContents = this.parent().contents();
110 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
113 isSurroundedByTextElements: function() {
114 var prev = this.prev(),
116 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
119 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
120 var node = (metaData && metaData.node) ? metaData.node : this,
121 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
122 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
123 this.document.trigger('change', event);
125 if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
126 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
127 this.document.trigger('change', event);
131 getNodeInsertion: function(node) {
132 return this.document.getNodeInsertion(node);
135 getIndex: function() {
139 return this.parent().indexOf(this);
144 var ElementNode = function(nativeNode, document) {
145 DocumentNode.call(this, nativeNode, document);
147 ElementNode.prototype = Object.create(DocumentNode.prototype);
149 $.extend(ElementNode.prototype, {
150 nodeType: Node.ELEMENT_NODE,
152 setData: function(key, value) {
153 if(value !== undefined) {
154 this._$.data(key, value);
156 this._$.removeData(_.keys(this._$.data()));
161 getData: function(key) {
163 return this._$.data(key);
165 return this._$.data();
168 getTagName: function() {
169 return this.nativeNode.tagName.toLowerCase();
172 contents: function(selector) {
174 document = this.document;
176 this._$.children(selector).each(function() {
177 toret.push(document.createDocumentNode(this));
180 this._$.contents().each(function() {
181 toret.push(document.createDocumentNode(this));
187 indexOf: function(node) {
188 return this._$.contents().index(node._$);
191 getAttr: function(name) {
192 return this._$.attr(name);
195 getAttrs: function() {
197 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
198 toret.push(this.nativeNode.attributes[i]);
204 var wrapper = $('<div>');
205 wrapper.append(this._getXMLDOMToDump());
206 return wrapper.html();
209 _getXMLDOMToDump: function() {
215 var TextNode = function(nativeNode, document) {
216 DocumentNode.call(this, nativeNode, document);
218 TextNode.prototype = Object.create(DocumentNode.prototype);
220 $.extend(TextNode.prototype, {
221 nodeType: Node.TEXT_NODE,
223 getText: function() {
224 return this.nativeNode.data;
227 triggerTextChangeEvent: function() {
228 var event = new events.ChangeEvent('nodeTextChange', {node: this});
229 this.document.trigger('change', event);
234 var parseXML = function(xml) {
235 var toret = $($.trim(xml));
237 throw new Error('Unable to parse XML: ' + xml);
243 var registerTransformation = function(desc, name, target) {
244 var Transformation = transformations.createContextTransformation(desc, name);
245 target[name] = function() {
247 args = Array.prototype.slice.call(arguments, 0);
248 return instance.transform(Transformation, args);
252 var registerMethod = function(methodName, method, target) {
253 if(target[methodName]) {
254 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
255 .replace('{target}', target)
256 .replace('{methodName}', methodName)
259 target[methodName] = method;
263 var Document = function(xml, extensions) {
266 this._transactionStack = [];
267 this._transformationLevel = 0;
269 this._nodeMethods = {};
270 this._textNodeMethods = {};
271 this._elementNodeMethods = {};
272 this._nodeTransformations = {};
273 this._textNodeTransformations = {};
274 this._elementNodeTransformations = {};
276 this.registerExtension(coreTransformations);
278 (extensions || []).forEach(function(extension) {
279 this.registerExtension(extension);
284 $.extend(Document.prototype, Backbone.Events, {
285 ElementNodeFactory: ElementNode,
286 TextNodeFactory: TextNode,
288 createDocumentNode: function(from) {
289 if(!(from instanceof Node)) {
290 if(typeof from === 'string') {
291 from = parseXML(from);
292 this.normalizeXML(from);
294 if(from.text !== undefined) {
295 /* globals document */
296 from = document.createTextNode(from.text);
299 throw new Error('tagName missing');
301 var node = $('<' + from.tagName + '>');
303 _.keys(from.attrs || {}).forEach(function(key) {
304 node.attr(key, from.attrs[key]);
311 var Factory, typeMethods, typeTransformations;
312 if(from.nodeType === Node.TEXT_NODE) {
313 Factory = this.TextNodeFactory;
314 typeMethods = this._textNodeMethods;
315 typeTransformations = this._textNodeTransformations;
316 } else if(from.nodeType === Node.ELEMENT_NODE) {
317 Factory = this.ElementNodeFactory;
318 typeMethods = this._elementNodeMethods;
319 typeTransformations = this._elementNodeTransformations;
321 var toret = new Factory(from, this);
322 _.extend(toret, this._nodeMethods);
323 _.extend(toret, typeMethods);
325 _.extend(toret, this._nodeTransformations);
326 _.extend(toret, typeTransformations);
328 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
329 _.keys(toret.__super__).forEach(function(key) {
330 toret.__super__[key] = _.bind(toret.__super__[key], toret);
336 loadXML: function(xml, options) {
337 options = options || {};
338 this._defineDocumentProperties($(parseXML(xml)));
339 this.normalizeXML(this.dom);
340 if(!options.silent) {
341 this.trigger('contentSet');
345 normalizeXML: function(nativeNode) {
346 void(nativeNode); // noop
350 return this.root.toXML();
353 containsNode: function(node) {
354 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
357 getSiblingParents: function(params) {
358 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
359 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
360 noSiblingParents = null;
362 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
363 return noSiblingParents;
367 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
368 if(parents1[i].sameNode(parents2[i])) {
373 return {node1: parents1[i], node2: parents2[i]};
376 trigger: function() {
377 Backbone.Events.trigger.apply(this, arguments);
380 getNodeInsertion: function(node) {
382 if(node instanceof DocumentNode) {
383 insertion.ofNode = node;
384 insertion.insertsNew = !this.containsNode(node);
386 insertion.ofNode = this.createDocumentNode(node);
387 insertion.insertsNew = true;
392 registerMethod: function(methodName, method, dstName) {
396 documentNode: doc._nodeMethods,
397 textNode: doc._textNodeMethods,
398 elementNode: doc._elementNodeMethods
400 registerMethod(methodName, method, destination);
403 registerTransformation: function(desc, name, dstName) {
407 documentNode: doc._nodeTransformations,
408 textNode: doc._textNodeTransformations,
409 elementNode: doc._elementNodeTransformations
411 registerTransformation(desc, name, destination);
414 registerExtension: function(extension) {
417 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
418 var dstExtension = extension[dstName];
420 if(dstExtension.methods) {
421 _.pairs(dstExtension.methods).forEach(function(pair) {
422 var methodName = pair[0],
425 doc.registerMethod(methodName, method, dstName);
430 if(dstExtension.transformations) {
431 _.pairs(dstExtension.transformations).forEach(function(pair) {
434 doc.registerTransformation(desc, name, dstName);
441 transform: function(Transformation, args) {
442 var toret, transformation;
444 if(typeof Transformation === 'function') {
445 transformation = new Transformation(this, this, args);
447 transformation = Transformation;
450 this._transformationLevel++;
451 toret = transformation.run({beUndoable:this._transformationLevel === 1});
452 if(this._transformationLevel === 1 && !this._undoInProgress) {
453 if(this._transactionInProgress) {
454 this._transactionStack.push(transformation);
456 this.undoStack.push(transformation);
459 if(!this._undoInProgress && this._transformationLevel === 1) {
462 this._transformationLevel--;
465 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
469 var transformationObject = this.undoStack.pop(),
471 transformations, stopAt;
473 if(transformationObject) {
474 this._undoInProgress = true;
476 if(_.isArray(transformationObject)) {
477 // We will modify this array in a minute so make sure we work on a copy.
478 transformations = transformationObject.slice(0);
480 // Lets normalize single transformation to a transaction containing one transformation.
481 transformations = [transformationObject];
484 if(transformations.length > 1) {
485 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
487 transformations.some(function(t, idx) {
488 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
493 if(stopAt !== undefined) {
494 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
495 transformations = transformations.slice(0, stopAt+1);
499 transformations.reverse();
500 transformations.forEach(function(t) {
504 this._undoInProgress = false;
505 this.redoStack.push(transformationObject);
509 var transformationObject = this.redoStack.pop(),
511 if(transformationObject) {
512 this._transformationLevel++;
513 transformations = _.isArray(transformationObject) ? transformationObject : [transformationObject];
514 transformations.forEach(function(t) {
515 t.run({beUndoable: true});
517 this._transformationLevel--;
518 this.undoStack.push(transformationObject);
522 startTransaction: function() {
523 if(this._transactionInProgress) {
524 throw new Error('Nested transactions not supported!');
526 this._transactionInProgress = true;
529 endTransaction: function() {
530 if(!this._transactionInProgress) {
531 throw new Error('End of transaction requested, but there is no transaction in progress!');
533 this._transactionInProgress = false;
534 if(this._transactionStack.length) {
535 this.undoStack.push(this._transactionStack);
536 this._transactionStack = [];
540 getNodeByPath: function(path) {
541 var toret = this.root;
542 path.forEach(function(idx) {
543 toret = toret.contents()[idx];
548 _defineDocumentProperties: function($document) {
550 Object.defineProperty(doc, 'root', {get: function() {
551 return doc.createDocumentNode($document[0]);
552 }, configurable: true});
553 Object.defineProperty(doc, 'dom', {get: function() {
555 }, configurable: true});
561 documentFromXML: function(xml) {
562 var doc = new Document(xml);
566 elementNodeFromXML: function(xml) {
567 return this.documentFromXML(xml).root;
571 DocumentNode: DocumentNode,
572 ElementNode: ElementNode,