wlxml: metdata wip - empty key/value is represented as an empty string
[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     transform: function(Transformation, args) {
445         var toret, transformation;
446
447         if(typeof Transformation === 'function') {
448             transformation = new Transformation(this, this, args);
449         } else {
450             transformation = Transformation;
451         }
452         if(transformation) {
453             this._transformationLevel++;
454             toret = transformation.run({beUndoable:this._transformationLevel === 1});
455             if(this._transformationLevel === 1 && !this._undoInProgress) {
456                 if(this._transactionInProgress) {
457                     this._transactionStack.push(transformation);
458                 } else {
459                     this.undoStack.push(transformation);
460                 }
461             }
462             if(!this._undoInProgress && this._transformationLevel === 1) {
463                 this.redoStack = [];
464             }
465             this._transformationLevel--;
466             return toret;
467         } else {
468             throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
469         }
470     },
471     undo: function() {
472         var transformationObject = this.undoStack.pop(),
473             doc = this,
474             transformations, stopAt;
475
476         if(transformationObject) {
477             this._undoInProgress = true;
478
479             if(_.isArray(transformationObject)) {
480                 // We will modify this array in a minute so make sure we work on a copy.
481                 transformations = transformationObject.slice(0);
482             } else {
483                 // Lets normalize single transformation to a transaction containing one transformation.
484                 transformations = [transformationObject];
485             }
486
487             if(transformations.length > 1) {
488                 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
489                 stopAt = undefined;
490                 transformations.some(function(t, idx) {
491                     if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
492                         stopAt = idx;
493                         return true; //break
494                     }
495                 });
496                 if(stopAt !== undefined) {
497                     // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
498                     transformations = transformations.slice(0, stopAt+1);
499                 }
500             }
501
502             transformations.reverse();
503             transformations.forEach(function(t) {
504                 t.undo();
505             });
506
507             this._undoInProgress = false;
508             this.redoStack.push(transformationObject);
509         }
510     },
511     redo: function() {
512         var transformationObject = this.redoStack.pop(),
513             transformations;
514         if(transformationObject) {
515             this._transformationLevel++;
516             transformations = _.isArray(transformationObject) ? transformationObject : [transformationObject];
517             transformations.forEach(function(t) {
518                 t.run({beUndoable: true});
519             });
520             this._transformationLevel--;
521             this.undoStack.push(transformationObject);
522         }
523     },
524
525     startTransaction: function() {
526         if(this._transactionInProgress) {
527             throw new Error('Nested transactions not supported!');
528         }
529         this._transactionInProgress = true;
530     },
531
532     endTransaction: function() {
533         if(!this._transactionInProgress) {
534             throw new Error('End of transaction requested, but there is no transaction in progress!');
535         }
536         this._transactionInProgress = false;
537         if(this._transactionStack.length) {
538             this.undoStack.push(this._transactionStack);
539             this._transactionStack = [];
540         }
541     },
542
543     getNodeByPath: function(path) {
544         var toret = this.root;
545         path.forEach(function(idx) {
546             toret = toret.contents()[idx];
547         });
548         return toret;
549     },
550
551     _defineDocumentProperties: function($document) {
552         var doc = this;
553         Object.defineProperty(doc, 'root', {get: function() {
554             return doc.createDocumentNode($document[0]);
555         }, configurable: true});
556         Object.defineProperty(doc, 'dom', {get: function() {
557             return $document[0];
558         }, configurable: true});
559     }
560 });
561
562
563 return {
564     documentFromXML: function(xml) {
565         var doc = new Document(xml);
566         return doc;
567     },
568
569     elementNodeFromXML: function(xml) {
570         return this.documentFromXML(xml).root;
571     },
572
573     Document: Document,
574     DocumentNode: DocumentNode,
575     ElementNode: ElementNode,
576     TextNode: TextNode
577 };
578
579 });