wip: detach2 ok
[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         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) {
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))) {
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() {
241         var toret = [],
242             document = this.document;
243         this._$.contents().each(function() {
244             toret.push(document.createDocumentNode(this));
245         });
246         return toret;
247     },
248
249     indexOf: function(node) {
250         return this._$.contents().index(node._$);
251     },
252
253     setTag: function(tagName) {
254         var node = this.document.createDocumentNode({tagName: tagName}),
255             oldTagName = this.getTagName(),
256             myContents = this._$.contents();
257
258         this.getAttrs().forEach(function(attribute) {
259             node.setAttr(attribute.name, attribute.value, true);
260         });
261         node.setData(this.getData());
262
263         if(this.sameNode(this.document.root)) {
264             defineDocumentProperties(this.document, node._$);
265         }
266         this._$.replaceWith(node._$);
267         this._setNativeNode(node._$[0]);
268         this._$.append(myContents);
269         this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
270     },
271
272     getAttr: function(name) {
273         return this._$.attr(name);
274     },
275
276     setAttr: function(name, value, silent) {
277         var oldVal = this.getAttr(name);
278         this._$.attr(name, value);
279         if(!silent) {
280             this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
281         }
282     },
283
284     getAttrs: function() {
285         var toret = [];
286         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
287             toret.push(this.nativeNode.attributes[i]);
288         }
289         return toret;
290     },
291
292     append: INSERTION(function(nativeNode) {
293         this._$.append(nativeNode);
294     }),
295
296     prepend: INSERTION(function(nativeNode) {
297         this._$.prepend(nativeNode);
298     }),
299
300     insertAtIndex: function(nativeNode, index) {
301         var contents = this.contents();
302         if(index < contents.length) {
303             return contents[index].before(nativeNode);
304         } else if(index === contents.length) {
305             return this.append(nativeNode);
306         }
307     },
308
309     unwrapContent: function() {
310         var parent = this.parent();
311         if(!parent) {
312             return;
313         }
314
315         var myContents = this.contents(),
316             myIdx = parent.indexOf(this);
317
318
319         if(myContents.length === 0) {
320             return this.detach();
321         }
322
323         var prev = this.prev(),
324             next = this.next(),
325             moveLeftRange, moveRightRange, leftMerged;
326
327         if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
328             prev.appendText(myContents[0].getText());
329             myContents[0].detach();
330             moveLeftRange = true;
331             leftMerged = true;
332         } else {
333             leftMerged = false;
334         }
335
336         if(!(leftMerged && myContents.length === 1)) {
337             var lastContents = _.last(myContents);
338             if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
339                 next.prependText(lastContents.getText());
340                 lastContents.detach();
341                 moveRightRange = true;
342             }
343         }
344
345         var childrenLength = this.contents().length;
346         this.contents().forEach(function(child) {
347             this.before(child);
348         }.bind(this));
349
350         this.detach();
351
352         return {
353             element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
354             element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
355         };
356     },
357
358     wrapText: function(params) {
359         return this.document._wrapText(_.extend({inside: this}, params));
360     },
361
362     toXML: function() {
363         var wrapper = $('<div>');
364         wrapper.append(this._getXMLDOMToDump());
365         return wrapper.html();
366     },
367     
368     _getXMLDOMToDump: function() {
369         return this._$;
370     }
371 });
372
373 var TextNode = function(nativeNode, document) {
374     DocumentNode.call(this, nativeNode, document);
375 };
376 TextNode.prototype = Object.create(DocumentNode.prototype);
377
378 $.extend(TextNode.prototype, {
379     nodeType: Node.TEXT_NODE,
380
381     getText: function() {
382         return this.nativeNode.data;
383     },
384
385     setText: function(text) {
386         this.nativeNode.data = text;
387         this.triggerTextChangeEvent();
388     },
389
390     appendText: function(text) {
391         this.nativeNode.data = this.nativeNode.data + text;
392         this.triggerTextChangeEvent();
393     },
394
395     prependText: function(text) {
396         this.nativeNode.data = text + this.nativeNode.data;
397         this.triggerTextChangeEvent();
398     },
399
400     wrapWith: function(desc) {
401         if(typeof desc.start === 'number' && typeof desc.end === 'number') {
402             return this.document._wrapText({
403                 inside: this.parent(),
404                 textNodeIdx: this.parent().indexOf(this),
405                 offsetStart: Math.min(desc.start, desc.end),
406                 offsetEnd: Math.max(desc.start, desc.end),
407                 _with: {tagName: desc.tagName, attrs: desc.attrs}
408             });
409         } else {
410             return DocumentNode.prototype.wrapWith.call(this, desc);
411         }
412     },
413
414     split: function(params) {
415         var parentElement = this.parent(),
416             passed = false,
417             succeedingChildren = [],
418             prefix = this.getText().substr(0, params.offset),
419             suffix = this.getText().substr(params.offset);
420
421         parentElement.contents().forEach(function(child) {
422             if(passed) {
423                 succeedingChildren.push(child);
424             }
425             if(child.sameNode(this)) {
426                 passed = true;
427             }
428         }.bind(this));
429
430         if(prefix.length > 0) {
431             this.setText(prefix);
432         }
433         else {
434             this.detach();
435         }
436
437         var attrs = {};
438         parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
439         var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
440         parentElement.after(newElement);
441
442         if(suffix.length > 0) {
443             newElement.append({text: suffix});
444         }
445         succeedingChildren.forEach(function(child) {
446             newElement.append(child);
447         });
448
449         return {first: parentElement, second: newElement};
450     },
451
452     triggerTextChangeEvent: function() {
453         var event = new events.ChangeEvent('nodeTextChange', {node: this});
454         this.document.trigger('change', event);
455     }
456 });
457
458
459 var parseXML = function(xml) {
460     return $($.trim(xml))[0];
461 };
462
463 var Document = function(xml) {
464     this.loadXML(xml);
465     this.undoStack = [];
466     this.redoStack = [];
467 };
468
469 $.extend(Document.prototype, Backbone.Events, {
470     ElementNodeFactory: ElementNode,
471     TextNodeFactory: TextNode,
472
473     createDocumentNode: function(from) {
474         if(!(from instanceof Node)) {
475             if(from.text !== undefined) {
476                 /* globals document */
477                 from = document.createTextNode(from.text);
478             } else {
479                 var node = $('<' + from.tagName + '>');
480
481                 _.keys(from.attrs || {}).forEach(function(key) {
482                     node.attr(key, from.attrs[key]);
483                 });
484
485                 from = node[0];
486             }
487         }
488         var Factory;
489         if(from.nodeType === Node.TEXT_NODE) {
490             Factory = this.TextNodeFactory;
491         } else if(from.nodeType === Node.ELEMENT_NODE) {
492             Factory = this.ElementNodeFactory;
493         }
494         return new Factory(from, this);
495     },
496
497     loadXML: function(xml, options) {
498         options = options || {};
499         defineDocumentProperties(this, $(parseXML(xml)));
500         if(!options.silent) {
501             this.trigger('contentSet');
502         }
503     },
504
505     toXML: function() {
506         return this.root.toXML();
507     },
508
509     containsNode: function(node) {
510         return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
511     },
512
513     wrapNodes: function(params) {
514         if(!(params.node1.parent().sameNode(params.node2.parent()))) {
515             throw new Error('Wrapping non-sibling nodes not supported.');
516         }
517
518         var parent = params.node1.parent(),
519             parentContents = parent.contents(),
520             wrapper = this.createDocumentNode({
521                 tagName: params._with.tagName,
522                 attrs: params._with.attrs}),
523             idx1 = parent.indexOf(params.node1),
524             idx2 = parent.indexOf(params.node2);
525
526         if(idx1 > idx2) {
527             var tmp = idx1;
528             idx1 = idx2;
529             idx2 = tmp;
530         }
531
532         var insertingMethod, insertingTarget;
533         if(idx1 === 0) {
534             insertingMethod = 'prepend';
535             insertingTarget = parent;
536         } else {
537             insertingMethod = 'after';
538             insertingTarget = parentContents[idx1-1];
539         }
540
541         for(var i = idx1; i <= idx2; i++) {
542             wrapper.append(parentContents[i].detach());
543         }
544
545         insertingTarget[insertingMethod](wrapper);
546         return wrapper;
547     },
548
549     getSiblingParents: function(params) {
550         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
551             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
552             noSiblingParents = null;
553
554         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
555             return noSiblingParents;
556         }
557
558         var i;
559         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
560             if(parents1[i].sameNode(parents2[i])) {
561                 continue;
562             }
563             break;
564         }
565         return {node1: parents1[i], node2: parents2[i]};
566     },
567
568     _wrapText: function(params) {
569         params = _.extend({textNodeIdx: 0}, params);
570         if(typeof params.textNodeIdx === 'number') {
571             params.textNodeIdx = [params.textNodeIdx];
572         }
573         
574         var contentsInside = params.inside.contents(),
575             idx1 = Math.min.apply(Math, params.textNodeIdx),
576             idx2 = Math.max.apply(Math, params.textNodeIdx),
577             textNode1 = contentsInside[idx1],
578             textNode2 = contentsInside[idx2],
579             sameNode = textNode1.sameNode(textNode2),
580             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
581             prefixInside = textNode1.getText().substr(params.offsetStart),
582             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
583             suffixOutside = textNode2.getText().substr(params.offsetEnd)
584         ;
585
586         if(!(textNode1.parent().sameNode(textNode2.parent()))) {
587             throw new Error('Wrapping text in non-sibling text nodes not supported.');
588         }
589         
590         var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
591         textNode1.after(wrapperElement);
592         textNode1.detach();
593         
594         if(prefixOutside.length > 0) {
595             wrapperElement.before({text:prefixOutside});
596         }
597         if(sameNode) {
598             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
599             wrapperElement.append({text: core});
600         } else {
601             textNode2.detach();
602             if(prefixInside.length > 0) {
603                 wrapperElement.append({text: prefixInside});
604             }
605             for(var i = idx1 + 1; i < idx2; i++) {
606                 wrapperElement.append(contentsInside[i]);
607             }
608             if(suffixInside.length > 0) {
609                 wrapperElement.append({text: suffixInside});
610             }
611         }
612         if(suffixOutside.length > 0) {
613             wrapperElement.after({text: suffixOutside});
614         }
615         return wrapperElement;
616     },
617
618     trigger: function() {
619         //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
620         Backbone.Events.trigger.apply(this, arguments);
621     },
622
623     getNodeInsertion: function(node) {
624         var insertion = {};
625         if(node instanceof DocumentNode) {
626             insertion.ofNode = node;
627             insertion.insertsNew = !this.containsNode(node);
628         } else {
629           insertion.ofNode = this.createDocumentNode(node);
630           insertion.insertsNew = true;
631         }
632         return insertion;
633     },
634
635     replaceRoot: function(node) {
636         var insertion = this.getNodeInsertion(node);
637         this.root.detach();
638         defineDocumentProperties(this, insertion.ofNode._$);
639         insertion.ofNode.triggerChangeEvent('nodeAdded');
640         return insertion.ofNode;
641     },
642
643     transform: function(transformationName, args) {
644         var Transformation = transformations[transformationName],
645             transformation;
646         if(Transformation) {
647             transformation = new Transformation(args);
648             transformation.run();
649             this.undoStack.push(transformation);
650             this.redoStack = [];
651         } else {
652             throw new Error('Transformation ' + transformationName + ' doesn\'t exist!');
653         }
654     },
655     undo: function() {
656         var transformation = this.undoStack.pop();
657         if(transformation) {
658             transformation.undo();
659             this.redoStack.push(transformation);
660         }
661     },
662     redo: function() {
663         var transformation = this.redoStack.pop();
664         if(transformation) {
665             transformation.run();
666             this.undoStack.push(transformation);
667         }
668     },
669
670     getNodeByPath: function(path) {
671         var toret = this.root;
672         path.forEach(function(idx) {
673             toret = toret.contents()[idx];
674         });
675         return toret;
676     }
677 });
678
679 var defineDocumentProperties = function(doc, $document) {
680     Object.defineProperty(doc, 'root', {get: function() {
681         return doc.createDocumentNode($document[0]);
682     }, configurable: true});
683     Object.defineProperty(doc, 'dom', {get: function() {
684         return $document[0];
685     }, configurable: true});
686 };
687
688
689 // var registerTransformationsFromObject = function(object) {
690 //     _.values(object).filter(function(val) {
691 //         return typeof val === 'function' && val._isTransformation;
692 //     })
693 //     .forEach(function(val) {
694 //         registerTransformation(val._transformationName, val, object);
695 //     });
696 // };
697 // registerTransformationsFromObject(ElementNode.prototype);
698 // registerTransformationsFromObject(TextNode.prototype);
699 // registerTransformationsFromObject(Document.prototype);
700
701 // var Transformation = function() {
702 // };
703 // $.extend(Transformation.prototype, {
704
705 // });
706
707
708 // var createDumbTransformation = function(impl, contextObject) {
709 //     var DumbTransformation = function(args) {
710 //         this.args = this.args;
711 //     };
712 //     DumbTransformation.prototype = Object.create(Transformation.prototype);
713 //     $.extend(DumbTransformation.prototype, {
714 //         run: function() {
715 //             impl.apply(contextObject, this.args);
716 //         }
717 //     });
718
719 //     return DumbTransformation;
720
721
722 // };
723
724 var transformations = {};
725 // var registerTransformation = function(name, impl, contextObject) {
726 //     if(typeof impl === 'function') {
727 //         transformations[name] = createDumbTransformation(impl, contextObject);
728 //     }
729 // };
730
731 // registerTransformation('detachx', DocumentNode.prototype.detach,  )
732
733
734 // 1. detach via totalny fallback
735 var DetachNodeTransformation = function(args) {
736     this.node = args.node;
737     this.document = this.node.document;
738 };
739 $.extend(DetachNodeTransformation.prototype, {
740     run: function() {
741         this.oldRoot = this.node.document.root.clone();
742         this.path = this.node.getPath();
743         this.node.detach(); // @TS
744         
745     },
746     undo: function() {
747         this.document.root.replaceWith(this.oldRoot); // this.getDocument?
748         this.node = this.document.getNodeByPath(this.path);
749     }
750 });
751 transformations['detach'] = DetachNodeTransformation;
752
753 //2. detach via wskazanie changeroot
754
755 var Detach2NodeTransformation = function(args) {
756     this.nodePath = args.node.getPath();
757     this.document = args.node.document;
758 };
759 $.extend(Detach2NodeTransformation.prototype, {
760     run: function() {
761         var node = this.document.getNodeByPath(this.nodePath),
762             root = node.parent() ? node.parent() : this.document.root;
763         
764         this.rootPath = root.getPath();
765         this.oldRoot = (root).clone();
766         node.detach();
767     },
768     undo: function() {
769         this.document.getNodeByPath(this.rootPath).replaceWith(this.oldRoot);
770     }
771 });
772 transformations['detach2'] = Detach2NodeTransformation;
773
774 //3. detach z pełnym własnym redo
775
776 var Detach3NodeTransformation = function(args) {
777     this.node = args.node;
778     this.document = this.node.document;
779 };
780 $.extend(Detach3NodeTransformation.prototype, {
781     run: function() {
782         //this.index = this.node.getIndex();
783         //this.parent = this.node.parent();
784         
785         this.path = this.node.getPath();
786         if(this.node.isSurroundedByTextElements()) {
787             this.prevText = this.node.prev().getText();
788             this.nextText = this.node.next().getText();
789             this.merge = true;
790         } else {
791             this.prevText = this.nextText = null;
792             this.merge = false;
793         }
794
795         this.node.detach();
796     },
797     undo: function() {
798         var parent = this.document.getNodeByPath(this.path.slice(0,-1)),
799             idx = _.last(this.path);
800         var inserted = parent.insertAtIndex(this.node, idx);
801         if(this.merge) {
802             if(inserted.next()) {
803                 inserted.before({text: this.prevText});
804                 inserted.next().setText(this.nextText);
805             } else {
806                 inserted.prev().setText(this.prevText);
807                 inserted.after({text: this.nextText});
808             }
809         }
810     }
811 });
812 transformations['detach3'] = Detach3NodeTransformation;
813
814 return {
815     documentFromXML: function(xml) {
816         return new Document(xml);
817     },
818
819     elementNodeFromXML: function(xml) {
820         return this.documentFromXML(xml).root;
821     },
822
823     Document: Document,
824     DocumentNode: DocumentNode,
825     ElementNode: ElementNode
826 };
827
828 });