splitting blocks from spans
[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     'smartxml/fragments'
9 ], function($, _, Backbone, events, transformations, coreTransformations, fragments) {
10     
11 'use strict';
12 /* globals Node */
13
14
15 var privateKey = '_smartxml';
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.object = {};
23     this._setNativeNode(nativeNode);
24
25 };
26
27 $.extend(DocumentNode.prototype, {
28
29     getProperty: function(propName) {
30         var toret = this.object[propName];
31         if(toret && _.isFunction(toret)) {
32             toret = toret.call(this);
33         }
34         return toret;
35     },
36
37     transform: function(Transformation, args) {
38         var transformation = new Transformation(this.document, this, args);
39         return this.document.transform(transformation);
40     },
41
42     _setNativeNode: function(nativeNode) {
43         this.nativeNode = nativeNode;
44         this._$ = $(nativeNode);
45     },
46
47     clone: function() {
48         var clone = this._$.clone(true, true),
49             node = this;
50         clone.find('*').addBack().each(function() {
51             var el = this,
52                 clonedData = $(this).data();
53             $(el).removeData(privateKey);
54             _.pairs(clonedData).forEach(function(pair) {
55                 var key = pair[0],
56                     value = pair[1];
57                 if(_.isFunction(value.clone)) {
58                     clonedData[key] = value.clone(node.document.createDocumentNode(el));
59                 }
60             });
61         });
62         return this.document.createDocumentNode(clone[0]);
63     },
64
65     getPath: function(ancestor) {
66         if(!(this.document.containsNode(this))) {
67             return null;
68         }
69
70         var nodePath = [this].concat(this.parents()),
71             toret, idx;
72         ancestor = ancestor || this.document.root;
73
74         nodePath.some(function(node, i) {
75             if(node.sameNode(ancestor)) {
76                 idx = i;
77                 return true;
78             }
79         });
80
81         if(idx !== undefined) {
82             nodePath = nodePath.slice(0, idx);
83         }
84         toret = nodePath.map(function(node) {return node.getIndex(); });
85         toret.reverse();
86         return toret;
87     },
88
89     isRoot: function() {
90         return this.document.root.sameNode(this);
91     },
92
93     isInDocument: function() {
94         return this.document.containsNode(this);
95     },
96
97     isSiblingOf: function(node) {
98         return node && this.parent().sameNode(node.parent());
99     },
100
101     sameNode: function(otherNode) {
102         return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
103     },
104
105     parent: function() {
106         var parentNode = this.nativeNode.parentNode;
107         if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
108             return this.document.createDocumentNode(parentNode);
109         }
110         return null;
111     },
112
113     parents: function() {
114         var parent = this.parent(),
115             parents = parent ? parent.parents() : [];
116         if(parent) {
117             parents.unshift(parent);
118         }
119         return parents;
120     },
121
122     prev: function() {
123         var myIdx = this.getIndex();
124         return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
125     },
126
127     next: function() {
128         if(this.isRoot()) {
129             return null;
130         }
131         var myIdx = this.getIndex(),
132             parentContents = this.parent().contents();
133         return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
134     },
135
136     isSurroundedByTextNodes: function() {
137         return this.isPrecededByTextNode() && this.isFollowedByTextNode();
138     },
139
140     isPrecededByTextNode: function() {
141         var prev = this.prev();
142         return prev && prev.nodeType === Node.TEXT_NODE;
143     },
144
145     isFollowedByTextNode: function() {
146         var next = this.next();
147         return next && next.nodeType === Node.TEXT_NODE;
148     },
149
150     triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
151         var node = (metaData && metaData.node) ? metaData.node : this,
152             event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
153         if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
154             this.document.trigger('change', event);
155         }
156         if(type === 'nodeAdded' && !this.document.containsNode(this) && nodeWasContained) {
157              event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
158              this.document.trigger('change', event);
159         }
160     },
161     
162     getNodeInsertion: function(node) {
163         return this.document.getNodeInsertion(node);
164     },
165
166     getIndex: function() {
167         var parent;
168
169         if(this.isRoot()) {
170             return 0;
171         }
172
173         parent = this.parent();
174         return parent ? parent.indexOf(this) : undefined;
175     },
176
177     getNearestElementNode: function() {
178         return this.nodeType === Node.ELEMENT_NODE ? this : this.parent();
179     }
180 });
181
182
183 var ElementNode = function(nativeNode, document) {
184     DocumentNode.call(this, nativeNode, document);
185     $(nativeNode).data(privateKey, {node: this});
186 };
187 ElementNode.prototype = Object.create(DocumentNode.prototype);
188
189 $.extend(ElementNode.prototype, {
190     nodeType: Node.ELEMENT_NODE,
191
192     setData: function(arg1, arg2) {
193         if(arguments.length === 2) {
194             if(_.isUndefined(arg2)) {
195                 this._$.removeData(arg1);
196             } else {
197                 this._$.data(arg1, arg2);
198             }
199         } else {
200             this._$.removeData(_.keys(this._$.data()));
201             this._$.data(arg1);
202         }
203     },
204
205     getData: function(key) {
206         if(key) {
207             return this._$.data(key);
208         }
209         var toret = _.clone(this._$.data());
210         delete toret[privateKey];
211         return toret;
212     },
213
214     getTagName: function() {
215         return this.nativeNode.tagName.toLowerCase();
216     },
217
218     contents: function(selector) {
219         var toret = [],
220             document = this.document;
221         if(selector) {
222             this._$.children(selector).each(function() {
223                 toret.push(document.createDocumentNode(this));
224             });
225         } else {
226             this._$.contents().each(function() {
227                 toret.push(document.createDocumentNode(this));
228             });
229         }
230         return toret;
231     },
232
233     indexOf: function(node) {
234         return this._$.contents().index(node._$);
235     },
236
237     getAttr: function(name) {
238         return this._$.attr(name);
239     },
240
241     getAttrs: function() {
242         var toret = [];
243         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
244             toret.push(this.nativeNode.attributes[i]);
245         }
246         return toret;
247     },
248
249     containsNode: function(node) {
250         return node && (node.nativeNode === this.nativeNode || node._$.parents().index(this._$) !== -1);
251     },
252
253     getLastTextNode: function() {
254         var contents = this.contents(),
255             toret;
256
257         contents.reverse().some(function(node) {
258             if(node.nodeType === Node.TEXT_NODE) {
259                 toret = node;
260                 return true;
261             }
262             toret = node.getLastTextNode();
263             return !!toret;
264         });
265
266         return toret;
267     },
268
269     toXML: function() {
270         var wrapper = $('<div>');
271         wrapper.append(this._getXMLDOMToDump());
272         return wrapper.html();
273     },
274     
275     _getXMLDOMToDump: function() {
276         return this._$;
277     }
278 });
279
280
281 var TextNode = function(nativeNode, document) {
282     DocumentNode.call(this, nativeNode, document);
283     this._data = Object.create({});
284     nativeNode.__smartxmlTextNodeInstance = this;
285 };
286 TextNode.prototype = Object.create(DocumentNode.prototype);
287
288 $.extend(TextNode.prototype, {
289     nodeType: Node.TEXT_NODE,
290
291     setData: function(arg1, arg2) {
292         if(arguments.length === 2) {
293             if(_.isUndefined(arg2)) {
294                 delete this._data[arg1];
295             } else {
296                 this._data[arg1] = arg2;
297             }
298         } else {
299             this._data = _.extend({}, arg1);
300         }
301     },
302
303     getData: function(key) {
304         if(key) {
305             return this._data[key];
306         }
307         return this._data;
308     },
309
310     getText: function() {
311         return this.nativeNode.data;
312     },
313
314
315     containsNode: function() {
316         return false;
317     },
318
319     triggerTextChangeEvent: function() {
320         var event = new events.ChangeEvent('nodeTextChange', {node: this});
321         this.document.trigger('change', event);
322     }
323 });
324
325
326 var parseXML = function(xml) {
327     var toret = $($.trim(xml));
328     if(toret.length !== 1) {
329         throw new Error('Unable to parse XML: ' + xml);
330     }
331     return toret[0];
332
333 };
334
335 var registerTransformation = function(desc, name, target) {
336     var Transformation = transformations.createContextTransformation(desc, name);
337     target[name] = function() {
338         var instance = this,
339             args = Array.prototype.slice.call(arguments, 0);
340         return instance.transform(Transformation, args);
341     };
342 };
343
344 var registerMethod = function(methodName, method, target) {
345     if(target[methodName]) {
346         throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
347             .replace('{target}', target)
348             .replace('{methodName}', methodName)
349         );
350     }
351     target[methodName] = method;
352 };
353
354
355 var Document = function(xml, extensions) {
356     this.undoStack = [];
357     this.redoStack = [];
358     this._currentTransaction = null;
359     this._transformationLevel = 0;
360     
361     this._nodeMethods = {};
362     this._textNodeMethods = {};
363     this._elementNodeMethods = {};
364     this._nodeTransformations = {};
365     this._textNodeTransformations = {};
366     this._elementNodeTransformations = {};
367     
368     this.registerExtension(coreTransformations);
369
370     (extensions || []).forEach(function(extension) {
371         this.registerExtension(extension);
372     }.bind(this));
373     this.loadXML(xml);
374 };
375
376 $.extend(Document.prototype, Backbone.Events, fragments, {
377     ElementNodeFactory: ElementNode,
378     TextNodeFactory: TextNode,
379
380     createDocumentNode: function(from) {
381         var cached;
382
383         if(from instanceof Node) {
384             /* globals Text */
385             cached = from instanceof Text ? from.__smartxmlTextNodeInstance : ($(from).data(privateKey) || {}).node;
386             if(cached instanceof DocumentNode) {
387                 return cached;
388             }
389         } else {
390             if(typeof from === 'string') {
391                 from = parseXML(from);
392                 this.normalizeXML(from);
393             } else {
394                 if(from.text !== undefined) {
395                     /* globals document */
396                     from = document.createTextNode(from.text);
397                 } else {
398                     if(!from.tagName) {
399                         throw new Error('tagName missing');
400                     }
401                     var node = $('<' + from.tagName + '>');
402
403                     _.keys(from.attrs || {}).forEach(function(key) {
404                         node.attr(key, from.attrs[key]);
405                     });
406
407                     from = node[0];
408                 }
409             }
410         }
411         var Factory, typeMethods, typeTransformations;
412         if(from.nodeType === Node.TEXT_NODE) {
413             Factory = this.TextNodeFactory;
414             typeMethods = this._textNodeMethods;
415             typeTransformations = this._textNodeTransformations;
416         } else if(from.nodeType === Node.ELEMENT_NODE) {
417             Factory = this.ElementNodeFactory;
418             typeMethods = this._elementNodeMethods;
419             typeTransformations = this._elementNodeTransformations;
420         }
421         var toret = new Factory(from, this);
422         _.extend(toret, this._nodeMethods);
423         _.extend(toret, typeMethods);
424         
425         _.extend(toret, this._nodeTransformations);
426         _.extend(toret, typeTransformations);
427         
428         toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
429         _.keys(toret.__super__).forEach(function(key) {
430             toret.__super__[key] = _.bind(toret.__super__[key], toret);
431         });
432
433         return toret;
434     },
435
436     loadXML: function(xml, options) {
437         options = options || {};
438         this._defineDocumentProperties($(parseXML(xml)));
439         this.normalizeXML(this.dom);
440         if(!options.silent) {
441             this.trigger('contentSet');
442         }
443     },
444
445     normalizeXML: function(nativeNode) {
446         void(nativeNode); // noop
447     },
448
449     toXML: function() {
450         return this.root.toXML();
451     },
452
453     containsNode: function(node) {
454         return this.root && this.root.containsNode(node);
455     },
456
457     getSiblingParents: function(params) {
458         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
459             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
460             noSiblingParents = null;
461
462         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
463             return noSiblingParents;
464         }
465
466         var stop = Math.min(parents1.length, parents2.length),
467             i;
468         for(i = 0; i < stop; i++) {
469             if(parents1[i].sameNode(parents2[i])) {
470                 continue;
471             }
472             break;
473         }
474         if(i === stop) {
475             i--;
476         }
477         return {node1: parents1[i], node2: parents2[i]};
478     },
479
480     trigger: function() {
481         Backbone.Events.trigger.apply(this, arguments);
482     },
483
484     getNodeInsertion: function(node) {
485         var insertion = {};
486         if(node instanceof DocumentNode) {
487             insertion.ofNode = node;
488             insertion.insertsNew = !this.containsNode(node);
489         } else {
490           insertion.ofNode = this.createDocumentNode(node);
491           insertion.insertsNew = true;
492         }
493         return insertion;
494     },
495
496     registerMethod: function(methodName, method, dstName) {
497         var doc = this;
498         var destination = {
499             document: doc,
500             documentNode: doc._nodeMethods,
501             textNode: doc._textNodeMethods,
502             elementNode: doc._elementNodeMethods
503         }[dstName];
504         registerMethod(methodName, method, destination);
505     },
506
507     registerTransformation: function(desc, name, dstName) {
508         var doc = this;
509         var destination = {
510             document: doc,
511             documentNode: doc._nodeTransformations,
512             textNode: doc._textNodeTransformations,
513             elementNode: doc._elementNodeTransformations
514         }[dstName];
515         registerTransformation(desc, name, destination);
516     },
517
518     registerExtension: function(extension) {
519         var doc = this;
520
521         ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
522             var dstExtension = extension[dstName];
523             if(dstExtension) {
524                 if(dstExtension.methods) {
525                     _.pairs(dstExtension.methods).forEach(function(pair) {
526                         var methodName = pair[0],
527                             method = pair[1];
528
529                         doc.registerMethod(methodName, method, dstName);
530
531                     });
532                 }
533
534                 if(dstExtension.transformations) {
535                     _.pairs(dstExtension.transformations).forEach(function(pair) {
536                         var name = pair[0],
537                             desc = pair[1];
538                         doc.registerTransformation(desc, name, dstName);
539                     });
540                 }
541             }
542         });
543     },
544
545     ifChanged: function(context, action, documentChangedHandler, documentUnchangedHandler) {
546         var hasChanged = false,
547             changeMonitor = function() {
548                 hasChanged = true;
549             };
550
551         this.on('change', changeMonitor);
552         action.call(context);
553         this.off('change', changeMonitor);
554         
555         if(hasChanged) {
556             if(documentChangedHandler) {
557                 documentChangedHandler.call(context);
558             }
559         } else {
560             if(documentUnchangedHandler) {
561                 documentUnchangedHandler.call(context);
562             }
563         }
564     },
565
566     transform: function(Transformation, args) {
567         var toret, transformation;
568
569         if(!this._currentTransaction) {
570             return this.transaction(function() {
571                 return this.transform(Transformation, args);
572             }, {context: this});
573         }
574
575         if(typeof Transformation === 'function') {
576             transformation = new Transformation(this, this, args);
577         } else {
578             transformation = Transformation;
579         }
580         if(transformation) {
581             this._transformationLevel++;
582             
583             this.ifChanged(
584                 this,
585                 function() {
586                     toret = transformation.run({beUndoable:this._transformationLevel === 1});
587                 },
588                 function() {
589                     if(this._transformationLevel === 1 && !this._undoInProgress) {
590                         this._currentTransaction.pushTransformation(transformation);
591                         this.redoStack = [];
592                     }
593                 }
594             );
595
596             this._transformationLevel--;
597             return toret;
598         } else {
599             throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
600         }
601     },
602     undo: function() {
603         var transaction = this.undoStack.pop(),
604             doc = this,
605             transformations, stopAt;
606
607         if(transaction) {
608             this._undoInProgress = true;
609
610             // We will modify this array in a minute so make sure we work on a copy.
611             transformations = transaction.transformations.slice(0);
612
613             if(transformations.length > 1) {
614                 // In case of real transactions we don't want to run undo on all of transformations if we don't have to.
615                 transformations.some(function(t, idx) {
616                     if(!t.undo && t.getChangeRoot().sameNode(doc.root)) {
617                         stopAt = idx;
618                         return true; //break
619                     }
620                 });
621                 if(stopAt !== undefined) {
622                     // We will get away with undoing only this transformations as the one at stopAt reverses the whole document.
623                     transformations = transformations.slice(0, stopAt+1);
624                 }
625             }
626
627             transformations.reverse();
628             transformations.forEach(function(t) {
629                 t.undo();
630             });
631
632             this._undoInProgress = false;
633             this.redoStack.push(transaction);
634             this.trigger('operationEnd');
635         }
636     },
637     redo: function() {
638         var transaction = this.redoStack.pop();
639         if(transaction) {
640             this._transformationLevel++;
641             transaction.transformations.forEach(function(t) {
642                 t.run({beUndoable: true});
643             });
644             this._transformationLevel--;
645             this.undoStack.push(transaction);
646             this.trigger('operationEnd');
647
648         }
649     },
650
651     startTransaction: function(metadata) {
652         if(this._currentTransaction) {
653             throw new Error('Nested transactions not supported!');
654         }
655         this._rollbackBackup = this.root.clone();
656         this._currentTransaction = new Transaction([], metadata);
657     },
658
659     endTransaction: function() {
660         if(!this._currentTransaction) {
661             throw new Error('End of transaction requested, but there is no transaction in progress!');
662         }
663         if(this._currentTransaction.hasTransformations()) {
664             this.undoStack.push(this._currentTransaction);
665             this.trigger('operationEnd');
666         }
667         this._currentTransaction = null;
668     },
669
670     rollbackTransaction: function() {
671         if(!this._currentTransaction) {
672             throw new Error('Transaction rollback requested, but there is no transaction in progress!');
673         }
674         this.replaceRoot(this._rollbackBackup);
675         this._rollbackBackup = null;
676         this._currentTransaction = null;
677         this._transformationLevel = 0;
678     },
679
680     transaction: function(callback, params) {
681         var toret;
682         params = params || {};
683         this.startTransaction(params.metadata);
684         try {
685             toret = callback.call(params.context || this);
686         } catch(e) {
687             if(params.error) {
688                 params.error(e);
689             }
690             this.rollbackTransaction();
691             return;
692         }
693         this.endTransaction();
694         if(params.success) {
695             params.success(toret);
696         }
697         return toret;
698     },
699
700     getNodeByPath: function(path) {
701         var toret = this.root;
702         path.some(function(idx) {
703             toret = toret.contents()[idx];
704             if(!toret) {
705                 return true;
706             }
707         });
708         return toret;
709     },
710
711     _defineDocumentProperties: function($document) {
712         var doc = this;
713         Object.defineProperty(doc, 'root', {get: function() {
714             if(!$document) {
715                 return null;
716             }
717             return doc.createDocumentNode($document[0]);
718         }, configurable: true});
719         Object.defineProperty(doc, 'dom', {get: function() {
720             if(!$document) {
721                 return null;
722             }
723             return $document[0];
724         }, configurable: true});
725     },
726
727     createFragment: function(Type, params) {
728         if(!Type.prototype instanceof fragments.Fragment) {
729             throw new Error('Can\'t create a fragment: `Type` is not a valid Fragment');
730         }
731         return new Type(this, params);
732     }
733 });
734
735 var Transaction = function(transformations, metadata) {
736     this.transformations = transformations || [];
737     this.metadata = metadata;
738 };
739 $.extend(Transaction.prototype, {
740     pushTransformation: function(transformation) {
741         this.transformations.push(transformation);
742     },
743     hasTransformations: function() {
744         return this.transformations.length > 0;
745     }
746 });
747
748
749 return {
750     documentFromXML: function(xml) {
751         var doc = new Document(xml);
752         return doc;
753     },
754
755     elementNodeFromXML: function(xml) {
756         return this.documentFromXML(xml).root;
757     },
758
759     Document: Document,
760     DocumentNode: DocumentNode,
761     ElementNode: ElementNode,
762     TextNode: TextNode
763 };
764
765 });