smartxml: allow objects set with setData to clone themselves on node cloning
[fnpeditor.git] / src / smartxml / smartxml.js
1 define([
2     'libs/jquery',
3     'libs/underscore',
4     'libs/backbone',
5     'smartxml/events',
6     'smartxml/transformations',
7     'smartxml/core'
8 ], function($, _, Backbone, events, transformations, coreTransformations) {
9     
10 'use strict';
11 /* globals Node */
12
13
14 var DocumentNode = function(nativeNode, document) {
15     if(!document) {
16         throw new Error('undefined document for a node');
17     }
18     this.document = document;
19     this._setNativeNode(nativeNode);
20
21 };
22
23 $.extend(DocumentNode.prototype, {
24
25     transform: function(Transformation, args) {
26         var transformation = new Transformation(this.document, this, args);
27         return this.document.transform(transformation);
28     },
29
30     _setNativeNode: function(nativeNode) {
31         this.nativeNode = nativeNode;
32         this._$ = $(nativeNode);
33     },
34
35     clone: function() {
36         var clone = this._$.clone(true, true);
37         clone.find('*').addBack().each(function() {
38             var clonedData = $(this).data();
39             _.pairs(clonedData).forEach(function(pair) {
40                 var key = pair[0],
41                     value = pair[1];
42                 if(_.isFunction(value.clone)) {
43                     clonedData[key] = value.clone();
44                 }
45             });
46         });
47         return this.document.createDocumentNode(clone[0]);
48     },
49
50     getPath: function(ancestor) {
51         if(!(this.document.containsNode(this))) {
52             return null;
53         }
54
55         var nodePath = [this].concat(this.parents()),
56             toret, idx;
57         ancestor = ancestor || this.document.root;
58
59         nodePath.some(function(node, i) {
60             if(node.sameNode(ancestor)) {
61                 idx = i;
62                 return true;
63             }
64         });
65
66         if(idx !== 'undefined') {
67             nodePath = nodePath.slice(0, idx);
68         }
69         toret = nodePath.map(function(node) {return node.getIndex(); });
70         toret.reverse();
71         return toret;
72     },
73
74     isRoot: function() {
75         return this.document.root.sameNode(this);
76     },
77
78     sameNode: function(otherNode) {
79         return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
80     },
81
82     parent: function() {
83         var parentNode = this.nativeNode.parentNode;
84         if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
85             return this.document.createDocumentNode(parentNode);
86         }
87         return null;
88     },
89
90     parents: function() {
91         var parent = this.parent(),
92             parents = parent ? parent.parents() : [];
93         if(parent) {
94             parents.unshift(parent);
95         }
96         return parents;
97     },
98
99     prev: function() {
100         var myIdx = this.getIndex();
101         return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
102     },
103
104     next: function() {
105         if(this.isRoot()) {
106             return null;
107         }
108         var myIdx = this.getIndex(),
109             parentContents = this.parent().contents();
110         return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
111     },
112
113     isSurroundedByTextElements: function() {
114         var prev = this.prev(),
115             next = this.next();
116         return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
117     },
118
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);
124         }
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);
128         }
129     },
130     
131     getNodeInsertion: function(node) {
132         return this.document.getNodeInsertion(node);
133     },
134
135     getIndex: function() {
136         if(this.isRoot()) {
137             return 0;
138         }
139         return this.parent().indexOf(this);
140     }
141 });
142
143
144 var ElementNode = function(nativeNode, document) {
145     DocumentNode.call(this, nativeNode, document);
146 };
147 ElementNode.prototype = Object.create(DocumentNode.prototype);
148
149 $.extend(ElementNode.prototype, {
150     nodeType: Node.ELEMENT_NODE,
151
152     setData: function(key, value) {
153         if(value !== undefined) {
154             this._$.data(key, value);
155         } else {
156             this._$.removeData(_.keys(this._$.data()));
157             this._$.data(key);
158         }
159     },
160
161     getData: function(key) {
162         if(key) {
163             return this._$.data(key);
164         }
165         return this._$.data();
166     },
167
168     getTagName: function() {
169         return this.nativeNode.tagName.toLowerCase();
170     },
171
172     contents: function(selector) {
173         var toret = [],
174             document = this.document;
175         if(selector) {
176             this._$.children(selector).each(function() {
177                 toret.push(document.createDocumentNode(this));
178             });
179         } else {
180             this._$.contents().each(function() {
181                 toret.push(document.createDocumentNode(this));
182             });
183         }
184         return toret;
185     },
186
187     indexOf: function(node) {
188         return this._$.contents().index(node._$);
189     },
190
191     getAttr: function(name) {
192         return this._$.attr(name);
193     },
194
195     getAttrs: function() {
196         var toret = [];
197         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
198             toret.push(this.nativeNode.attributes[i]);
199         }
200         return toret;
201     },
202
203     toXML: function() {
204         var wrapper = $('<div>');
205         wrapper.append(this._getXMLDOMToDump());
206         return wrapper.html();
207     },
208     
209     _getXMLDOMToDump: function() {
210         return this._$;
211     }
212 });
213
214
215 var TextNode = function(nativeNode, document) {
216     DocumentNode.call(this, nativeNode, document);
217 };
218 TextNode.prototype = Object.create(DocumentNode.prototype);
219
220 $.extend(TextNode.prototype, {
221     nodeType: Node.TEXT_NODE,
222
223     getText: function() {
224         return this.nativeNode.data;
225     },
226
227     triggerTextChangeEvent: function() {
228         var event = new events.ChangeEvent('nodeTextChange', {node: this});
229         this.document.trigger('change', event);
230     }
231 });
232
233
234 var parseXML = function(xml) {
235     var toret = $($.trim(xml));
236     if(!toret.length) {
237         throw new Error('Unable to parse XML: ' + xml);
238     }
239     return toret[0];
240
241 };
242
243 var registerTransformation = function(desc, name, target) {
244     var Transformation = transformations.createContextTransformation(desc, name);
245     target[name] = function() {
246         var instance = this,
247             args = Array.prototype.slice.call(arguments, 0);
248         return instance.transform(Transformation, args);
249     };
250 };
251
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)
257         );
258     }
259     target[methodName] = method;
260 };
261
262
263 var Document = function(xml) {
264     this.loadXML(xml);
265     this.undoStack = [];
266     this.redoStack = [];
267     this._transactionStack = [];
268     this._transformationLevel = 0;
269     
270     this._nodeMethods = {};
271     this._textNodeMethods = {};
272     this._elementNodeMethods = {};
273     this._nodeTransformations = {};
274     this._textNodeTransformations = {};
275     this._elementNodeTransformations = {};
276     
277     this.registerExtension(coreTransformations);
278 };
279
280 $.extend(Document.prototype, Backbone.Events, {
281     ElementNodeFactory: ElementNode,
282     TextNodeFactory: TextNode,
283
284     createDocumentNode: function(from) {
285         if(!(from instanceof Node)) {
286             if(typeof from === 'string') {
287                 from = parseXML(from);
288                 this.normalizeXML(from);
289             } else {
290                 if(from.text !== undefined) {
291                     /* globals document */
292                     from = document.createTextNode(from.text);
293                 } else {
294                     if(!from.tagName) {
295                         throw new Error('tagName missing');
296                     }
297                     var node = $('<' + from.tagName + '>');
298
299                     _.keys(from.attrs || {}).forEach(function(key) {
300                         node.attr(key, from.attrs[key]);
301                     });
302
303                     from = node[0];
304                 }
305             }
306         }
307         var Factory, typeMethods, typeTransformations;
308         if(from.nodeType === Node.TEXT_NODE) {
309             Factory = this.TextNodeFactory;
310             typeMethods = this._textNodeMethods;
311             typeTransformations = this._textNodeTransformations;
312         } else if(from.nodeType === Node.ELEMENT_NODE) {
313             Factory = this.ElementNodeFactory;
314             typeMethods = this._elementNodeMethods;
315             typeTransformations = this._elementNodeTransformations;
316         }
317         var toret = new Factory(from, this);
318         _.extend(toret, this._nodeMethods);
319         _.extend(toret, typeMethods);
320         
321         _.extend(toret, this._nodeTransformations);
322         _.extend(toret, typeTransformations);
323         
324         toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
325         _.keys(toret.__super__).forEach(function(key) {
326             toret.__super__[key] = _.bind(toret.__super__[key], toret);
327         });
328
329         return toret;
330     },
331
332     loadXML: function(xml, options) {
333         options = options || {};
334         this._defineDocumentProperties($(parseXML(xml)));
335         this.normalizeXML(this.dom);
336         if(!options.silent) {
337             this.trigger('contentSet');
338         }
339     },
340
341     normalizeXML: function(nativeNode) {
342         void(nativeNode); // noop
343     },
344
345     toXML: function() {
346         return this.root.toXML();
347     },
348
349     containsNode: function(node) {
350         return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
351     },
352
353     getSiblingParents: function(params) {
354         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
355             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
356             noSiblingParents = null;
357
358         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
359             return noSiblingParents;
360         }
361
362         var i;
363         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
364             if(parents1[i].sameNode(parents2[i])) {
365                 continue;
366             }
367             break;
368         }
369         return {node1: parents1[i], node2: parents2[i]};
370     },
371
372     trigger: function() {
373         Backbone.Events.trigger.apply(this, arguments);
374     },
375
376     getNodeInsertion: function(node) {
377         var insertion = {};
378         if(node instanceof DocumentNode) {
379             insertion.ofNode = node;
380             insertion.insertsNew = !this.containsNode(node);
381         } else {
382           insertion.ofNode = this.createDocumentNode(node);
383           insertion.insertsNew = true;
384         }
385         return insertion;
386     },
387
388     registerMethod: function(methodName, method, dstName) {
389         var doc = this;
390         var destination = {
391             document: doc,
392             documentNode: doc._nodeMethods,
393             textNode: doc._textNodeMethods,
394             elementNode: doc._elementNodeMethods
395         }[dstName];
396         registerMethod(methodName, method, destination);
397     },
398
399     registerTransformation: function(desc, name, dstName) {
400         var doc = this;
401         var destination = {
402             document: doc,
403             documentNode: doc._nodeTransformations,
404             textNode: doc._textNodeTransformations,
405             elementNode: doc._elementNodeTransformations
406         }[dstName];
407         registerTransformation(desc, name, destination);
408     },
409
410     registerExtension: function(extension) {
411         var doc = this;
412
413         ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
414             var dstExtension = extension[dstName];
415             if(dstExtension) {
416                 if(dstExtension.methods) {
417                     _.pairs(dstExtension.methods).forEach(function(pair) {
418                         var methodName = pair[0],
419                             method = pair[1];
420
421                         doc.registerMethod(methodName, method, dstName);
422
423                     });
424                 }
425
426                 if(dstExtension.transformations) {
427                     _.pairs(dstExtension.transformations).forEach(function(pair) {
428                         var name = pair[0],
429                             desc = pair[1];
430                         doc.registerTransformation(desc, name, dstName);
431                     });
432                 }
433             }
434         });
435     },
436
437     transform: function(Transformation, args) {
438         var toret, transformation;
439
440         if(typeof Transformation === 'function') {
441             transformation = new Transformation(this, this, args);
442         } else {
443             transformation = Transformation;
444         }
445         if(transformation) {
446             this._transformationLevel++;
447             toret = transformation.run({beUndoable:this._transformationLevel === 1});
448             if(this._transformationLevel === 1 && !this._undoInProgress) {
449                 if(this._transactionInProgress) {
450                     this._transactionStack.push(transformation);
451                 } else {
452                     this.undoStack.push(transformation);
453                 }
454             }
455             if(!this._undoInProgress && this._transformationLevel === 1) {
456                 this.redoStack = [];
457             }
458             this._transformationLevel--;
459             return toret;
460         } else {
461             throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
462         }
463     },
464     undo: function() {
465         var transformationObject = this.undoStack.pop(),
466             doc = this,
467             transformations, stopAt;
468
469         if(transformationObject) {
470             this._undoInProgress = true;
471
472             if(_.isArray(transformationObject)) {
473                 // We will modify this array in a minute so make sure we work on a copy.
474                 transformations = transformationObject.slice(0);
475             } else {
476                 // Lets normalize single transformation to a transaction containing one transformation.
477                 transformations = [transformationObject];
478             }
479
480             if(transformations.length > 1) {
481                 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
482                 stopAt = undefined;
483                 transformations.some(function(t, idx) {
484                     if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
485                         stopAt = idx;
486                         return true; //break
487                     }
488                 });
489                 if(stopAt !== undefined) {
490                     // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
491                     transformations = transformations.slice(0, stopAt+1);
492                 }
493             }
494
495             transformations.reverse();
496             transformations.forEach(function(t) {
497                 t.undo();
498             });
499
500             this._undoInProgress = false;
501             this.redoStack.push(transformationObject);
502         }
503     },
504     redo: function() {
505         var transformationObject = this.redoStack.pop(),
506             transformations;
507         if(transformationObject) {
508             this._transformationLevel++;
509             transformations = _.isArray(transformationObject) ? transformationObject : [transformationObject];
510             transformations.forEach(function(t) {
511                 t.run({beUndoable: true});
512             });
513             this._transformationLevel--;
514             this.undoStack.push(transformationObject);
515         }
516     },
517
518     startTransaction: function() {
519         if(this._transactionInProgress) {
520             throw new Error('Nested transactions not supported!');
521         }
522         this._transactionInProgress = true;
523     },
524
525     endTransaction: function() {
526         if(!this._transactionInProgress) {
527             throw new Error('End of transaction requested, but there is no transaction in progress!');
528         }
529         this._transactionInProgress = false;
530         if(this._transactionStack.length) {
531             this.undoStack.push(this._transactionStack);
532             this._transactionStack = [];
533         }
534     },
535
536     getNodeByPath: function(path) {
537         var toret = this.root;
538         path.forEach(function(idx) {
539             toret = toret.contents()[idx];
540         });
541         return toret;
542     },
543
544     _defineDocumentProperties: function($document) {
545         var doc = this;
546         Object.defineProperty(doc, 'root', {get: function() {
547             return doc.createDocumentNode($document[0]);
548         }, configurable: true});
549         Object.defineProperty(doc, 'dom', {get: function() {
550             return $document[0];
551         }, configurable: true});
552     }
553 });
554
555
556 return {
557     documentFromXML: function(xml) {
558         var doc = new Document(xml);
559         return doc;
560     },
561
562     elementNodeFromXML: function(xml) {
563         return this.documentFromXML(xml).root;
564     },
565
566     Document: Document,
567     DocumentNode: DocumentNode,
568     ElementNode: ElementNode,
569     TextNode: TextNode
570 };
571
572 });