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