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