smartxml: minor refactoring to improve clarity
[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     'smartxml/fragments'
9 ], function($, _, Backbone, events, transformations, coreTransformations, fragments) {
10     
11 'use strict';
12 /* globals Node */
13
14
15 var DocumentNode = function(nativeNode, document) {
16     if(!document) {
17         throw new Error('undefined document for a node');
18     }
19     this.document = document;
20     this._setNativeNode(nativeNode);
21
22 };
23
24 $.extend(DocumentNode.prototype, {
25
26     transform: function(Transformation, args) {
27         var transformation = new Transformation(this.document, this, args);
28         return this.document.transform(transformation);
29     },
30
31     _setNativeNode: function(nativeNode) {
32         this.nativeNode = nativeNode;
33         this._$ = $(nativeNode);
34     },
35
36     clone: function() {
37         var clone = this._$.clone(true, true),
38             node = this;
39         clone.find('*').addBack().each(function() {
40             var el = this,
41                 clonedData = $(this).data();
42
43             _.pairs(clonedData).forEach(function(pair) {
44                 var key = pair[0],
45                     value = pair[1];
46                 if(_.isFunction(value.clone)) {
47                     clonedData[key] = value.clone(node.document.createDocumentNode(el));
48                 }
49             });
50         });
51         return this.document.createDocumentNode(clone[0]);
52     },
53
54     getPath: function(ancestor) {
55         if(!(this.document.containsNode(this))) {
56             return null;
57         }
58
59         var nodePath = [this].concat(this.parents()),
60             toret, idx;
61         ancestor = ancestor || this.document.root;
62
63         nodePath.some(function(node, i) {
64             if(node.sameNode(ancestor)) {
65                 idx = i;
66                 return true;
67             }
68         });
69
70         if(idx !== undefined) {
71             nodePath = nodePath.slice(0, idx);
72         }
73         toret = nodePath.map(function(node) {return node.getIndex(); });
74         toret.reverse();
75         return toret;
76     },
77
78     isRoot: function() {
79         return this.document.root.sameNode(this);
80     },
81
82     isInDocument: function() {
83         return this.document.containsNode(this);
84     },
85
86     isSiblingOf: function(node) {
87         return node && this.parent().sameNode(node.parent());
88     },
89
90     sameNode: function(otherNode) {
91         return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
92     },
93
94     parent: function() {
95         var parentNode = this.nativeNode.parentNode;
96         if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
97             return this.document.createDocumentNode(parentNode);
98         }
99         return null;
100     },
101
102     parents: function() {
103         var parent = this.parent(),
104             parents = parent ? parent.parents() : [];
105         if(parent) {
106             parents.unshift(parent);
107         }
108         return parents;
109     },
110
111     prev: function() {
112         var myIdx = this.getIndex();
113         return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
114     },
115
116     next: function() {
117         if(this.isRoot()) {
118             return null;
119         }
120         var myIdx = this.getIndex(),
121             parentContents = this.parent().contents();
122         return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
123     },
124
125     isSurroundedByTextNodes: function() {
126         return this.isPrecededByTextNode() && this.isFollowedByTextNode();
127     },
128
129     isPrecededByTextNode: function() {
130         var prev = this.prev();
131         return prev && prev.nodeType === Node.TEXT_NODE;
132     },
133
134     isFollowedByTextNode: function() {
135         var next = this.next();
136         return next && next.nodeType === Node.TEXT_NODE;
137     },
138
139     triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
140         var node = (metaData && metaData.node) ? metaData.node : this,
141             event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
142         if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
143             if(type === 'nodeMoved') {
144                 event.meta.parent = origParent;
145             }
146             this.document.trigger('change', event);
147         }
148         if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
149              event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
150              this.document.trigger('change', event);
151         }
152     },
153     
154     getNodeInsertion: function(node) {
155         return this.document.getNodeInsertion(node);
156     },
157
158     getIndex: function() {
159         if(this.isRoot()) {
160             return 0;
161         }
162         return this.parent().indexOf(this);
163     },
164
165     getNearestElementNode: function() {
166         return this.nodeType === Node.ELEMENT_NODE ? this : this.parent();
167     }
168 });
169
170
171 var ElementNode = function(nativeNode, document) {
172     DocumentNode.call(this, nativeNode, document);
173 };
174 ElementNode.prototype = Object.create(DocumentNode.prototype);
175
176 $.extend(ElementNode.prototype, {
177     nodeType: Node.ELEMENT_NODE,
178
179     setData: function(arg1, arg2) {
180         if(arguments.length === 2) {
181             if(_.isUndefined(arg2)) {
182                 this._$.removeData(arg1);
183             } else {
184                 this._$.data(arg1, arg2);
185             }
186         } else {
187             this._$.removeData(_.keys(this._$.data()));
188             this._$.data(arg1);
189         }
190     },
191
192     getData: function(key) {
193         if(key) {
194             return this._$.data(key);
195         }
196         return this._$.data();
197     },
198
199     getTagName: function() {
200         return this.nativeNode.tagName.toLowerCase();
201     },
202
203     contents: function(selector) {
204         var toret = [],
205             document = this.document;
206         if(selector) {
207             this._$.children(selector).each(function() {
208                 toret.push(document.createDocumentNode(this));
209             });
210         } else {
211             this._$.contents().each(function() {
212                 toret.push(document.createDocumentNode(this));
213             });
214         }
215         return toret;
216     },
217
218     indexOf: function(node) {
219         return this._$.contents().index(node._$);
220     },
221
222     getAttr: function(name) {
223         return this._$.attr(name);
224     },
225
226     getAttrs: function() {
227         var toret = [];
228         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
229             toret.push(this.nativeNode.attributes[i]);
230         }
231         return toret;
232     },
233
234     containsNode: function(node) {
235         return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
236     },
237
238     getLastTextNode: function() {
239         var contents = this.contents(),
240             toret;
241
242         contents.reverse().some(function(node) {
243             if(node.nodeType === Node.TEXT_NODE) {
244                 toret = node;
245                 return true;
246             }
247             toret = node.getLastTextNode();
248             return !!toret;
249         });
250
251         return toret;
252     },
253
254     toXML: function() {
255         var wrapper = $('<div>');
256         wrapper.append(this._getXMLDOMToDump());
257         return wrapper.html();
258     },
259     
260     _getXMLDOMToDump: function() {
261         return this._$;
262     }
263 });
264
265
266 var TextNode = function(nativeNode, document) {
267     DocumentNode.call(this, nativeNode, document);
268 };
269 TextNode.prototype = Object.create(DocumentNode.prototype);
270
271 $.extend(TextNode.prototype, {
272     nodeType: Node.TEXT_NODE,
273
274     getText: function() {
275         return this.nativeNode.data;
276     },
277
278
279     containsNode: function() {
280         return false;
281     },
282
283     triggerTextChangeEvent: function() {
284         var event = new events.ChangeEvent('nodeTextChange', {node: this});
285         this.document.trigger('change', event);
286     }
287 });
288
289
290 var parseXML = function(xml) {
291     var toret = $($.trim(xml));
292     if(!toret.length) {
293         throw new Error('Unable to parse XML: ' + xml);
294     }
295     return toret[0];
296
297 };
298
299 var registerTransformation = function(desc, name, target) {
300     var Transformation = transformations.createContextTransformation(desc, name);
301     target[name] = function() {
302         var instance = this,
303             args = Array.prototype.slice.call(arguments, 0);
304         return instance.transform(Transformation, args);
305     };
306 };
307
308 var registerMethod = function(methodName, method, target) {
309     if(target[methodName]) {
310         throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
311             .replace('{target}', target)
312             .replace('{methodName}', methodName)
313         );
314     }
315     target[methodName] = method;
316 };
317
318
319 var Document = function(xml, extensions) {
320     this.undoStack = [];
321     this.redoStack = [];
322     this._currentTransaction = null;
323     this._transformationLevel = 0;
324     
325     this._nodeMethods = {};
326     this._textNodeMethods = {};
327     this._elementNodeMethods = {};
328     this._nodeTransformations = {};
329     this._textNodeTransformations = {};
330     this._elementNodeTransformations = {};
331     
332     this.registerExtension(coreTransformations);
333
334     (extensions || []).forEach(function(extension) {
335         this.registerExtension(extension);
336     }.bind(this));
337     this.loadXML(xml);
338 };
339
340 $.extend(Document.prototype, Backbone.Events, fragments, {
341     ElementNodeFactory: ElementNode,
342     TextNodeFactory: TextNode,
343
344     createDocumentNode: function(from) {
345         if(!(from instanceof Node)) {
346             if(typeof from === 'string') {
347                 from = parseXML(from);
348                 this.normalizeXML(from);
349             } else {
350                 if(from.text !== undefined) {
351                     /* globals document */
352                     from = document.createTextNode(from.text);
353                 } else {
354                     if(!from.tagName) {
355                         throw new Error('tagName missing');
356                     }
357                     var node = $('<' + from.tagName + '>');
358
359                     _.keys(from.attrs || {}).forEach(function(key) {
360                         node.attr(key, from.attrs[key]);
361                     });
362
363                     from = node[0];
364                 }
365             }
366         }
367         var Factory, typeMethods, typeTransformations;
368         if(from.nodeType === Node.TEXT_NODE) {
369             Factory = this.TextNodeFactory;
370             typeMethods = this._textNodeMethods;
371             typeTransformations = this._textNodeTransformations;
372         } else if(from.nodeType === Node.ELEMENT_NODE) {
373             Factory = this.ElementNodeFactory;
374             typeMethods = this._elementNodeMethods;
375             typeTransformations = this._elementNodeTransformations;
376         }
377         var toret = new Factory(from, this);
378         _.extend(toret, this._nodeMethods);
379         _.extend(toret, typeMethods);
380         
381         _.extend(toret, this._nodeTransformations);
382         _.extend(toret, typeTransformations);
383         
384         toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
385         _.keys(toret.__super__).forEach(function(key) {
386             toret.__super__[key] = _.bind(toret.__super__[key], toret);
387         });
388
389         return toret;
390     },
391
392     loadXML: function(xml, options) {
393         options = options || {};
394         this._defineDocumentProperties($(parseXML(xml)));
395         this.normalizeXML(this.dom);
396         if(!options.silent) {
397             this.trigger('contentSet');
398         }
399     },
400
401     normalizeXML: function(nativeNode) {
402         void(nativeNode); // noop
403     },
404
405     toXML: function() {
406         return this.root.toXML();
407     },
408
409     containsNode: function(node) {
410         return this.root && this.root.containsNode(node);
411     },
412
413     getSiblingParents: function(params) {
414         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
415             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
416             noSiblingParents = null;
417
418         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
419             return noSiblingParents;
420         }
421
422         var stop = Math.min(parents1.length, parents2.length),
423             i;
424         for(i = 0; i < stop; i++) {
425             if(parents1[i].sameNode(parents2[i])) {
426                 continue;
427             }
428             break;
429         }
430         if(i === stop) {
431             i--;
432         }
433         return {node1: parents1[i], node2: parents2[i]};
434     },
435
436     trigger: function() {
437         Backbone.Events.trigger.apply(this, arguments);
438     },
439
440     getNodeInsertion: function(node) {
441         var insertion = {};
442         if(node instanceof DocumentNode) {
443             insertion.ofNode = node;
444             insertion.insertsNew = !this.containsNode(node);
445         } else {
446           insertion.ofNode = this.createDocumentNode(node);
447           insertion.insertsNew = true;
448         }
449         return insertion;
450     },
451
452     registerMethod: function(methodName, method, dstName) {
453         var doc = this;
454         var destination = {
455             document: doc,
456             documentNode: doc._nodeMethods,
457             textNode: doc._textNodeMethods,
458             elementNode: doc._elementNodeMethods
459         }[dstName];
460         registerMethod(methodName, method, destination);
461     },
462
463     registerTransformation: function(desc, name, dstName) {
464         var doc = this;
465         var destination = {
466             document: doc,
467             documentNode: doc._nodeTransformations,
468             textNode: doc._textNodeTransformations,
469             elementNode: doc._elementNodeTransformations
470         }[dstName];
471         registerTransformation(desc, name, destination);
472     },
473
474     registerExtension: function(extension) {
475         var doc = this;
476
477         ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
478             var dstExtension = extension[dstName];
479             if(dstExtension) {
480                 if(dstExtension.methods) {
481                     _.pairs(dstExtension.methods).forEach(function(pair) {
482                         var methodName = pair[0],
483                             method = pair[1];
484
485                         doc.registerMethod(methodName, method, dstName);
486
487                     });
488                 }
489
490                 if(dstExtension.transformations) {
491                     _.pairs(dstExtension.transformations).forEach(function(pair) {
492                         var name = pair[0],
493                             desc = pair[1];
494                         doc.registerTransformation(desc, name, dstName);
495                     });
496                 }
497             }
498         });
499     },
500
501     ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
502         var hasChanged = false,
503             changeMonitor = function() {
504                 hasChanged = true;
505             };
506
507         this.on('change', changeMonitor);
508         action.call(context);
509         this.off('change', changeMonitor);
510         
511         if(hasChanged) {
512             if(documentChangedHandler) {
513                 documentChangedHandler.call(context);
514             }
515         } else {
516             if(documentUnchangedHandler) {
517                 documentUnchangedHandler.call(context);
518             }
519         }
520     },
521
522     transform: function(Transformation, args) {
523         var toret, transformation;
524
525         if(!this._currentTransaction) {
526             return this.transaction(function() {
527                 return this.transform(Transformation, args);
528             }, {context: this});
529         }
530
531         if(typeof Transformation === 'function') {
532             transformation = new Transformation(this, this, args);
533         } else {
534             transformation = Transformation;
535         }
536         if(transformation) {
537             this._transformationLevel++;
538             
539             this.ifChanged(
540                 this,
541                 function() {
542                     toret = transformation.run({beUndoable:this._transformationLevel === 1});
543                 },
544                 function() {
545                     if(this._transformationLevel === 1 && !this._undoInProgress) {
546                         this._currentTransaction.pushTransformation(transformation);
547                         this.redoStack = [];
548                     }
549                 }
550             );
551
552             this._transformationLevel--;
553             return toret;
554         } else {
555             throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
556         }
557     },
558     undo: function() {
559         var transaction = this.undoStack.pop(),
560             doc = this,
561             transformations, stopAt;
562
563         if(transaction) {
564             this._undoInProgress = true;
565
566             // We will modify this array in a minute so make sure we work on a copy.
567             transformations = transaction.transformations.slice(0);
568
569             if(transformations.length > 1) {
570                 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
571                 stopAt = undefined;
572                 transformations.some(function(t, idx) {
573                     if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
574                         stopAt = idx;
575                         return true; //break
576                     }
577                 });
578                 if(stopAt !== undefined) {
579                     // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
580                     transformations = transformations.slice(0, stopAt+1);
581                 }
582             }
583
584             transformations.reverse();
585             transformations.forEach(function(t) {
586                 t.undo();
587             });
588
589             this._undoInProgress = false;
590             this.redoStack.push(transaction);
591             this.trigger('operationEnd');
592         }
593     },
594     redo: function() {
595         var transaction = this.redoStack.pop();
596         if(transaction) {
597             this._transformationLevel++;
598             transaction.transformations.forEach(function(t) {
599                 t.run({beUndoable: true});
600             });
601             this._transformationLevel--;
602             this.undoStack.push(transaction);
603             this.trigger('operationEnd');
604
605         }
606     },
607
608     startTransaction: function(metadata) {
609         if(this._currentTransaction) {
610             throw new Error('Nested transactions not supported!');
611         }
612         this._rollbackBackup = this.root.clone();
613         this._currentTransaction = new Transaction([], metadata);
614     },
615
616     endTransaction: function() {
617         if(!this._currentTransaction) {
618             throw new Error('End of transaction requested, but there is no transaction in progress!');
619         }
620         if(this._currentTransaction.hasTransformations()) {
621             this.undoStack.push(this._currentTransaction);
622             this.trigger('operationEnd');
623         }
624         this._currentTransaction = null;
625     },
626
627     rollbackTransaction: function() {
628         if(!this._currentTransaction) {
629             throw new Error('Transaction rollback requested, but there is no transaction in progress!');
630         }
631         this.replaceRoot(this._rollbackBackup);
632         this._rollbackBackup = null;
633         this._currentTransaction = null;
634         this._transformationLevel = 0;
635     },
636
637     transaction: function(callback, params) {
638         var toret;
639         params = params || {};
640         this.startTransaction(params.metadata);
641         try {
642             toret = callback.call(params.context || this);
643         } catch(e) {
644             if(params.error) {
645                 params.error(e);
646             }
647             this.rollbackTransaction();
648             return;
649         }
650         this.endTransaction();
651         if(params.success) {
652             params.success(toret);
653         }
654         return toret;
655     },
656
657     getNodeByPath: function(path) {
658         var toret = this.root;
659         path.forEach(function(idx) {
660             toret = toret.contents()[idx];
661         });
662         return toret;
663     },
664
665     _defineDocumentProperties: function($document) {
666         var doc = this;
667         Object.defineProperty(doc, 'root', {get: function() {
668             if(!$document) {
669                 return null;
670             }
671             return doc.createDocumentNode($document[0]);
672         }, configurable: true});
673         Object.defineProperty(doc, 'dom', {get: function() {
674             if(!$document) {
675                 return null;
676             }
677             return $document[0];
678         }, configurable: true});
679     },
680
681     createFragment: function(Type, params) {
682         if(!Type.prototype instanceof fragments.Fragment) {
683             throw new Error('Can\'t create a fragment: `Type` is not a valid Fragment');
684         }
685         return new Type(this, params);
686     }
687 });
688
689 var Transaction = function(transformations, metadata) {
690     this.transformations = transformations || [];
691     this.metadata = metadata;
692 };
693 $.extend(Transaction.prototype, {
694     pushTransformation: function(transformation) {
695         this.transformations.push(transformation);
696     },
697     hasTransformations: function() {
698         return this.transformations.length > 0;
699     }
700 });
701
702
703 return {
704     documentFromXML: function(xml) {
705         var doc = new Document(xml);
706         return doc;
707     },
708
709     elementNodeFromXML: function(xml) {
710         return this.documentFromXML(xml).root;
711     },
712
713     Document: Document,
714     DocumentNode: DocumentNode,
715     ElementNode: ElementNode,
716     TextNode: TextNode
717 };
718
719 });