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