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