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