smartxml: raise an Error on invalid XML
[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     var toret = $($.trim(xml));
226     if(!toret.length) {
227         throw new Error('Unable to parse XML: ' + xml);
228     }
229     return toret[0];
230
231 };
232
233 var registerTransformation = function(desc, name, target) {
234     var Transformation = transformations.createContextTransformation(desc, name);
235     target[name] = function() {
236         var instance = this,
237             args = Array.prototype.slice.call(arguments, 0);
238         return instance.transform(Transformation, args);
239     };
240 };
241
242 var registerMethod = function(methodName, method, target) {
243     if(target[methodName]) {
244         throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
245             .replace('{target}', target)
246             .replace('{methodName}', methodName)
247         );
248     }
249     target[methodName] = method;
250 };
251
252
253 var Document = function(xml) {
254     this.loadXML(xml);
255     this.undoStack = [];
256     this.redoStack = [];
257     this._transactionStack = [];
258     this._transformationLevel = 0;
259     
260     this._nodeMethods = {};
261     this._textNodeMethods = {};
262     this._elementNodeMethods = {};
263     this._nodeTransformations = {};
264     this._textNodeTransformations = {};
265     this._elementNodeTransformations = {};
266     
267     this.registerExtension(coreTransformations);
268 };
269
270 $.extend(Document.prototype, Backbone.Events, {
271     ElementNodeFactory: ElementNode,
272     TextNodeFactory: TextNode,
273
274     createDocumentNode: function(from) {
275         if(!(from instanceof Node)) {
276             if(typeof from === 'string') {
277                 from = parseXML(from);
278                 this.normalizeXML(from);
279             } else {
280                 if(from.text !== undefined) {
281                     /* globals document */
282                     from = document.createTextNode(from.text);
283                 } else {
284                     if(!from.tagName) {
285                         throw new Error('tagName missing');
286                     }
287                     var node = $('<' + from.tagName + '>');
288
289                     _.keys(from.attrs || {}).forEach(function(key) {
290                         node.attr(key, from.attrs[key]);
291                     });
292
293                     from = node[0];
294                 }
295             }
296         }
297         var Factory, typeMethods, typeTransformations;
298         if(from.nodeType === Node.TEXT_NODE) {
299             Factory = this.TextNodeFactory;
300             typeMethods = this._textNodeMethods;
301             typeTransformations = this._textNodeTransformations;
302         } else if(from.nodeType === Node.ELEMENT_NODE) {
303             Factory = this.ElementNodeFactory;
304             typeMethods = this._elementNodeMethods;
305             typeTransformations = this._elementNodeTransformations;
306         }
307         var toret = new Factory(from, this);
308         _.extend(toret, this._nodeMethods);
309         _.extend(toret, typeMethods);
310         
311         _.extend(toret, this._nodeTransformations);
312         _.extend(toret, typeTransformations);
313         
314         toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
315         _.keys(toret.__super__).forEach(function(key) {
316             toret.__super__[key] = _.bind(toret.__super__[key], toret);
317         });
318
319         return toret;
320     },
321
322     loadXML: function(xml, options) {
323         options = options || {};
324         this._defineDocumentProperties($(parseXML(xml)));
325         this.normalizeXML(this.dom);
326         if(!options.silent) {
327             this.trigger('contentSet');
328         }
329     },
330
331     normalizeXML: function(nativeNode) {
332         void(nativeNode); // noop
333     },
334
335     toXML: function() {
336         return this.root.toXML();
337     },
338
339     containsNode: function(node) {
340         return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
341     },
342
343     getSiblingParents: function(params) {
344         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
345             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
346             noSiblingParents = null;
347
348         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
349             return noSiblingParents;
350         }
351
352         var i;
353         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
354             if(parents1[i].sameNode(parents2[i])) {
355                 continue;
356             }
357             break;
358         }
359         return {node1: parents1[i], node2: parents2[i]};
360     },
361
362     trigger: function() {
363         Backbone.Events.trigger.apply(this, arguments);
364     },
365
366     getNodeInsertion: function(node) {
367         var insertion = {};
368         if(node instanceof DocumentNode) {
369             insertion.ofNode = node;
370             insertion.insertsNew = !this.containsNode(node);
371         } else {
372           insertion.ofNode = this.createDocumentNode(node);
373           insertion.insertsNew = true;
374         }
375         return insertion;
376     },
377
378     registerMethod: function(methodName, method, dstName) {
379         var doc = this;
380         var destination = {
381             document: doc,
382             documentNode: doc._nodeMethods,
383             textNode: doc._textNodeMethods,
384             elementNode: doc._elementNodeMethods
385         }[dstName];
386         registerMethod(methodName, method, destination);
387     },
388
389     registerTransformation: function(desc, name, dstName) {
390         var doc = this;
391         var destination = {
392             document: doc,
393             documentNode: doc._nodeTransformations,
394             textNode: doc._textNodeTransformations,
395             elementNode: doc._elementNodeTransformations
396         }[dstName];
397         registerTransformation(desc, name, destination);
398     },
399
400     registerExtension: function(extension) {
401         var doc = this;
402
403         ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
404             var dstExtension = extension[dstName];
405             if(dstExtension) {
406                 if(dstExtension.methods) {
407                     _.pairs(dstExtension.methods).forEach(function(pair) {
408                         var methodName = pair[0],
409                             method = pair[1];
410
411                         doc.registerMethod(methodName, method, dstName);
412
413                     });
414                 }
415
416                 if(dstExtension.transformations) {
417                     _.pairs(dstExtension.transformations).forEach(function(pair) {
418                         var name = pair[0],
419                             desc = pair[1];
420                         doc.registerTransformation(desc, name, dstName);
421                     });
422                 }
423             }
424         });
425     },
426
427     transform: function(Transformation, args) {
428         var toret, transformation;
429
430         if(typeof Transformation === 'function') {
431             transformation = new Transformation(this, this, args);
432         } else {
433             transformation = Transformation;
434         }
435         if(transformation) {
436             this._transformationLevel++;
437             toret = transformation.run({beUndoable:this._transformationLevel === 1});
438             if(this._transformationLevel === 1 && !this._undoInProgress) {
439                 if(this._transactionInProgress) {
440                     this._transactionStack.push(transformation);
441                 } else {
442                     this.undoStack.push(transformation);
443                 }
444             }
445             if(!this._undoInProgress && this._transformationLevel === 1) {
446                 this.redoStack = [];
447             }
448             this._transformationLevel--;
449             return toret;
450         } else {
451             throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
452         }
453     },
454     undo: function() {
455         var transformationObject = this.undoStack.pop(),
456             doc = this,
457             transformations, stopAt;
458
459         if(transformationObject) {
460             this._undoInProgress = true;
461
462             if(_.isArray(transformationObject)) {
463                 // We will modify this array in a minute so make sure we work on a copy.
464                 transformations = transformationObject.slice(0);
465             } else {
466                 // Lets normalize single transformation to a transaction containing one transformation.
467                 transformations = [transformationObject];
468             }
469
470             if(transformations.length > 1) {
471                 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
472                 stopAt = undefined;
473                 transformations.some(function(t, idx) {
474                     if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
475                         stopAt = idx;
476                         return true; //break
477                     }
478                 });
479                 if(stopAt !== undefined) {
480                     // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
481                     transformations = transformations.slice(0, stopAt+1);
482                 }
483             }
484
485             transformations.reverse();
486             transformations.forEach(function(t) {
487                 t.undo();
488             });
489
490             this._undoInProgress = false;
491             this.redoStack.push(transformationObject);
492         }
493     },
494     redo: function() {
495         var transformationObject = this.redoStack.pop(),
496             transformations;
497         if(transformationObject) {
498             this._transformationLevel++;
499             transformations = _.isArray(transformationObject) ? transformationObject : [transformationObject];
500             transformations.forEach(function(t) {
501                 t.run({beUndoable: true});
502             });
503             this._transformationLevel--;
504             this.undoStack.push(transformationObject);
505         }
506     },
507
508     startTransaction: function() {
509         if(this._transactionInProgress) {
510             throw new Error('Nested transactions not supported!');
511         }
512         this._transactionInProgress = true;
513     },
514
515     endTransaction: function() {
516         if(!this._transactionInProgress) {
517             throw new Error('End of transaction requested, but there is no transaction in progress!');
518         }
519         this._transactionInProgress = false;
520         if(this._transactionStack.length) {
521             this.undoStack.push(this._transactionStack);
522             this._transactionStack = [];
523         }
524     },
525
526     getNodeByPath: function(path) {
527         var toret = this.root;
528         path.forEach(function(idx) {
529             toret = toret.contents()[idx];
530         });
531         return toret;
532     },
533
534     _defineDocumentProperties: function($document) {
535         var doc = this;
536         Object.defineProperty(doc, 'root', {get: function() {
537             return doc.createDocumentNode($document[0]);
538         }, configurable: true});
539         Object.defineProperty(doc, 'dom', {get: function() {
540             return $document[0];
541         }, configurable: true});
542     }
543 });
544
545
546 return {
547     documentFromXML: function(xml) {
548         var doc = new Document(xml);
549         return doc;
550     },
551
552     elementNodeFromXML: function(xml) {
553         return this.documentFromXML(xml).root;
554     },
555
556     Document: Document,
557     DocumentNode: DocumentNode,
558     ElementNode: ElementNode,
559     TextNode: TextNode
560 };
561
562 });