allow text/element node methods and transformations to access node and transormations...
[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 var TEXT_NODE = Node.TEXT_NODE;
14
15
16
17 var DocumentNode = function(nativeNode, document) {
18     if(!document) {
19         throw new Error('undefined document for a node');
20     }
21     this.document = document;
22     this._setNativeNode(nativeNode);
23
24 };
25
26 $.extend(DocumentNode.prototype, {
27
28     transform: function(Transformation, args) {
29         var transformation = new Transformation(this.document, this, args);
30         return this.document.transform(transformation);
31     },
32
33     _setNativeNode: function(nativeNode) {
34         this.nativeNode = nativeNode;
35         this._$ = $(nativeNode);
36     },
37
38     clone: function() {
39         var clone = this._$.clone(true, true);
40         // clone.find('*').addBack().each(function() {
41         //     var n = $(this);
42         //     if(n.data('canvasElement')) {
43         //         n.data('canvasElement', $.extend(true, {}, n.data('canvasElement')));
44         //         n.data('canvasElement').$element = n.data('canvasElement').$element.clone(true, true);
45         //     }
46         // });
47         return this.document.createDocumentNode(clone[0]);
48     },
49
50     getPath: function(ancestor) {
51         var nodePath = [this].concat(this.parents()),
52             toret, idx;
53         ancestor = ancestor || this.document.root;
54
55         nodePath.some(function(node, i) {
56             if(node.sameNode(ancestor)) {
57                 idx = i;
58                 return true;
59             }
60         });
61
62         if(idx !== 'undefined') {
63             nodePath = nodePath.slice(0, idx);
64         }
65         toret = nodePath.map(function(node) {return node.getIndex(); });
66         toret.reverse();
67         return toret;
68     },
69
70     isRoot: function() {
71         return this.document.root.sameNode(this);
72     },
73
74     sameNode: function(otherNode) {
75         return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
76     },
77
78     parent: function() {
79         var parentNode = this.nativeNode.parentNode;
80         if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
81             return this.document.createDocumentNode(parentNode);
82         }
83         return null;
84     },
85
86     parents: function() {
87         var parent = this.parent(),
88             parents = parent ? parent.parents() : [];
89         if(parent) {
90             parents.unshift(parent);
91         }
92         return parents;
93     },
94
95     prev: function() {
96         var myIdx = this.getIndex();
97         return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
98     },
99
100     next: function() {
101         if(this.isRoot()) {
102             return null;
103         }
104         var myIdx = this.getIndex(),
105             parentContents = this.parent().contents();
106         return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
107     },
108
109     isSurroundedByTextElements: function() {
110         var prev = this.prev(),
111             next = this.next();
112         return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
113     },
114
115     triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
116         var node = (metaData && metaData.node) ? metaData.node : this,
117             event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
118         if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
119             this.document.trigger('change', event);
120         }
121         if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
122              event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
123              this.document.trigger('change', event);
124         }
125     },
126     
127     getNodeInsertion: function(node) {
128         return this.document.getNodeInsertion(node);
129     },
130
131     getIndex: function() {
132         if(this.isRoot()) {
133             return 0;
134         }
135         return this.parent().indexOf(this);
136     }
137 });
138
139
140 var ElementNode = function(nativeNode, document) {
141     DocumentNode.call(this, nativeNode, document);
142 };
143 ElementNode.prototype = Object.create(DocumentNode.prototype);
144
145 $.extend(ElementNode.prototype, {
146     nodeType: Node.ELEMENT_NODE,
147
148     setData: function(key, value) {
149         if(value !== undefined) {
150             this._$.data(key, value);
151         } else {
152             this._$.removeData(_.keys(this._$.data()));
153             this._$.data(key);
154         }
155     },
156
157     getData: function(key) {
158         if(key) {
159             return this._$.data(key);
160         }
161         return this._$.data();
162     },
163
164     getTagName: function() {
165         return this.nativeNode.tagName.toLowerCase();
166     },
167
168     contents: function(selector) {
169         var toret = [],
170             document = this.document;
171         if(selector) {
172             this._$.children(selector).each(function() {
173                 toret.push(document.createDocumentNode(this));
174             });
175         } else {
176             this._$.contents().each(function() {
177                 toret.push(document.createDocumentNode(this));
178             });
179         }
180         return toret;
181     },
182
183     indexOf: function(node) {
184         return this._$.contents().index(node._$);
185     },
186
187     getAttr: function(name) {
188         return this._$.attr(name);
189     },
190
191     getAttrs: function() {
192         var toret = [];
193         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
194             toret.push(this.nativeNode.attributes[i]);
195         }
196         return toret;
197     },
198
199     toXML: function() {
200         var wrapper = $('<div>');
201         wrapper.append(this._getXMLDOMToDump());
202         return wrapper.html();
203     },
204     
205     _getXMLDOMToDump: function() {
206         return this._$;
207     }
208 });
209
210
211 var TextNode = function(nativeNode, document) {
212     DocumentNode.call(this, nativeNode, document);
213 };
214 TextNode.prototype = Object.create(DocumentNode.prototype);
215
216 $.extend(TextNode.prototype, {
217     nodeType: Node.TEXT_NODE,
218
219     getText: function() {
220         return this.nativeNode.data;
221     },
222
223     triggerTextChangeEvent: function() {
224         var event = new events.ChangeEvent('nodeTextChange', {node: this});
225         this.document.trigger('change', event);
226     }
227 });
228
229
230 var parseXML = function(xml) {
231     return $($.trim(xml))[0];
232 };
233
234 var registerTransformation = function(desc, name, target) {
235     var Transformation = transformations.createContextTransformation(desc, name);
236     //+ to sie powinna nazywac registerTransformationFromDesc or sth
237     //+ ew. spr czy nie override (tylko jesli powyzej sa prototypy to trudno do nich dojsc)
238     target[name] = function() {
239         var instance = this,
240             args = Array.prototype.slice.call(arguments, 0);
241         return instance.transform(Transformation, args);
242     }
243 };
244
245 var registerMethod = function(methodName, method, target) {
246     if(target[methodName]) {
247         throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
248             .replace('{target}', target)
249             .replace('{methodName}', methodName)
250         );
251     }
252     target[methodName] = method;
253 };
254
255
256 var Document = function(xml) {
257     this.loadXML(xml);
258     this.undoStack = [];
259     this.redoStack = [];
260     this._transformationLevel = 0;
261     
262     this._nodeMethods = {};
263     this._textNodeMethods = {};
264     this._elementNodeMethods = {};
265     this._nodeTransformations = {};
266     this._textNodeTransformations = {};
267     this._elementNodeTransformations = {};
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(from.text !== undefined) {
277                 /* globals document */
278                 from = document.createTextNode(from.text);
279             } else {
280                 var node = $('<' + from.tagName + '>');
281
282                 _.keys(from.attrs || {}).forEach(function(key) {
283                     node.attr(key, from.attrs[key]);
284                 });
285
286                 from = node[0];
287             }
288         }
289         var Factory, typeMethods, typeTransformations;
290         if(from.nodeType === Node.TEXT_NODE) {
291             Factory = this.TextNodeFactory;
292             typeMethods = this._textNodeMethods;
293             typeTransformations = this._textNodeTransformations;
294         } else if(from.nodeType === Node.ELEMENT_NODE) {
295             Factory = this.ElementNodeFactory;
296             typeMethods = this._elementNodeMethods;
297             typeTransformations = this._elementNodeTransformations;
298         }
299         var toret = new Factory(from, this);
300         _.extend(toret, this._nodeMethods);
301         _.extend(toret, typeMethods);
302         
303         _.extend(toret, this._nodeTransformations);
304         _.extend(toret, typeTransformations);
305         
306         toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
307         _.keys(toret.__super__).forEach(function(key) {
308             toret.__super__[key] = _.bind(toret.__super__[key], toret);
309         });
310
311         return toret;
312     },
313
314     loadXML: function(xml, options) {
315         options = options || {};
316         this._defineDocumentProperties($(parseXML(xml)));
317         if(!options.silent) {
318             this.trigger('contentSet');
319         }
320     },
321
322     toXML: function() {
323         return this.root.toXML();
324     },
325
326     containsNode: function(node) {
327         return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
328     },
329
330     getSiblingParents: function(params) {
331         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
332             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
333             noSiblingParents = null;
334
335         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
336             return noSiblingParents;
337         }
338
339         var i;
340         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
341             if(parents1[i].sameNode(parents2[i])) {
342                 continue;
343             }
344             break;
345         }
346         return {node1: parents1[i], node2: parents2[i]};
347     },
348
349     trigger: function() {
350         //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
351         Backbone.Events.trigger.apply(this, arguments);
352     },
353
354     getNodeInsertion: function(node) {
355         var insertion = {};
356         if(node instanceof DocumentNode) {
357             insertion.ofNode = node;
358             insertion.insertsNew = !this.containsNode(node);
359         } else {
360           insertion.ofNode = this.createDocumentNode(node);
361           insertion.insertsNew = true;
362         }
363         return insertion;
364     },
365
366     registerMethod: function(methodName, method, dstName) {
367         var doc = this;
368         var destination = {
369             document: doc,
370             documentNode: doc._nodeMethods,
371             textNode: doc._textNodeMethods,
372             elementNode: doc._elementNodeMethods
373         }[dstName];
374         registerMethod(methodName, method, destination);
375     },
376
377     registerTransformation: function(desc, name, dstName) {
378         var doc = this;
379         var destination = {
380             document: doc,
381             documentNode: doc._nodeTransformations,
382             textNode: doc._textNodeTransformations,
383             elementNode: doc._elementNodeTransformations
384         }[dstName];
385         registerTransformation(desc, name, destination);
386     },
387
388     registerExtension: function(extension) {
389         //debugger;
390         var doc = this,
391             existingPropertyNames = _.values(this);
392
393         ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
394             var dstExtension = extension[dstName];
395             if(dstExtension) {
396                 if(dstExtension.methods) {
397                     _.pairs(dstExtension.methods).forEach(function(pair) {
398                         var methodName = pair[0],
399                             method = pair[1];
400
401                         doc.registerMethod(methodName, method, dstName);
402
403                     });
404                 }
405
406                 if(dstExtension.transformations) {
407                     _.pairs(dstExtension.transformations).forEach(function(pair) {
408                         var name = pair[0],
409                             desc = pair[1];
410                         doc.registerTransformation(desc, name, dstName);
411                     });
412                 }
413             }
414         });
415     },
416
417     transform: function(Transformation, args) {
418         //console.log('transform');
419         var toret, transformation;
420
421         // ref: odrebnie przygotowanie transformacji, odrebnie jej wykonanie (to pierwsze to analog transform z node)
422
423         if(typeof Transformation === 'function') {
424             transformation = new Transformation(this, this, args);
425         } else {
426             transformation = Transformation;
427         }
428         if(transformation) {
429             this._transformationLevel++;
430             toret = transformation.run();
431             if(this._transformationLevel === 1) {
432                 this.undoStack.push(transformation);
433             }
434             this._transformationLevel--;
435             //console.log('clearing redo stack');
436             this.redoStack = [];
437             return toret;
438         } else {
439             throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
440         }
441     },
442     undo: function() {
443         var transformation = this.undoStack.pop();
444         if(transformation) {
445             transformation.undo();
446             this.redoStack.push(transformation);
447         }
448     },
449     redo: function() {
450         var transformation = this.redoStack.pop();
451         if(transformation) {
452             transformation.run();
453             this.undoStack.push(transformation);
454         }
455     },
456
457     getNodeByPath: function(path) {
458         var toret = this.root;
459         path.forEach(function(idx) {
460             toret = toret.contents()[idx];
461         });
462         return toret;
463     },
464
465     _defineDocumentProperties: function($document) {
466         var doc = this;
467         Object.defineProperty(doc, 'root', {get: function() {
468             return doc.createDocumentNode($document[0]);
469         }, configurable: true});
470         Object.defineProperty(doc, 'dom', {get: function() {
471             return $document[0];
472         }, configurable: true});
473     }
474 });
475
476
477 return {
478     documentFromXML: function(xml) {
479         var doc = new Document(xml);
480         doc.registerExtension(coreTransformations);
481         return doc;
482     },
483
484     elementNodeFromXML: function(xml) {
485         return this.documentFromXML(xml).root;
486     },
487
488     Document: Document,
489     DocumentNode: DocumentNode,
490     ElementNode: ElementNode,
491     TextNode: TextNode
492 };
493
494 });