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