smartxml: allow for registering extensions before initial xml processing
[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, extensions) {
264     this.undoStack = [];
265     this.redoStack = [];
266     this._transactionStack = [];
267     this._transformationLevel = 0;
268     
269     this._nodeMethods = {};
270     this._textNodeMethods = {};
271     this._elementNodeMethods = {};
272     this._nodeTransformations = {};
273     this._textNodeTransformations = {};
274     this._elementNodeTransformations = {};
275     
276     this.registerExtension(coreTransformations);
277
278     (extensions || []).forEach(function(extension) {
279         this.registerExtension(extension);
280     }.bind(this));
281     this.loadXML(xml);
282 };
283
284 $.extend(Document.prototype, Backbone.Events, {
285     ElementNodeFactory: ElementNode,
286     TextNodeFactory: TextNode,
287
288     createDocumentNode: function(from) {
289         if(!(from instanceof Node)) {
290             if(typeof from === 'string') {
291                 from = parseXML(from);
292                 this.normalizeXML(from);
293             } else {
294                 if(from.text !== undefined) {
295                     /* globals document */
296                     from = document.createTextNode(from.text);
297                 } else {
298                     if(!from.tagName) {
299                         throw new Error('tagName missing');
300                     }
301                     var node = $('<' + from.tagName + '>');
302
303                     _.keys(from.attrs || {}).forEach(function(key) {
304                         node.attr(key, from.attrs[key]);
305                     });
306
307                     from = node[0];
308                 }
309             }
310         }
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;
320         }
321         var toret = new Factory(from, this);
322         _.extend(toret, this._nodeMethods);
323         _.extend(toret, typeMethods);
324         
325         _.extend(toret, this._nodeTransformations);
326         _.extend(toret, typeTransformations);
327         
328         toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
329         _.keys(toret.__super__).forEach(function(key) {
330             toret.__super__[key] = _.bind(toret.__super__[key], toret);
331         });
332
333         return toret;
334     },
335
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');
342         }
343     },
344
345     normalizeXML: function(nativeNode) {
346         void(nativeNode); // noop
347     },
348
349     toXML: function() {
350         return this.root.toXML();
351     },
352
353     containsNode: function(node) {
354         return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
355     },
356
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;
361
362         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
363             return noSiblingParents;
364         }
365
366         var i;
367         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
368             if(parents1[i].sameNode(parents2[i])) {
369                 continue;
370             }
371             break;
372         }
373         return {node1: parents1[i], node2: parents2[i]};
374     },
375
376     trigger: function() {
377         Backbone.Events.trigger.apply(this, arguments);
378     },
379
380     getNodeInsertion: function(node) {
381         var insertion = {};
382         if(node instanceof DocumentNode) {
383             insertion.ofNode = node;
384             insertion.insertsNew = !this.containsNode(node);
385         } else {
386           insertion.ofNode = this.createDocumentNode(node);
387           insertion.insertsNew = true;
388         }
389         return insertion;
390     },
391
392     registerMethod: function(methodName, method, dstName) {
393         var doc = this;
394         var destination = {
395             document: doc,
396             documentNode: doc._nodeMethods,
397             textNode: doc._textNodeMethods,
398             elementNode: doc._elementNodeMethods
399         }[dstName];
400         registerMethod(methodName, method, destination);
401     },
402
403     registerTransformation: function(desc, name, dstName) {
404         var doc = this;
405         var destination = {
406             document: doc,
407             documentNode: doc._nodeTransformations,
408             textNode: doc._textNodeTransformations,
409             elementNode: doc._elementNodeTransformations
410         }[dstName];
411         registerTransformation(desc, name, destination);
412     },
413
414     registerExtension: function(extension) {
415         var doc = this;
416
417         ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
418             var dstExtension = extension[dstName];
419             if(dstExtension) {
420                 if(dstExtension.methods) {
421                     _.pairs(dstExtension.methods).forEach(function(pair) {
422                         var methodName = pair[0],
423                             method = pair[1];
424
425                         doc.registerMethod(methodName, method, dstName);
426
427                     });
428                 }
429
430                 if(dstExtension.transformations) {
431                     _.pairs(dstExtension.transformations).forEach(function(pair) {
432                         var name = pair[0],
433                             desc = pair[1];
434                         doc.registerTransformation(desc, name, dstName);
435                     });
436                 }
437             }
438         });
439     },
440
441     transform: function(Transformation, args) {
442         var toret, transformation;
443
444         if(typeof Transformation === 'function') {
445             transformation = new Transformation(this, this, args);
446         } else {
447             transformation = Transformation;
448         }
449         if(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);
455                 } else {
456                     this.undoStack.push(transformation);
457                 }
458             }
459             if(!this._undoInProgress && this._transformationLevel === 1) {
460                 this.redoStack = [];
461             }
462             this._transformationLevel--;
463             return toret;
464         } else {
465             throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
466         }
467     },
468     undo: function() {
469         var transformationObject = this.undoStack.pop(),
470             doc = this,
471             transformations, stopAt;
472
473         if(transformationObject) {
474             this._undoInProgress = true;
475
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);
479             } else {
480                 // Lets normalize single transformation to a transaction containing one transformation.
481                 transformations = [transformationObject];
482             }
483
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.
486                 stopAt = undefined;
487                 transformations.some(function(t, idx) {
488                     if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
489                         stopAt = idx;
490                         return true; //break
491                     }
492                 });
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);
496                 }
497             }
498
499             transformations.reverse();
500             transformations.forEach(function(t) {
501                 t.undo();
502             });
503
504             this._undoInProgress = false;
505             this.redoStack.push(transformationObject);
506         }
507     },
508     redo: function() {
509         var transformationObject = this.redoStack.pop(),
510             transformations;
511         if(transformationObject) {
512             this._transformationLevel++;
513             transformations = _.isArray(transformationObject) ? transformationObject : [transformationObject];
514             transformations.forEach(function(t) {
515                 t.run({beUndoable: true});
516             });
517             this._transformationLevel--;
518             this.undoStack.push(transformationObject);
519         }
520     },
521
522     startTransaction: function() {
523         if(this._transactionInProgress) {
524             throw new Error('Nested transactions not supported!');
525         }
526         this._transactionInProgress = true;
527     },
528
529     endTransaction: function() {
530         if(!this._transactionInProgress) {
531             throw new Error('End of transaction requested, but there is no transaction in progress!');
532         }
533         this._transactionInProgress = false;
534         if(this._transactionStack.length) {
535             this.undoStack.push(this._transactionStack);
536             this._transactionStack = [];
537         }
538     },
539
540     getNodeByPath: function(path) {
541         var toret = this.root;
542         path.forEach(function(idx) {
543             toret = toret.contents()[idx];
544         });
545         return toret;
546     },
547
548     _defineDocumentProperties: function($document) {
549         var doc = this;
550         Object.defineProperty(doc, 'root', {get: function() {
551             return doc.createDocumentNode($document[0]);
552         }, configurable: true});
553         Object.defineProperty(doc, 'dom', {get: function() {
554             return $document[0];
555         }, configurable: true});
556     }
557 });
558
559
560 return {
561     documentFromXML: function(xml) {
562         var doc = new Document(xml);
563         return doc;
564     },
565
566     elementNodeFromXML: function(xml) {
567         return this.documentFromXML(xml).root;
568     },
569
570     Document: Document,
571     DocumentNode: DocumentNode,
572     ElementNode: ElementNode,
573     TextNode: TextNode
574 };
575
576 });