registering textNode/elementNode transformations
[fnpeditor.git] / src / smartxml / smartxml.js
1 define([
2     'libs/jquery',
3     'libs/underscore',
4     'libs/backbone',
5     'smartxml/events',
6     'smartxml/transformations'
7 ], function($, _, Backbone, events, transformations) {
8     
9 'use strict';
10 /* globals Node */
11
12 var TEXT_NODE = Node.TEXT_NODE;
13
14
15 var INSERTION = function(implementation) {
16     var toret = function(node) {
17         var insertion = this.getNodeInsertion(node),
18             nodeWasContained = this.document.containsNode(insertion.ofNode),
19             nodeParent;
20         if(!(this.document.containsNode(this))) {
21             nodeParent = insertion.ofNode.parent();
22         }
23         implementation.call(this, insertion.ofNode.nativeNode);
24         this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode}, nodeParent, nodeWasContained);
25         return insertion.ofNode;
26     };
27     return toret;
28 };
29
30 var DocumentNode = function(nativeNode, document) {
31     if(!document) {
32         throw new Error('undefined document for a node');
33     }
34     this.document = document;
35     this._setNativeNode(nativeNode);
36
37 };
38
39 $.extend(DocumentNode.prototype, {
40
41     transform: function(Transformation, args) {
42         var transformation = new Transformation(this.document, this, args);
43         return this.document.transform(transformation);
44     },
45
46     _setNativeNode: function(nativeNode) {
47         this.nativeNode = nativeNode;
48         this._$ = $(nativeNode);
49     },
50
51     clone: function() {
52         var clone = this._$.clone(true, true);
53         // clone.find('*').addBack().each(function() {
54         //     var n = $(this);
55         //     if(n.data('canvasElement')) {
56         //         n.data('canvasElement', $.extend(true, {}, n.data('canvasElement')));
57         //         n.data('canvasElement').$element = n.data('canvasElement').$element.clone(true, true);
58         //     }
59         // });
60         return this.document.createDocumentNode(clone[0]);
61     },
62
63     getPath: function(ancestor) {
64         var nodePath = [this].concat(this.parents()),
65             toret, idx;
66         ancestor = ancestor || this.document.root;
67
68         nodePath.some(function(node, i) {
69             if(node.sameNode(ancestor)) {
70                 idx = i;
71                 return true;
72             }
73         });
74
75         if(idx !== 'undefined') {
76             nodePath = nodePath.slice(0, idx);
77         }
78         toret = nodePath.map(function(node) {return node.getIndex(); });
79         toret.reverse();
80         return toret;
81     },
82
83     isRoot: function() {
84         return this.document.root.sameNode(this);
85     },
86
87     detach: function() {
88         var parent = this.parent();
89         this._$.detach();
90         this.triggerChangeEvent('nodeDetached', {parent: parent});
91         return this;
92     },
93
94     replaceWith: function(node) {
95         var toret;
96         if(this.isRoot()) {
97             return this.document.replaceRoot(node);
98         }
99         toret = this.after(node);
100         this.detach();
101         return toret;
102     },
103
104     sameNode: function(otherNode) {
105         return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
106     },
107
108     parent: function() {
109         var parentNode = this.nativeNode.parentNode;
110         if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
111             return this.document.createDocumentNode(parentNode);
112         }
113         return null;
114     },
115
116     parents: function() {
117         var parent = this.parent(),
118             parents = parent ? parent.parents() : [];
119         if(parent) {
120             parents.unshift(parent);
121         }
122         return parents;
123     },
124
125     prev: function() {
126         var myIdx = this.getIndex();
127         return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
128     },
129
130     next: function() {
131         if(this.isRoot()) {
132             return null;
133         }
134         var myIdx = this.getIndex(),
135             parentContents = this.parent().contents();
136         return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
137     },
138
139     isSurroundedByTextElements: function() {
140         var prev = this.prev(),
141             next = this.next();
142         return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
143     },
144
145     after: INSERTION(function(nativeNode) {
146         return this._$.after(nativeNode);
147     }),
148
149     before: INSERTION(function(nativeNode) {
150         return this._$.before(nativeNode);
151     }),
152
153     wrapWith: function(node) {
154         var insertion = this.getNodeInsertion(node);
155         if(this.parent()) {
156             this.before(insertion.ofNode);
157         }
158         insertion.ofNode.append(this);
159         return insertion.ofNode;
160     },
161
162     /**
163     * Removes parent of a node if node has no siblings.
164     */
165     unwrap: function() {
166         if(this.isRoot()) {
167             return;
168         }
169         var parent = this.parent(),
170             grandParent;
171         if(parent.contents().length === 1) {
172             grandParent = parent.parent();
173             parent.unwrapContent();
174             return grandParent;
175         }
176     },
177
178     triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
179         var node = (metaData && metaData.node) ? metaData.node : this,
180             event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
181         if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
182             this.document.trigger('change', event);
183         }
184         if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
185              event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
186              this.document.trigger('change', event);
187         }
188     },
189     
190     getNodeInsertion: function(node) {
191         return this.document.getNodeInsertion(node);
192     },
193
194     getIndex: function() {
195         if(this.isRoot()) {
196             return 0;
197         }
198         return this.parent().indexOf(this);
199     }
200 });
201
202 var ElementNode = function(nativeNode, document) {
203     DocumentNode.call(this, nativeNode, document);
204 };
205 ElementNode.prototype = Object.create(DocumentNode.prototype);
206
207 $.extend(ElementNode.prototype, {
208     nodeType: Node.ELEMENT_NODE,
209
210     detach: function() {
211         var next;
212         if(this.parent() && this.isSurroundedByTextElements()) {
213             next = this.next();
214             this.prev().appendText(next.getText());
215             next.detach();
216         }
217         return DocumentNode.prototype.detach.call(this);
218     },
219
220     setData: function(key, value) {
221         if(value !== undefined) {
222             this._$.data(key, value);
223         } else {
224             this._$.removeData(_.keys(this._$.data()));
225             this._$.data(key);
226         }
227     },
228
229     getData: function(key) {
230         if(key) {
231             return this._$.data(key);
232         }
233         return this._$.data();
234     },
235
236     getTagName: function() {
237         return this.nativeNode.tagName.toLowerCase();
238     },
239
240     contents: function(selector) {
241         var toret = [],
242             document = this.document;
243         if(selector) {
244             this._$.children(selector).each(function() {
245                 toret.push(document.createDocumentNode(this));
246             });
247         } else {
248             this._$.contents().each(function() {
249                 toret.push(document.createDocumentNode(this));
250             });
251         }
252         return toret;
253     },
254
255     indexOf: function(node) {
256         return this._$.contents().index(node._$);
257     },
258
259     setTag: function(tagName) {
260         var node = this.document.createDocumentNode({tagName: tagName}),
261             oldTagName = this.getTagName(),
262             myContents = this._$.contents();
263
264         this.getAttrs().forEach(function(attribute) {
265             node.setAttr(attribute.name, attribute.value, true);
266         });
267         node.setData(this.getData());
268
269         if(this.sameNode(this.document.root)) {
270             defineDocumentProperties(this.document, node._$);
271         }
272         this._$.replaceWith(node._$);
273         this._setNativeNode(node._$[0]);
274         this._$.append(myContents);
275         this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
276     },
277
278     getAttr: function(name) {
279         return this._$.attr(name);
280     },
281
282     setAttr: function(name, value, silent) {
283         var oldVal = this.getAttr(name);
284         this._$.attr(name, value);
285         if(!silent) {
286             this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
287         }
288     },
289
290     getAttrs: function() {
291         var toret = [];
292         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
293             toret.push(this.nativeNode.attributes[i]);
294         }
295         return toret;
296     },
297
298     append: INSERTION(function(nativeNode) {
299         this._$.append(nativeNode);
300     }),
301
302     prepend: INSERTION(function(nativeNode) {
303         this._$.prepend(nativeNode);
304     }),
305
306     insertAtIndex: function(nativeNode, index) {
307         var contents = this.contents();
308         if(index < contents.length) {
309             return contents[index].before(nativeNode);
310         } else if(index === contents.length) {
311             return this.append(nativeNode);
312         }
313     },
314
315     unwrapContent: function() {
316         var parent = this.parent();
317         if(!parent) {
318             return;
319         }
320
321         var myContents = this.contents(),
322             myIdx = parent.indexOf(this);
323
324
325         if(myContents.length === 0) {
326             return this.detach();
327         }
328
329         var prev = this.prev(),
330             next = this.next(),
331             moveLeftRange, moveRightRange, leftMerged;
332
333         if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
334             prev.appendText(myContents[0].getText());
335             myContents[0].detach();
336             moveLeftRange = true;
337             leftMerged = true;
338         } else {
339             leftMerged = false;
340         }
341
342         if(!(leftMerged && myContents.length === 1)) {
343             var lastContents = _.last(myContents);
344             if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
345                 next.prependText(lastContents.getText());
346                 lastContents.detach();
347                 moveRightRange = true;
348             }
349         }
350
351         var childrenLength = this.contents().length;
352         this.contents().forEach(function(child) {
353             this.before(child);
354         }.bind(this));
355
356         this.detach();
357
358         return {
359             element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
360             element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
361         };
362     },
363
364     wrapText: function(params) {
365         return this.document._wrapText(_.extend({inside: this}, params));
366     },
367
368     toXML: function() {
369         var wrapper = $('<div>');
370         wrapper.append(this._getXMLDOMToDump());
371         return wrapper.html();
372     },
373     
374     _getXMLDOMToDump: function() {
375         return this._$;
376     }
377 });
378
379 var TextNode = function(nativeNode, document) {
380     DocumentNode.call(this, nativeNode, document);
381 };
382 TextNode.prototype = Object.create(DocumentNode.prototype);
383
384 $.extend(TextNode.prototype, {
385     nodeType: Node.TEXT_NODE,
386
387     getText: function() {
388         return this.nativeNode.data;
389     },
390
391     setText: function(text) {
392         //console.log('smartxml: ' + text);
393         this.nativeNode.data = text;
394         this.triggerTextChangeEvent();
395     },
396
397     appendText: function(text) {
398         this.nativeNode.data = this.nativeNode.data + text;
399         this.triggerTextChangeEvent();
400     },
401
402     prependText: function(text) {
403         this.nativeNode.data = text + this.nativeNode.data;
404         this.triggerTextChangeEvent();
405     },
406
407     wrapWith: function(desc) {
408         if(typeof desc.start === 'number' && typeof desc.end === 'number') {
409             return this.document._wrapText({
410                 inside: this.parent(),
411                 textNodeIdx: this.parent().indexOf(this),
412                 offsetStart: Math.min(desc.start, desc.end),
413                 offsetEnd: Math.max(desc.start, desc.end),
414                 _with: {tagName: desc.tagName, attrs: desc.attrs}
415             });
416         } else {
417             return DocumentNode.prototype.wrapWith.call(this, desc);
418         }
419     },
420
421     split: function(params) {
422         var parentElement = this.parent(),
423             passed = false,
424             succeedingChildren = [],
425             prefix = this.getText().substr(0, params.offset),
426             suffix = this.getText().substr(params.offset);
427
428         parentElement.contents().forEach(function(child) {
429             if(passed) {
430                 succeedingChildren.push(child);
431             }
432             if(child.sameNode(this)) {
433                 passed = true;
434             }
435         }.bind(this));
436
437         if(prefix.length > 0) {
438             this.setText(prefix);
439         }
440         else {
441             this.detach();
442         }
443
444         var attrs = {};
445         parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
446         var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
447         parentElement.after(newElement);
448
449         if(suffix.length > 0) {
450             newElement.append({text: suffix});
451         }
452         succeedingChildren.forEach(function(child) {
453             newElement.append(child);
454         });
455
456         return {first: parentElement, second: newElement};
457     },
458
459     triggerTextChangeEvent: function() {
460         var event = new events.ChangeEvent('nodeTextChange', {node: this});
461         this.document.trigger('change', event);
462     }
463 });
464
465
466 var parseXML = function(xml) {
467     return $($.trim(xml))[0];
468 };
469
470 var registerTransformation = function(desc, name, target) {
471     var Transformation = transformations.createContextTransformation(desc, name);
472     target[name] = function(args) {
473         var instance = this;
474         return instance.transform(Transformation, args);
475     }
476 };
477
478 var registerMethod = function(methodName, method, target) {
479     if(target[methodName]) {
480         throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
481             .replace('{target}', target)
482             .replace('{methodName}', methodName)
483         );
484     }
485     target[methodName] = method;
486 };
487
488
489 var Document = function(xml) {
490     this.loadXML(xml);
491     this.undoStack = [];
492     this.redoStack = [];
493     this._transformationLevel = 0;
494     
495     this._nodeMethods = {};
496     this._textNodeMethods = {};
497     this._elementNodeMethods = {};
498     this._nodeTransformations = {};
499     this._textNodeTransformations = {};
500     this._elementNodeTransformations = {};
501 };
502
503 $.extend(Document.prototype, Backbone.Events, {
504     ElementNodeFactory: ElementNode,
505     TextNodeFactory: TextNode,
506
507     createDocumentNode: function(from) {
508         if(!(from instanceof Node)) {
509             if(from.text !== undefined) {
510                 /* globals document */
511                 from = document.createTextNode(from.text);
512             } else {
513                 var node = $('<' + from.tagName + '>');
514
515                 _.keys(from.attrs || {}).forEach(function(key) {
516                     node.attr(key, from.attrs[key]);
517                 });
518
519                 from = node[0];
520             }
521         }
522         var Factory, typeMethods, typeTransformations;
523         if(from.nodeType === Node.TEXT_NODE) {
524             Factory = this.TextNodeFactory;
525             typeMethods = this._textNodeMethods;
526             typeTransformations = this._textNodeTransformations;
527         } else if(from.nodeType === Node.ELEMENT_NODE) {
528             Factory = this.ElementNodeFactory;
529             typeMethods = this._elementNodeMethods;
530             typeTransformations = this._elementNodeTransformations;
531         }
532         var toret = new Factory(from, this);
533         _.extend(toret, this._nodeMethods);
534         _.extend(toret, typeMethods);
535         _.extend(toret, this._nodeTransformations);
536         _.extend(toret, typeTransformations);
537         return toret;
538     },
539
540     loadXML: function(xml, options) {
541         options = options || {};
542         defineDocumentProperties(this, $(parseXML(xml)));
543         if(!options.silent) {
544             this.trigger('contentSet');
545         }
546     },
547
548     toXML: function() {
549         return this.root.toXML();
550     },
551
552     containsNode: function(node) {
553         return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
554     },
555
556     wrapNodes: function(params) {
557         if(!(params.node1.parent().sameNode(params.node2.parent()))) {
558             throw new Error('Wrapping non-sibling nodes not supported.');
559         }
560
561         var parent = params.node1.parent(),
562             parentContents = parent.contents(),
563             wrapper = this.createDocumentNode({
564                 tagName: params._with.tagName,
565                 attrs: params._with.attrs}),
566             idx1 = parent.indexOf(params.node1),
567             idx2 = parent.indexOf(params.node2);
568
569         if(idx1 > idx2) {
570             var tmp = idx1;
571             idx1 = idx2;
572             idx2 = tmp;
573         }
574
575         var insertingMethod, insertingTarget;
576         if(idx1 === 0) {
577             insertingMethod = 'prepend';
578             insertingTarget = parent;
579         } else {
580             insertingMethod = 'after';
581             insertingTarget = parentContents[idx1-1];
582         }
583
584         for(var i = idx1; i <= idx2; i++) {
585             wrapper.append(parentContents[i].detach());
586         }
587
588         insertingTarget[insertingMethod](wrapper);
589         return wrapper;
590     },
591
592     getSiblingParents: function(params) {
593         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
594             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
595             noSiblingParents = null;
596
597         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
598             return noSiblingParents;
599         }
600
601         var i;
602         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
603             if(parents1[i].sameNode(parents2[i])) {
604                 continue;
605             }
606             break;
607         }
608         return {node1: parents1[i], node2: parents2[i]};
609     },
610
611     _wrapText: function(params) {
612         params = _.extend({textNodeIdx: 0}, params);
613         if(typeof params.textNodeIdx === 'number') {
614             params.textNodeIdx = [params.textNodeIdx];
615         }
616         
617         var contentsInside = params.inside.contents(),
618             idx1 = Math.min.apply(Math, params.textNodeIdx),
619             idx2 = Math.max.apply(Math, params.textNodeIdx),
620             textNode1 = contentsInside[idx1],
621             textNode2 = contentsInside[idx2],
622             sameNode = textNode1.sameNode(textNode2),
623             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
624             prefixInside = textNode1.getText().substr(params.offsetStart),
625             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
626             suffixOutside = textNode2.getText().substr(params.offsetEnd)
627         ;
628
629         if(!(textNode1.parent().sameNode(textNode2.parent()))) {
630             throw new Error('Wrapping text in non-sibling text nodes not supported.');
631         }
632         
633         var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
634         textNode1.after(wrapperElement);
635         textNode1.detach();
636         
637         if(prefixOutside.length > 0) {
638             wrapperElement.before({text:prefixOutside});
639         }
640         if(sameNode) {
641             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
642             wrapperElement.append({text: core});
643         } else {
644             textNode2.detach();
645             if(prefixInside.length > 0) {
646                 wrapperElement.append({text: prefixInside});
647             }
648             for(var i = idx1 + 1; i < idx2; i++) {
649                 wrapperElement.append(contentsInside[i]);
650             }
651             if(suffixInside.length > 0) {
652                 wrapperElement.append({text: suffixInside});
653             }
654         }
655         if(suffixOutside.length > 0) {
656             wrapperElement.after({text: suffixOutside});
657         }
658         return wrapperElement;
659     },
660
661     trigger: function() {
662         //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
663         Backbone.Events.trigger.apply(this, arguments);
664     },
665
666     getNodeInsertion: function(node) {
667         var insertion = {};
668         if(node instanceof DocumentNode) {
669             insertion.ofNode = node;
670             insertion.insertsNew = !this.containsNode(node);
671         } else {
672           insertion.ofNode = this.createDocumentNode(node);
673           insertion.insertsNew = true;
674         }
675         return insertion;
676     },
677
678     replaceRoot: function(node) {
679         var insertion = this.getNodeInsertion(node);
680         this.root.detach();
681         defineDocumentProperties(this, insertion.ofNode._$);
682         insertion.ofNode.triggerChangeEvent('nodeAdded');
683         return insertion.ofNode;
684     },
685
686     registerMethod: function(methodName, method, dstName) {
687         var doc = this;
688         var destination = {
689             document: doc,
690             documentNode: doc._nodeMethods,
691             textNode: doc._textNodeMethods,
692             elementNode: doc._elementNodeMethods
693         }[dstName];
694         registerMethod(methodName, method, destination);
695     },
696
697     registerTransformation: function(desc, name, dstName) {
698         var doc = this;
699         var destination = {
700             document: doc,
701             documentNode: doc._nodeTransformations,
702             textNode: doc._textNodeTransformations,
703             elementNode: doc._elementNodeTransformations
704         }[dstName];
705         registerTransformation(desc, name, destination);
706     },
707
708     registerExtension: function(extension) {
709         //debugger;
710         var doc = this,
711             existingPropertyNames = _.values(this);
712
713         ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
714             var dstExtension = extension[dstName];
715             if(dstExtension) {
716                 if(dstExtension.methods) {
717                     _.pairs(dstExtension.methods).forEach(function(pair) {
718                         var methodName = pair[0],
719                             method = pair[1];
720
721                         doc.registerMethod(methodName, method, dstName);
722
723                     });
724                 }
725
726                 if(dstExtension.transformations) {
727                     _.pairs(dstExtension.transformations).forEach(function(pair) {
728                         var name = pair[0],
729                             desc = pair[1];
730                         doc.registerTransformation(desc, name, dstName);
731                     });
732                 }
733             }
734         });
735     },
736
737     transform: function(Transformation, args) {
738         //console.log('transform');
739         var toret, transformation;
740
741         if(typeof Transformation === 'function') {
742             transformation = new Transformation(this, this, args);
743         } else {
744             transformation = Transformation;
745         }
746         if(transformation) {
747             this._transformationLevel++;
748             toret = transformation.run();
749             if(this._transformationLevel === 1) {
750                 this.undoStack.push(transformation);
751             }
752             this._transformationLevel--;
753             //console.log('clearing redo stack');
754             this.redoStack = [];
755             return toret;
756         } else {
757             throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
758         }
759     },
760     undo: function() {
761         var transformation = this.undoStack.pop();
762         if(transformation) {
763             transformation.undo();
764             this.redoStack.push(transformation);
765         }
766     },
767     redo: function() {
768         var transformation = this.redoStack.pop();
769         if(transformation) {
770             transformation.run();
771             this.undoStack.push(transformation);
772         }
773     },
774
775     getNodeByPath: function(path) {
776         var toret = this.root;
777         path.forEach(function(idx) {
778             toret = toret.contents()[idx];
779         });
780         return toret;
781     }
782 });
783
784 var defineDocumentProperties = function(doc, $document) {
785     Object.defineProperty(doc, 'root', {get: function() {
786         return doc.createDocumentNode($document[0]);
787     }, configurable: true});
788     Object.defineProperty(doc, 'dom', {get: function() {
789         return $document[0];
790     }, configurable: true});
791 };
792
793
794 return {
795     documentFromXML: function(xml) {
796         return new Document(xml);
797     },
798
799     elementNodeFromXML: function(xml) {
800         return this.documentFromXML(xml).root;
801     },
802
803     Document: Document,
804     DocumentNode: DocumentNode,
805     ElementNode: ElementNode,
806     TextNode: TextNode
807 };
808
809 });