editor: removing version number from main bar
[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(key, value) {
180         if(value !== undefined) {
181             this._$.data(key, value);
182         } else {
183             this._$.removeData(_.keys(this._$.data()));
184             this._$.data(key);
185         }
186     },
187
188     getData: function(key) {
189         if(key) {
190             return this._$.data(key);
191         }
192         return this._$.data();
193     },
194
195     getTagName: function() {
196         return this.nativeNode.tagName.toLowerCase();
197     },
198
199     contents: function(selector) {
200         var toret = [],
201             document = this.document;
202         if(selector) {
203             this._$.children(selector).each(function() {
204                 toret.push(document.createDocumentNode(this));
205             });
206         } else {
207             this._$.contents().each(function() {
208                 toret.push(document.createDocumentNode(this));
209             });
210         }
211         return toret;
212     },
213
214     indexOf: function(node) {
215         return this._$.contents().index(node._$);
216     },
217
218     getAttr: function(name) {
219         return this._$.attr(name);
220     },
221
222     getAttrs: function() {
223         var toret = [];
224         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
225             toret.push(this.nativeNode.attributes[i]);
226         }
227         return toret;
228     },
229
230     containsNode: function(node) {
231         return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
232     },
233
234     getLastTextNode: function() {
235         var contents = this.contents(),
236             toret;
237
238         contents.reverse().some(function(node) {
239             if(node.nodeType === Node.TEXT_NODE) {
240                 toret = node;
241                 return true;
242             }
243             toret = node.getLastTextNode();
244             return !!toret;
245         });
246
247         return toret;
248     },
249
250     toXML: function() {
251         var wrapper = $('<div>');
252         wrapper.append(this._getXMLDOMToDump());
253         return wrapper.html();
254     },
255     
256     _getXMLDOMToDump: function() {
257         return this._$;
258     }
259 });
260
261
262 var TextNode = function(nativeNode, document) {
263     DocumentNode.call(this, nativeNode, document);
264 };
265 TextNode.prototype = Object.create(DocumentNode.prototype);
266
267 $.extend(TextNode.prototype, {
268     nodeType: Node.TEXT_NODE,
269
270     getText: function() {
271         return this.nativeNode.data;
272     },
273
274
275     containsNode: function() {
276         return false;
277     },
278
279     triggerTextChangeEvent: function() {
280         var event = new events.ChangeEvent('nodeTextChange', {node: this});
281         this.document.trigger('change', event);
282     }
283 });
284
285
286 var parseXML = function(xml) {
287     var toret = $($.trim(xml));
288     if(!toret.length) {
289         throw new Error('Unable to parse XML: ' + xml);
290     }
291     return toret[0];
292
293 };
294
295 var registerTransformation = function(desc, name, target) {
296     var Transformation = transformations.createContextTransformation(desc, name);
297     target[name] = function() {
298         var instance = this,
299             args = Array.prototype.slice.call(arguments, 0);
300         return instance.transform(Transformation, args);
301     };
302 };
303
304 var registerMethod = function(methodName, method, target) {
305     if(target[methodName]) {
306         throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
307             .replace('{target}', target)
308             .replace('{methodName}', methodName)
309         );
310     }
311     target[methodName] = method;
312 };
313
314
315 var Document = function(xml, extensions) {
316     this.undoStack = [];
317     this.redoStack = [];
318     this._currentTransaction = null;
319     this._transformationLevel = 0;
320     
321     this._nodeMethods = {};
322     this._textNodeMethods = {};
323     this._elementNodeMethods = {};
324     this._nodeTransformations = {};
325     this._textNodeTransformations = {};
326     this._elementNodeTransformations = {};
327     
328     this.registerExtension(coreTransformations);
329
330     (extensions || []).forEach(function(extension) {
331         this.registerExtension(extension);
332     }.bind(this));
333     this.loadXML(xml);
334 };
335
336 $.extend(Document.prototype, Backbone.Events, fragments, {
337     ElementNodeFactory: ElementNode,
338     TextNodeFactory: TextNode,
339
340     createDocumentNode: function(from) {
341         if(!(from instanceof Node)) {
342             if(typeof from === 'string') {
343                 from = parseXML(from);
344                 this.normalizeXML(from);
345             } else {
346                 if(from.text !== undefined) {
347                     /* globals document */
348                     from = document.createTextNode(from.text);
349                 } else {
350                     if(!from.tagName) {
351                         throw new Error('tagName missing');
352                     }
353                     var node = $('<' + from.tagName + '>');
354
355                     _.keys(from.attrs || {}).forEach(function(key) {
356                         node.attr(key, from.attrs[key]);
357                     });
358
359                     from = node[0];
360                 }
361             }
362         }
363         var Factory, typeMethods, typeTransformations;
364         if(from.nodeType === Node.TEXT_NODE) {
365             Factory = this.TextNodeFactory;
366             typeMethods = this._textNodeMethods;
367             typeTransformations = this._textNodeTransformations;
368         } else if(from.nodeType === Node.ELEMENT_NODE) {
369             Factory = this.ElementNodeFactory;
370             typeMethods = this._elementNodeMethods;
371             typeTransformations = this._elementNodeTransformations;
372         }
373         var toret = new Factory(from, this);
374         _.extend(toret, this._nodeMethods);
375         _.extend(toret, typeMethods);
376         
377         _.extend(toret, this._nodeTransformations);
378         _.extend(toret, typeTransformations);
379         
380         toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
381         _.keys(toret.__super__).forEach(function(key) {
382             toret.__super__[key] = _.bind(toret.__super__[key], toret);
383         });
384
385         return toret;
386     },
387
388     loadXML: function(xml, options) {
389         options = options || {};
390         this._defineDocumentProperties($(parseXML(xml)));
391         this.normalizeXML(this.dom);
392         if(!options.silent) {
393             this.trigger('contentSet');
394         }
395     },
396
397     normalizeXML: function(nativeNode) {
398         void(nativeNode); // noop
399     },
400
401     toXML: function() {
402         return this.root.toXML();
403     },
404
405     containsNode: function(node) {
406         return this.root && this.root.containsNode(node);
407     },
408
409     getSiblingParents: function(params) {
410         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
411             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
412             noSiblingParents = null;
413
414         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
415             return noSiblingParents;
416         }
417
418         var stop = Math.min(parents1.length, parents2.length),
419             i;
420         for(i = 0; i < stop; i++) {
421             if(parents1[i].sameNode(parents2[i])) {
422                 continue;
423             }
424             break;
425         }
426         if(i === stop) {
427             i--;
428         }
429         return {node1: parents1[i], node2: parents2[i]};
430     },
431
432     trigger: function() {
433         Backbone.Events.trigger.apply(this, arguments);
434     },
435
436     getNodeInsertion: function(node) {
437         var insertion = {};
438         if(node instanceof DocumentNode) {
439             insertion.ofNode = node;
440             insertion.insertsNew = !this.containsNode(node);
441         } else {
442           insertion.ofNode = this.createDocumentNode(node);
443           insertion.insertsNew = true;
444         }
445         return insertion;
446     },
447
448     registerMethod: function(methodName, method, dstName) {
449         var doc = this;
450         var destination = {
451             document: doc,
452             documentNode: doc._nodeMethods,
453             textNode: doc._textNodeMethods,
454             elementNode: doc._elementNodeMethods
455         }[dstName];
456         registerMethod(methodName, method, destination);
457     },
458
459     registerTransformation: function(desc, name, dstName) {
460         var doc = this;
461         var destination = {
462             document: doc,
463             documentNode: doc._nodeTransformations,
464             textNode: doc._textNodeTransformations,
465             elementNode: doc._elementNodeTransformations
466         }[dstName];
467         registerTransformation(desc, name, destination);
468     },
469
470     registerExtension: function(extension) {
471         var doc = this;
472
473         ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
474             var dstExtension = extension[dstName];
475             if(dstExtension) {
476                 if(dstExtension.methods) {
477                     _.pairs(dstExtension.methods).forEach(function(pair) {
478                         var methodName = pair[0],
479                             method = pair[1];
480
481                         doc.registerMethod(methodName, method, dstName);
482
483                     });
484                 }
485
486                 if(dstExtension.transformations) {
487                     _.pairs(dstExtension.transformations).forEach(function(pair) {
488                         var name = pair[0],
489                             desc = pair[1];
490                         doc.registerTransformation(desc, name, dstName);
491                     });
492                 }
493             }
494         });
495     },
496
497     ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
498         var hasChanged = false,
499             changeMonitor = function() {
500                 hasChanged = true;
501             };
502
503         this.on('change', changeMonitor);
504         action.call(context);
505         this.off('change', changeMonitor);
506         
507         if(hasChanged) {
508             if(documentChangedHandler) {
509                 documentChangedHandler.call(context);
510             }
511         } else {
512             if(documentUnchangedHandler) {
513                 documentUnchangedHandler.call(context);
514             }
515         }
516     },
517
518     transform: function(Transformation, args) {
519         var toret, transformation;
520
521         if(!this._currentTransaction) {
522             return this.transaction(function() {
523                 return this.transform(Transformation, args);
524             }, {context: this});
525         }
526
527         if(typeof Transformation === 'function') {
528             transformation = new Transformation(this, this, args);
529         } else {
530             transformation = Transformation;
531         }
532         if(transformation) {
533             this._transformationLevel++;
534             
535             this.ifChanged(
536                 this,
537                 function() {
538                     toret = transformation.run({beUndoable:this._transformationLevel === 1});
539                 },
540                 function() {
541                     if(this._transformationLevel === 1 && !this._undoInProgress) {
542                         this._currentTransaction.pushTransformation(transformation);
543                         this.redoStack = [];
544                     }
545                 }
546             );
547
548             this._transformationLevel--;
549             return toret;
550         } else {
551             throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
552         }
553     },
554     undo: function() {
555         var transaction = this.undoStack.pop(),
556             doc = this,
557             transformations, stopAt;
558
559         if(transaction) {
560             this._undoInProgress = true;
561
562             // We will modify this array in a minute so make sure we work on a copy.
563             transformations = transaction.transformations.slice(0);
564
565             if(transformations.length > 1) {
566                 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
567                 stopAt = undefined;
568                 transformations.some(function(t, idx) {
569                     if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
570                         stopAt = idx;
571                         return true; //break
572                     }
573                 });
574                 if(stopAt !== undefined) {
575                     // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
576                     transformations = transformations.slice(0, stopAt+1);
577                 }
578             }
579
580             transformations.reverse();
581             transformations.forEach(function(t) {
582                 t.undo();
583             });
584
585             this._undoInProgress = false;
586             this.redoStack.push(transaction);
587             this.trigger('operationEnd');
588         }
589     },
590     redo: function() {
591         var transaction = this.redoStack.pop();
592         if(transaction) {
593             this._transformationLevel++;
594             transaction.transformations.forEach(function(t) {
595                 t.run({beUndoable: true});
596             });
597             this._transformationLevel--;
598             this.undoStack.push(transaction);
599             this.trigger('operationEnd');
600
601         }
602     },
603
604     startTransaction: function(metadata) {
605         if(this._currentTransaction) {
606             throw new Error('Nested transactions not supported!');
607         }
608         this._rollbackBackup = this.root.clone();
609         this._currentTransaction = new Transaction([], metadata);
610     },
611
612     endTransaction: function() {
613         if(!this._currentTransaction) {
614             throw new Error('End of transaction requested, but there is no transaction in progress!');
615         }
616         if(this._currentTransaction.hasTransformations()) {
617             this.undoStack.push(this._currentTransaction);
618             this.trigger('operationEnd');
619         }
620         this._currentTransaction = null;
621     },
622
623     rollbackTransaction: function() {
624         if(!this._currentTransaction) {
625             throw new Error('Transaction rollback requested, but there is no transaction in progress!');
626         }
627         this.replaceRoot(this._rollbackBackup);
628         this._rollbackBackup = null;
629         this._currentTransaction = null;
630         this._transformationLevel = 0;
631     },
632
633     transaction: function(callback, params) {
634         var toret;
635         params = params || {};
636         this.startTransaction(params.metadata);
637         try {
638             toret = callback.call(params.context || this);
639         } catch(e) {
640             if(params.error) {
641                 params.error(e);
642             }
643             this.rollbackTransaction();
644             return;
645         }
646         this.endTransaction();
647         if(params.success) {
648             params.success(toret);
649         }
650         return toret;
651     },
652
653     getNodeByPath: function(path) {
654         var toret = this.root;
655         path.forEach(function(idx) {
656             toret = toret.contents()[idx];
657         });
658         return toret;
659     },
660
661     _defineDocumentProperties: function($document) {
662         var doc = this;
663         Object.defineProperty(doc, 'root', {get: function() {
664             if(!$document) {
665                 return null;
666             }
667             return doc.createDocumentNode($document[0]);
668         }, configurable: true});
669         Object.defineProperty(doc, 'dom', {get: function() {
670             if(!$document) {
671                 return null;
672             }
673             return $document[0];
674         }, configurable: true});
675     },
676
677     createFragment: function(Type, params) {
678         if(!Type.prototype instanceof fragments.Fragment) {
679             throw new Error('Can\'t create a fragment: `Type` is not a valid Fragment');
680         }
681         return new Type(this, params);
682     }
683 });
684
685 var Transaction = function(transformations, metadata) {
686     this.transformations = transformations || [];
687     this.metadata = metadata;
688 };
689 $.extend(Transaction.prototype, {
690     pushTransformation: function(transformation) {
691         this.transformations.push(transformation);
692     },
693     hasTransformations: function() {
694         return this.transformations.length > 0;
695     }
696 });
697
698
699 return {
700     documentFromXML: function(xml) {
701         var doc = new Document(xml);
702         return doc;
703     },
704
705     elementNodeFromXML: function(xml) {
706         return this.documentFromXML(xml).root;
707     },
708
709     Document: Document,
710     DocumentNode: DocumentNode,
711     ElementNode: ElementNode,
712     TextNode: TextNode
713 };
714
715 });