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]);
206 containsNode: function(node) {
207 return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
211 var wrapper = $('<div>');
212 wrapper.append(this._getXMLDOMToDump());
213 return wrapper.html();
216 _getXMLDOMToDump: function() {
222 var TextNode = function(nativeNode, document) {
223 DocumentNode.call(this, nativeNode, document);
225 TextNode.prototype = Object.create(DocumentNode.prototype);
227 $.extend(TextNode.prototype, {
228 nodeType: Node.TEXT_NODE,
230 getText: function() {
231 return this.nativeNode.data;
234 triggerTextChangeEvent: function() {
235 var event = new events.ChangeEvent('nodeTextChange', {node: this});
236 this.document.trigger('change', event);
241 var parseXML = function(xml) {
242 var toret = $($.trim(xml));
244 throw new Error('Unable to parse XML: ' + xml);
250 var registerTransformation = function(desc, name, target) {
251 var Transformation = transformations.createContextTransformation(desc, name);
252 target[name] = function() {
254 args = Array.prototype.slice.call(arguments, 0);
255 return instance.transform(Transformation, args);
259 var registerMethod = function(methodName, method, target) {
260 if(target[methodName]) {
261 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
262 .replace('{target}', target)
263 .replace('{methodName}', methodName)
266 target[methodName] = method;
270 var Document = function(xml, extensions) {
273 this._transactionStack = [];
274 this._transformationLevel = 0;
276 this._nodeMethods = {};
277 this._textNodeMethods = {};
278 this._elementNodeMethods = {};
279 this._nodeTransformations = {};
280 this._textNodeTransformations = {};
281 this._elementNodeTransformations = {};
283 this.registerExtension(coreTransformations);
285 (extensions || []).forEach(function(extension) {
286 this.registerExtension(extension);
291 $.extend(Document.prototype, Backbone.Events, {
292 ElementNodeFactory: ElementNode,
293 TextNodeFactory: TextNode,
295 createDocumentNode: function(from) {
296 if(!(from instanceof Node)) {
297 if(typeof from === 'string') {
298 from = parseXML(from);
299 this.normalizeXML(from);
301 if(from.text !== undefined) {
302 /* globals document */
303 from = document.createTextNode(from.text);
306 throw new Error('tagName missing');
308 var node = $('<' + from.tagName + '>');
310 _.keys(from.attrs || {}).forEach(function(key) {
311 node.attr(key, from.attrs[key]);
318 var Factory, typeMethods, typeTransformations;
319 if(from.nodeType === Node.TEXT_NODE) {
320 Factory = this.TextNodeFactory;
321 typeMethods = this._textNodeMethods;
322 typeTransformations = this._textNodeTransformations;
323 } else if(from.nodeType === Node.ELEMENT_NODE) {
324 Factory = this.ElementNodeFactory;
325 typeMethods = this._elementNodeMethods;
326 typeTransformations = this._elementNodeTransformations;
328 var toret = new Factory(from, this);
329 _.extend(toret, this._nodeMethods);
330 _.extend(toret, typeMethods);
332 _.extend(toret, this._nodeTransformations);
333 _.extend(toret, typeTransformations);
335 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
336 _.keys(toret.__super__).forEach(function(key) {
337 toret.__super__[key] = _.bind(toret.__super__[key], toret);
343 loadXML: function(xml, options) {
344 options = options || {};
345 this._defineDocumentProperties($(parseXML(xml)));
346 this.normalizeXML(this.dom);
347 if(!options.silent) {
348 this.trigger('contentSet');
352 normalizeXML: function(nativeNode) {
353 void(nativeNode); // noop
357 return this.root.toXML();
360 containsNode: function(node) {
361 return this.root && this.root.containsNode(node);
364 getSiblingParents: function(params) {
365 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
366 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
367 noSiblingParents = null;
369 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
370 return noSiblingParents;
374 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
375 if(parents1[i].sameNode(parents2[i])) {
380 return {node1: parents1[i], node2: parents2[i]};
383 trigger: function() {
384 Backbone.Events.trigger.apply(this, arguments);
387 getNodeInsertion: function(node) {
389 if(node instanceof DocumentNode) {
390 insertion.ofNode = node;
391 insertion.insertsNew = !this.containsNode(node);
393 insertion.ofNode = this.createDocumentNode(node);
394 insertion.insertsNew = true;
399 registerMethod: function(methodName, method, dstName) {
403 documentNode: doc._nodeMethods,
404 textNode: doc._textNodeMethods,
405 elementNode: doc._elementNodeMethods
407 registerMethod(methodName, method, destination);
410 registerTransformation: function(desc, name, dstName) {
414 documentNode: doc._nodeTransformations,
415 textNode: doc._textNodeTransformations,
416 elementNode: doc._elementNodeTransformations
418 registerTransformation(desc, name, destination);
421 registerExtension: function(extension) {
424 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
425 var dstExtension = extension[dstName];
427 if(dstExtension.methods) {
428 _.pairs(dstExtension.methods).forEach(function(pair) {
429 var methodName = pair[0],
432 doc.registerMethod(methodName, method, dstName);
437 if(dstExtension.transformations) {
438 _.pairs(dstExtension.transformations).forEach(function(pair) {
441 doc.registerTransformation(desc, name, dstName);
448 ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
449 var hasChanged = false,
450 changeMonitor = function() {
454 this.on('change', changeMonitor);
455 action.call(context);
456 this.off('change', changeMonitor);
459 if(documentChangedHandler) {
460 documentChangedHandler.call(context);
463 if(documentUnchangedHandler) {
464 documentUnchangedHandler.call(context);
469 transform: function(Transformation, args) {
470 var toret, transformation;
472 if(typeof Transformation === 'function') {
473 transformation = new Transformation(this, this, args);
475 transformation = Transformation;
478 this._transformationLevel++;
483 toret = transformation.run({beUndoable:this._transformationLevel === 1});
486 if(this._transformationLevel === 1 && !this._undoInProgress) {
487 if(this._transactionInProgress) {
488 this._transactionStack.push(transformation);
490 this.undoStack.push(transformation);
493 if(!this._undoInProgress && this._transformationLevel === 1) {
499 this._transformationLevel--;
502 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
506 var transformationObject = this.undoStack.pop(),
508 transformations, stopAt;
510 if(transformationObject) {
511 this._undoInProgress = true;
513 if(_.isArray(transformationObject)) {
514 // We will modify this array in a minute so make sure we work on a copy.
515 transformations = transformationObject.slice(0);
517 // Lets normalize single transformation to a transaction containing one transformation.
518 transformations = [transformationObject];
521 if(transformations.length > 1) {
522 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
524 transformations.some(function(t, idx) {
525 if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
530 if(stopAt !== undefined) {
531 // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
532 transformations = transformations.slice(0, stopAt+1);
536 transformations.reverse();
537 transformations.forEach(function(t) {
541 this._undoInProgress = false;
542 this.redoStack.push(transformationObject);
546 var transformationObject = this.redoStack.pop(),
548 if(transformationObject) {
549 this._transformationLevel++;
550 transformations = _.isArray(transformationObject) ? transformationObject : [transformationObject];
551 transformations.forEach(function(t) {
552 t.run({beUndoable: true});
554 this._transformationLevel--;
555 this.undoStack.push(transformationObject);
559 startTransaction: function() {
560 if(this._transactionInProgress) {
561 throw new Error('Nested transactions not supported!');
563 this._transactionInProgress = true;
566 endTransaction: function() {
567 if(!this._transactionInProgress) {
568 throw new Error('End of transaction requested, but there is no transaction in progress!');
570 this._transactionInProgress = false;
571 if(this._transactionStack.length) {
572 this.undoStack.push(this._transactionStack);
573 this._transactionStack = [];
577 transaction: function(callback, context) {
578 this.startTransaction();
579 callback.call(context);
580 this.endTransaction();
583 getNodeByPath: function(path) {
584 var toret = this.root;
585 path.forEach(function(idx) {
586 toret = toret.contents()[idx];
591 _defineDocumentProperties: function($document) {
593 Object.defineProperty(doc, 'root', {get: function() {
594 return doc.createDocumentNode($document[0]);
595 }, configurable: true});
596 Object.defineProperty(doc, 'dom', {get: function() {
598 }, configurable: true});
604 documentFromXML: function(xml) {
605 var doc = new Document(xml);
609 elementNodeFromXML: function(xml) {
610 return this.documentFromXML(xml).root;
614 DocumentNode: DocumentNode,
615 ElementNode: ElementNode,