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