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