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