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