editor: fixing nodeMoved event handling in Canvas
[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             if(type === 'nodeMoved') {
127                 event.meta.parent = origParent;
128             }
129             this.document.trigger('change', event);
130         }
131         if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
132              event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
133              this.document.trigger('change', event);
134         }
135     },
136     
137     getNodeInsertion: function(node) {
138         return this.document.getNodeInsertion(node);
139     },
140
141     getIndex: function() {
142         if(this.isRoot()) {
143             return 0;
144         }
145         return this.parent().indexOf(this);
146     }
147 });
148
149
150 var ElementNode = function(nativeNode, document) {
151     DocumentNode.call(this, nativeNode, document);
152 };
153 ElementNode.prototype = Object.create(DocumentNode.prototype);
154
155 $.extend(ElementNode.prototype, {
156     nodeType: Node.ELEMENT_NODE,
157
158     setData: function(key, value) {
159         if(value !== undefined) {
160             this._$.data(key, value);
161         } else {
162             this._$.removeData(_.keys(this._$.data()));
163             this._$.data(key);
164         }
165     },
166
167     getData: function(key) {
168         if(key) {
169             return this._$.data(key);
170         }
171         return this._$.data();
172     },
173
174     getTagName: function() {
175         return this.nativeNode.tagName.toLowerCase();
176     },
177
178     contents: function(selector) {
179         var toret = [],
180             document = this.document;
181         if(selector) {
182             this._$.children(selector).each(function() {
183                 toret.push(document.createDocumentNode(this));
184             });
185         } else {
186             this._$.contents().each(function() {
187                 toret.push(document.createDocumentNode(this));
188             });
189         }
190         return toret;
191     },
192
193     indexOf: function(node) {
194         return this._$.contents().index(node._$);
195     },
196
197     getAttr: function(name) {
198         return this._$.attr(name);
199     },
200
201     getAttrs: function() {
202         var toret = [];
203         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
204             toret.push(this.nativeNode.attributes[i]);
205         }
206         return toret;
207     },
208
209     containsNode: function(node) {
210         return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
211     },
212
213     toXML: function() {
214         var wrapper = $('<div>');
215         wrapper.append(this._getXMLDOMToDump());
216         return wrapper.html();
217     },
218     
219     _getXMLDOMToDump: function() {
220         return this._$;
221     }
222 });
223
224
225 var TextNode = function(nativeNode, document) {
226     DocumentNode.call(this, nativeNode, document);
227 };
228 TextNode.prototype = Object.create(DocumentNode.prototype);
229
230 $.extend(TextNode.prototype, {
231     nodeType: Node.TEXT_NODE,
232
233     getText: function() {
234         return this.nativeNode.data;
235     },
236
237     triggerTextChangeEvent: function() {
238         var event = new events.ChangeEvent('nodeTextChange', {node: this});
239         this.document.trigger('change', event);
240     }
241 });
242
243
244 var parseXML = function(xml) {
245     var toret = $($.trim(xml));
246     if(!toret.length) {
247         throw new Error('Unable to parse XML: ' + xml);
248     }
249     return toret[0];
250
251 };
252
253 var registerTransformation = function(desc, name, target) {
254     var Transformation = transformations.createContextTransformation(desc, name);
255     target[name] = function() {
256         var instance = this,
257             args = Array.prototype.slice.call(arguments, 0);
258         return instance.transform(Transformation, args);
259     };
260 };
261
262 var registerMethod = function(methodName, method, target) {
263     if(target[methodName]) {
264         throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
265             .replace('{target}', target)
266             .replace('{methodName}', methodName)
267         );
268     }
269     target[methodName] = method;
270 };
271
272
273 var Document = function(xml, extensions) {
274     this.undoStack = [];
275     this.redoStack = [];
276     this._transactionStack = [];
277     this._transformationLevel = 0;
278     
279     this._nodeMethods = {};
280     this._textNodeMethods = {};
281     this._elementNodeMethods = {};
282     this._nodeTransformations = {};
283     this._textNodeTransformations = {};
284     this._elementNodeTransformations = {};
285     
286     this.registerExtension(coreTransformations);
287
288     (extensions || []).forEach(function(extension) {
289         this.registerExtension(extension);
290     }.bind(this));
291     this.loadXML(xml);
292 };
293
294 $.extend(Document.prototype, Backbone.Events, {
295     ElementNodeFactory: ElementNode,
296     TextNodeFactory: TextNode,
297
298     createDocumentNode: function(from) {
299         if(!(from instanceof Node)) {
300             if(typeof from === 'string') {
301                 from = parseXML(from);
302                 this.normalizeXML(from);
303             } else {
304                 if(from.text !== undefined) {
305                     /* globals document */
306                     from = document.createTextNode(from.text);
307                 } else {
308                     if(!from.tagName) {
309                         throw new Error('tagName missing');
310                     }
311                     var node = $('<' + from.tagName + '>');
312
313                     _.keys(from.attrs || {}).forEach(function(key) {
314                         node.attr(key, from.attrs[key]);
315                     });
316
317                     from = node[0];
318                 }
319             }
320         }
321         var Factory, typeMethods, typeTransformations;
322         if(from.nodeType === Node.TEXT_NODE) {
323             Factory = this.TextNodeFactory;
324             typeMethods = this._textNodeMethods;
325             typeTransformations = this._textNodeTransformations;
326         } else if(from.nodeType === Node.ELEMENT_NODE) {
327             Factory = this.ElementNodeFactory;
328             typeMethods = this._elementNodeMethods;
329             typeTransformations = this._elementNodeTransformations;
330         }
331         var toret = new Factory(from, this);
332         _.extend(toret, this._nodeMethods);
333         _.extend(toret, typeMethods);
334         
335         _.extend(toret, this._nodeTransformations);
336         _.extend(toret, typeTransformations);
337         
338         toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
339         _.keys(toret.__super__).forEach(function(key) {
340             toret.__super__[key] = _.bind(toret.__super__[key], toret);
341         });
342
343         return toret;
344     },
345
346     loadXML: function(xml, options) {
347         options = options || {};
348         this._defineDocumentProperties($(parseXML(xml)));
349         this.normalizeXML(this.dom);
350         if(!options.silent) {
351             this.trigger('contentSet');
352         }
353     },
354
355     normalizeXML: function(nativeNode) {
356         void(nativeNode); // noop
357     },
358
359     toXML: function() {
360         return this.root.toXML();
361     },
362
363     containsNode: function(node) {
364         return this.root && this.root.containsNode(node);
365     },
366
367     getSiblingParents: function(params) {
368         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
369             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
370             noSiblingParents = null;
371
372         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
373             return noSiblingParents;
374         }
375
376         var i;
377         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
378             if(parents1[i].sameNode(parents2[i])) {
379                 continue;
380             }
381             break;
382         }
383         return {node1: parents1[i], node2: parents2[i]};
384     },
385
386     trigger: function() {
387         Backbone.Events.trigger.apply(this, arguments);
388     },
389
390     getNodeInsertion: function(node) {
391         var insertion = {};
392         if(node instanceof DocumentNode) {
393             insertion.ofNode = node;
394             insertion.insertsNew = !this.containsNode(node);
395         } else {
396           insertion.ofNode = this.createDocumentNode(node);
397           insertion.insertsNew = true;
398         }
399         return insertion;
400     },
401
402     registerMethod: function(methodName, method, dstName) {
403         var doc = this;
404         var destination = {
405             document: doc,
406             documentNode: doc._nodeMethods,
407             textNode: doc._textNodeMethods,
408             elementNode: doc._elementNodeMethods
409         }[dstName];
410         registerMethod(methodName, method, destination);
411     },
412
413     registerTransformation: function(desc, name, dstName) {
414         var doc = this;
415         var destination = {
416             document: doc,
417             documentNode: doc._nodeTransformations,
418             textNode: doc._textNodeTransformations,
419             elementNode: doc._elementNodeTransformations
420         }[dstName];
421         registerTransformation(desc, name, destination);
422     },
423
424     registerExtension: function(extension) {
425         var doc = this;
426
427         ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
428             var dstExtension = extension[dstName];
429             if(dstExtension) {
430                 if(dstExtension.methods) {
431                     _.pairs(dstExtension.methods).forEach(function(pair) {
432                         var methodName = pair[0],
433                             method = pair[1];
434
435                         doc.registerMethod(methodName, method, dstName);
436
437                     });
438                 }
439
440                 if(dstExtension.transformations) {
441                     _.pairs(dstExtension.transformations).forEach(function(pair) {
442                         var name = pair[0],
443                             desc = pair[1];
444                         doc.registerTransformation(desc, name, dstName);
445                     });
446                 }
447             }
448         });
449     },
450
451     ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
452         var hasChanged = false,
453             changeMonitor = function() {
454                 hasChanged = true;
455             };
456
457         this.on('change', changeMonitor);
458         action.call(context);
459         this.off('change', changeMonitor);
460         
461         if(hasChanged) {
462             if(documentChangedHandler) {
463                 documentChangedHandler.call(context);
464             }
465         } else {
466             if(documentUnchangedHandler) {
467                 documentUnchangedHandler.call(context);
468             }
469         }
470     },
471
472     transform: function(Transformation, args) {
473         var toret, transformation;
474
475         if(typeof Transformation === 'function') {
476             transformation = new Transformation(this, this, args);
477         } else {
478             transformation = Transformation;
479         }
480         if(transformation) {
481             this._transformationLevel++;
482             
483             this.ifChanged(
484                 this,
485                 function() {
486                     toret = transformation.run({beUndoable:this._transformationLevel === 1});
487                 },
488                 function() {
489                     if(this._transformationLevel === 1 && !this._undoInProgress) {
490                         if(this._transactionInProgress) {
491                             this._transactionStack.push(transformation);
492                         } else {
493                             this.undoStack.push(transformation);
494                         }
495                     }
496                     if(!this._undoInProgress && this._transformationLevel === 1) {
497                         this.redoStack = [];
498                     }
499                 }
500             );
501
502             this._transformationLevel--;
503             return toret;
504         } else {
505             throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
506         }
507     },
508     undo: function() {
509         var transformationObject = this.undoStack.pop(),
510             doc = this,
511             transformations, stopAt;
512
513         if(transformationObject) {
514             this._undoInProgress = true;
515
516             if(_.isArray(transformationObject)) {
517                 // We will modify this array in a minute so make sure we work on a copy.
518                 transformations = transformationObject.slice(0);
519             } else {
520                 // Lets normalize single transformation to a transaction containing one transformation.
521                 transformations = [transformationObject];
522             }
523
524             if(transformations.length > 1) {
525                 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
526                 stopAt = undefined;
527                 transformations.some(function(t, idx) {
528                     if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
529                         stopAt = idx;
530                         return true; //break
531                     }
532                 });
533                 if(stopAt !== undefined) {
534                     // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
535                     transformations = transformations.slice(0, stopAt+1);
536                 }
537             }
538
539             transformations.reverse();
540             transformations.forEach(function(t) {
541                 t.undo();
542             });
543
544             this._undoInProgress = false;
545             this.redoStack.push(transformationObject);
546         }
547     },
548     redo: function() {
549         var transformationObject = this.redoStack.pop(),
550             transformations;
551         if(transformationObject) {
552             this._transformationLevel++;
553             transformations = _.isArray(transformationObject) ? transformationObject : [transformationObject];
554             transformations.forEach(function(t) {
555                 t.run({beUndoable: true});
556             });
557             this._transformationLevel--;
558             this.undoStack.push(transformationObject);
559         }
560     },
561
562     startTransaction: function() {
563         if(this._transactionInProgress) {
564             throw new Error('Nested transactions not supported!');
565         }
566         this._transactionInProgress = true;
567     },
568
569     endTransaction: function() {
570         if(!this._transactionInProgress) {
571             throw new Error('End of transaction requested, but there is no transaction in progress!');
572         }
573         this._transactionInProgress = false;
574         if(this._transactionStack.length) {
575             this.undoStack.push(this._transactionStack);
576             this._transactionStack = [];
577         }
578     },
579
580     transaction: function(callback, context) {
581         this.startTransaction();
582         callback.call(context);
583         this.endTransaction();
584     },
585
586     getNodeByPath: function(path) {
587         var toret = this.root;
588         path.forEach(function(idx) {
589             toret = toret.contents()[idx];
590         });
591         return toret;
592     },
593
594     _defineDocumentProperties: function($document) {
595         var doc = this;
596         Object.defineProperty(doc, 'root', {get: function() {
597             return doc.createDocumentNode($document[0]);
598         }, configurable: true});
599         Object.defineProperty(doc, 'dom', {get: function() {
600             return $document[0];
601         }, configurable: true});
602     }
603 });
604
605
606 return {
607     documentFromXML: function(xml) {
608         var doc = new Document(xml);
609         return doc;
610     },
611
612     elementNodeFromXML: function(xml) {
613         return this.documentFromXML(xml).root;
614     },
615
616     Document: Document,
617     DocumentNode: DocumentNode,
618     ElementNode: ElementNode,
619     TextNode: TextNode
620 };
621
622 });