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