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 this.document.trigger('change', event);
128 if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
129 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
130 this.document.trigger('change', event);
134 getNodeInsertion: function(node) {
135 return this.document.getNodeInsertion(node);
138 getIndex: function() {
142 return this.parent().indexOf(this);
147 var ElementNode = function(nativeNode, document) {
148 DocumentNode.call(this, nativeNode, document);
150 ElementNode.prototype = Object.create(DocumentNode.prototype);
152 $.extend(ElementNode.prototype, {
153 nodeType: Node.ELEMENT_NODE,
155 setData: function(key, value) {
156 if(value !== undefined) {
157 this._$.data(key, value);
159 this._$.removeData(_.keys(this._$.data()));
164 getData: function(key) {
166 return this._$.data(key);
168 return this._$.data();
171 getTagName: function() {
172 return this.nativeNode.tagName.toLowerCase();
175 contents: function(selector) {
177 document = this.document;
179 this._$.children(selector).each(function() {
180 toret.push(document.createDocumentNode(this));
183 this._$.contents().each(function() {
184 toret.push(document.createDocumentNode(this));
190 indexOf: function(node) {
191 return this._$.contents().index(node._$);
194 getAttr: function(name) {
195 return this._$.attr(name);
198 getAttrs: function() {
200 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
201 toret.push(this.nativeNode.attributes[i]);
207 var wrapper = $('<div>');
208 wrapper.append(this._getXMLDOMToDump());
209 return wrapper.html();
212 _getXMLDOMToDump: function() {
218 var TextNode = function(nativeNode, document) {
219 DocumentNode.call(this, nativeNode, document);
221 TextNode.prototype = Object.create(DocumentNode.prototype);
223 $.extend(TextNode.prototype, {
224 nodeType: Node.TEXT_NODE,
226 getText: function() {
227 return this.nativeNode.data;
230 triggerTextChangeEvent: function() {
231 var event = new events.ChangeEvent('nodeTextChange', {node: this});
232 this.document.trigger('change', event);
237 var parseXML = function(xml) {
238 var toret = $($.trim(xml));
240 throw new Error('Unable to parse XML: ' + xml);
246 var registerTransformation = function(desc, name, target) {
247 var Transformation = transformations.createContextTransformation(desc, name);
248 target[name] = function() {
250 args = Array.prototype.slice.call(arguments, 0);
251 return instance.transform(Transformation, args);
255 var registerMethod = function(methodName, method, target) {
256 if(target[methodName]) {
257 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
258 .replace('{target}', target)
259 .replace('{methodName}', methodName)
262 target[methodName] = method;
266 var Document = function(xml, extensions) {
269 this._transactionStack = [];
270 this._transformationLevel = 0;
272 this._nodeMethods = {};
273 this._textNodeMethods = {};
274 this._elementNodeMethods = {};
275 this._nodeTransformations = {};
276 this._textNodeTransformations = {};
277 this._elementNodeTransformations = {};
279 this.registerExtension(coreTransformations);
281 (extensions || []).forEach(function(extension) {
282 this.registerExtension(extension);
287 $.extend(Document.prototype, Backbone.Events, {
288 ElementNodeFactory: ElementNode,
289 TextNodeFactory: TextNode,
291 createDocumentNode: function(from) {
292 if(!(from instanceof Node)) {
293 if(typeof from === 'string') {
294 from = parseXML(from);
295 this.normalizeXML(from);
297 if(from.text !== undefined) {
298 /* globals document */
299 from = document.createTextNode(from.text);
302 throw new Error('tagName missing');
304 var node = $('<' + from.tagName + '>');
306 _.keys(from.attrs || {}).forEach(function(key) {
307 node.attr(key, from.attrs[key]);
314 var Factory, typeMethods, typeTransformations;
315 if(from.nodeType === Node.TEXT_NODE) {
316 Factory = this.TextNodeFactory;
317 typeMethods = this._textNodeMethods;
318 typeTransformations = this._textNodeTransformations;
319 } else if(from.nodeType === Node.ELEMENT_NODE) {
320 Factory = this.ElementNodeFactory;
321 typeMethods = this._elementNodeMethods;
322 typeTransformations = this._elementNodeTransformations;
324 var toret = new Factory(from, this);
325 _.extend(toret, this._nodeMethods);
326 _.extend(toret, typeMethods);
328 _.extend(toret, this._nodeTransformations);
329 _.extend(toret, typeTransformations);
331 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
332 _.keys(toret.__super__).forEach(function(key) {
333 toret.__super__[key] = _.bind(toret.__super__[key], toret);
339 loadXML: function(xml, options) {
340 options = options || {};
341 this._defineDocumentProperties($(parseXML(xml)));
342 this.normalizeXML(this.dom);
343 if(!options.silent) {
344 this.trigger('contentSet');
348 normalizeXML: function(nativeNode) {
349 void(nativeNode); // noop
353 return this.root.toXML();
356 containsNode: function(node) {
357 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
360 getSiblingParents: function(params) {
361 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
362 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
363 noSiblingParents = null;
365 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
366 return noSiblingParents;
370 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
371 if(parents1[i].sameNode(parents2[i])) {
376 return {node1: parents1[i], node2: parents2[i]};
379 trigger: function() {
380 Backbone.Events.trigger.apply(this, arguments);
383 getNodeInsertion: function(node) {
385 if(node instanceof DocumentNode) {
386 insertion.ofNode = node;
387 insertion.insertsNew = !this.containsNode(node);
389 insertion.ofNode = this.createDocumentNode(node);
390 insertion.insertsNew = true;
395 registerMethod: function(methodName, method, dstName) {
399 documentNode: doc._nodeMethods,
400 textNode: doc._textNodeMethods,
401 elementNode: doc._elementNodeMethods
403 registerMethod(methodName, method, destination);
406 registerTransformation: function(desc, name, dstName) {
410 documentNode: doc._nodeTransformations,
411 textNode: doc._textNodeTransformations,
412 elementNode: doc._elementNodeTransformations
414 registerTransformation(desc, name, destination);
417 registerExtension: function(extension) {
420 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
421 var dstExtension = extension[dstName];
423 if(dstExtension.methods) {
424 _.pairs(dstExtension.methods).forEach(function(pair) {
425 var methodName = pair[0],
428 doc.registerMethod(methodName, method, dstName);
433 if(dstExtension.transformations) {
434 _.pairs(dstExtension.transformations).forEach(function(pair) {
437 doc.registerTransformation(desc, name, dstName);
444 transform: function(Transformation, args) {
445 var toret, transformation;
447 if(typeof Transformation === 'function') {
448 transformation = new Transformation(this, this, args);
450 transformation = Transformation;
453 this._transformationLevel++;
454 toret = transformation.run({beUndoable:this._transformationLevel === 1});
455 if(this._transformationLevel === 1 && !this._undoInProgress) {
456 if(this._transactionInProgress) {
457 this._transactionStack.push(transformation);
459 this.undoStack.push(transformation);
462 if(!this._undoInProgress && this._transformationLevel === 1) {
465 this._transformationLevel--;
468 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
472 var transformationObject = this.undoStack.pop(),
474 transformations, stopAt;
476 if(transformationObject) {
477 this._undoInProgress = true;
479 if(_.isArray(transformationObject)) {
480 // We will modify this array in a minute so make sure we work on a copy.
481 transformations = transformationObject.slice(0);
483 // Lets normalize single transformation to a transaction containing one transformation.
484 transformations = [transformationObject];
487 if(transformations.length > 1) {
488 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
490 transformations.some(function(t, idx) {
491 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
496 if(stopAt !== undefined) {
497 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
498 transformations = transformations.slice(0, stopAt+1);
502 transformations.reverse();
503 transformations.forEach(function(t) {
507 this._undoInProgress = false;
508 this.redoStack.push(transformationObject);
512 var transformationObject = this.redoStack.pop(),
514 if(transformationObject) {
515 this._transformationLevel++;
516 transformations = _.isArray(transformationObject) ? transformationObject : [transformationObject];
517 transformations.forEach(function(t) {
518 t.run({beUndoable: true});
520 this._transformationLevel--;
521 this.undoStack.push(transformationObject);
525 startTransaction: function() {
526 if(this._transactionInProgress) {
527 throw new Error('Nested transactions not supported!');
529 this._transactionInProgress = true;
532 endTransaction: function() {
533 if(!this._transactionInProgress) {
534 throw new Error('End of transaction requested, but there is no transaction in progress!');
536 this._transactionInProgress = false;
537 if(this._transactionStack.length) {
538 this.undoStack.push(this._transactionStack);
539 this._transactionStack = [];
543 getNodeByPath: function(path) {
544 var toret = this.root;
545 path.forEach(function(idx) {
546 toret = toret.contents()[idx];
551 _defineDocumentProperties: function($document) {
553 Object.defineProperty(doc, 'root', {get: function() {
554 return doc.createDocumentNode($document[0]);
555 }, configurable: true});
556 Object.defineProperty(doc, 'dom', {get: function() {
558 }, configurable: true});
564 documentFromXML: function(xml) {
565 var doc = new Document(xml);
569 elementNodeFromXML: function(xml) {
570 return this.documentFromXML(xml).root;
574 DocumentNode: DocumentNode,
575 ElementNode: ElementNode,