pre d: setattr, settext, split as ContextTransformations; detach in old format; pre...
[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
47     transform: function(name, args) {
48         var Transformation = contextTransformations[name],
49             transformation;
50         if(Transformation) {
51             transformation = new Transformation(this.document, this, args);
52         }
53         return this.document.transform(transformation);
54     },
55
56     _setNativeNode: function(nativeNode) {
57         this.nativeNode = nativeNode;
58         this._$ = $(nativeNode);
59     },
60
61     clone: function() {
62         var clone = this._$.clone(true, true);
63         // clone.find('*').addBack().each(function() {
64         //     var n = $(this);
65         //     if(n.data('canvasElement')) {
66         //         n.data('canvasElement', $.extend(true, {}, n.data('canvasElement')));
67         //         n.data('canvasElement').$element = n.data('canvasElement').$element.clone(true, true);
68         //     }
69         // });
70         return this.document.createDocumentNode(clone[0]);
71     },
72
73     getPath: function(ancestor) {
74         var nodePath = [this].concat(this.parents()),
75             toret, idx;
76         ancestor = ancestor || this.document.root;
77
78         nodePath.some(function(node, i) {
79             if(node.sameNode(ancestor)) {
80                 idx = i;
81                 return true;
82             }
83         });
84
85         if(idx !== 'undefined') {
86             nodePath = nodePath.slice(0, idx);
87         }
88         toret = nodePath.map(function(node) {return node.getIndex(); });
89         toret.reverse();
90         return toret;
91     },
92
93     isRoot: function() {
94         return this.document.root.sameNode(this);
95     },
96
97     detach: function() {
98         var parent = this.parent();
99         this._$.detach();
100         this.triggerChangeEvent('nodeDetached', {parent: parent});
101         return this;
102     },
103
104     replaceWith: function(node) {
105         var toret;
106         if(this.isRoot()) {
107             return this.document.replaceRoot(node);
108         }
109         toret = this.after(node);
110         this.detach();
111         return toret;
112     },
113
114     sameNode: function(otherNode) {
115         return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
116     },
117
118     parent: function() {
119         var parentNode = this.nativeNode.parentNode;
120         if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
121             return this.document.createDocumentNode(parentNode);
122         }
123         return null;
124     },
125
126     parents: function() {
127         var parent = this.parent(),
128             parents = parent ? parent.parents() : [];
129         if(parent) {
130             parents.unshift(parent);
131         }
132         return parents;
133     },
134
135     prev: function() {
136         var myIdx = this.getIndex();
137         return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
138     },
139
140     next: function() {
141         if(this.isRoot()) {
142             return null;
143         }
144         var myIdx = this.getIndex(),
145             parentContents = this.parent().contents();
146         return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
147     },
148
149     isSurroundedByTextElements: function() {
150         var prev = this.prev(),
151             next = this.next();
152         return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
153     },
154
155     after: INSERTION(function(nativeNode) {
156         return this._$.after(nativeNode);
157     }),
158
159     before: INSERTION(function(nativeNode) {
160         return this._$.before(nativeNode);
161     }),
162
163     wrapWith: function(node) {
164         var insertion = this.getNodeInsertion(node);
165         if(this.parent()) {
166             this.before(insertion.ofNode);
167         }
168         insertion.ofNode.append(this);
169         return insertion.ofNode;
170     },
171
172     /**
173     * Removes parent of a node if node has no siblings.
174     */
175     unwrap: function() {
176         if(this.isRoot()) {
177             return;
178         }
179         var parent = this.parent(),
180             grandParent;
181         if(parent.contents().length === 1) {
182             grandParent = parent.parent();
183             parent.unwrapContent();
184             return grandParent;
185         }
186     },
187
188     triggerChangeEvent: function(type, metaData, origParent) {
189         var node = (metaData && metaData.node) ? metaData.node : this,
190             event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
191         if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
192             this.document.trigger('change', event);
193         }
194         if((type === 'nodeAdded' || type === 'nodeMoved') && !(this.document.containsNode(this))) {
195              event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
196              this.document.trigger('change', event);
197         }
198     },
199     
200     getNodeInsertion: function(node) {
201         return this.document.getNodeInsertion(node);
202     },
203
204     getIndex: function() {
205         if(this.isRoot()) {
206             return 0;
207         }
208         return this.parent().indexOf(this);
209     }
210 });
211
212 var ElementNode = function(nativeNode, document) {
213     DocumentNode.call(this, nativeNode, document);
214 };
215 ElementNode.prototype = Object.create(DocumentNode.prototype);
216
217 $.extend(ElementNode.prototype, {
218     nodeType: Node.ELEMENT_NODE,
219
220     detach: function() {
221         var next;
222         if(this.parent() && this.isSurroundedByTextElements()) {
223             next = this.next();
224             this.prev().appendText(next.getText());
225             next.detach();
226         }
227         return DocumentNode.prototype.detach.call(this);
228     },
229
230     setData: function(key, value) {
231         if(value !== undefined) {
232             this._$.data(key, value);
233         } else {
234             this._$.removeData(_.keys(this._$.data()));
235             this._$.data(key);
236         }
237     },
238
239     getData: function(key) {
240         if(key) {
241             return this._$.data(key);
242         }
243         return this._$.data();
244     },
245
246     getTagName: function() {
247         return this.nativeNode.tagName.toLowerCase();
248     },
249
250     contents: function() {
251         var toret = [],
252             document = this.document;
253         this._$.contents().each(function() {
254             toret.push(document.createDocumentNode(this));
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 Document = function(xml) {
475     this.loadXML(xml);
476     this.undoStack = [];
477     this.redoStack = [];
478 };
479
480 $.extend(Document.prototype, Backbone.Events, {
481     ElementNodeFactory: ElementNode,
482     TextNodeFactory: TextNode,
483
484     createDocumentNode: function(from) {
485         if(!(from instanceof Node)) {
486             if(from.text !== undefined) {
487                 /* globals document */
488                 from = document.createTextNode(from.text);
489             } else {
490                 var node = $('<' + from.tagName + '>');
491
492                 _.keys(from.attrs || {}).forEach(function(key) {
493                     node.attr(key, from.attrs[key]);
494                 });
495
496                 from = node[0];
497             }
498         }
499         var Factory;
500         if(from.nodeType === Node.TEXT_NODE) {
501             Factory = this.TextNodeFactory;
502         } else if(from.nodeType === Node.ELEMENT_NODE) {
503             Factory = this.ElementNodeFactory;
504         }
505         return new Factory(from, this);
506     },
507
508     loadXML: function(xml, options) {
509         options = options || {};
510         defineDocumentProperties(this, $(parseXML(xml)));
511         if(!options.silent) {
512             this.trigger('contentSet');
513         }
514     },
515
516     toXML: function() {
517         return this.root.toXML();
518     },
519
520     containsNode: function(node) {
521         return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
522     },
523
524     wrapNodes: function(params) {
525         if(!(params.node1.parent().sameNode(params.node2.parent()))) {
526             throw new Error('Wrapping non-sibling nodes not supported.');
527         }
528
529         var parent = params.node1.parent(),
530             parentContents = parent.contents(),
531             wrapper = this.createDocumentNode({
532                 tagName: params._with.tagName,
533                 attrs: params._with.attrs}),
534             idx1 = parent.indexOf(params.node1),
535             idx2 = parent.indexOf(params.node2);
536
537         if(idx1 > idx2) {
538             var tmp = idx1;
539             idx1 = idx2;
540             idx2 = tmp;
541         }
542
543         var insertingMethod, insertingTarget;
544         if(idx1 === 0) {
545             insertingMethod = 'prepend';
546             insertingTarget = parent;
547         } else {
548             insertingMethod = 'after';
549             insertingTarget = parentContents[idx1-1];
550         }
551
552         for(var i = idx1; i <= idx2; i++) {
553             wrapper.append(parentContents[i].detach());
554         }
555
556         insertingTarget[insertingMethod](wrapper);
557         return wrapper;
558     },
559
560     getSiblingParents: function(params) {
561         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
562             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
563             noSiblingParents = null;
564
565         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
566             return noSiblingParents;
567         }
568
569         var i;
570         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
571             if(parents1[i].sameNode(parents2[i])) {
572                 continue;
573             }
574             break;
575         }
576         return {node1: parents1[i], node2: parents2[i]};
577     },
578
579     _wrapText: function(params) {
580         params = _.extend({textNodeIdx: 0}, params);
581         if(typeof params.textNodeIdx === 'number') {
582             params.textNodeIdx = [params.textNodeIdx];
583         }
584         
585         var contentsInside = params.inside.contents(),
586             idx1 = Math.min.apply(Math, params.textNodeIdx),
587             idx2 = Math.max.apply(Math, params.textNodeIdx),
588             textNode1 = contentsInside[idx1],
589             textNode2 = contentsInside[idx2],
590             sameNode = textNode1.sameNode(textNode2),
591             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
592             prefixInside = textNode1.getText().substr(params.offsetStart),
593             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
594             suffixOutside = textNode2.getText().substr(params.offsetEnd)
595         ;
596
597         if(!(textNode1.parent().sameNode(textNode2.parent()))) {
598             throw new Error('Wrapping text in non-sibling text nodes not supported.');
599         }
600         
601         var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
602         textNode1.after(wrapperElement);
603         textNode1.detach();
604         
605         if(prefixOutside.length > 0) {
606             wrapperElement.before({text:prefixOutside});
607         }
608         if(sameNode) {
609             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
610             wrapperElement.append({text: core});
611         } else {
612             textNode2.detach();
613             if(prefixInside.length > 0) {
614                 wrapperElement.append({text: prefixInside});
615             }
616             for(var i = idx1 + 1; i < idx2; i++) {
617                 wrapperElement.append(contentsInside[i]);
618             }
619             if(suffixInside.length > 0) {
620                 wrapperElement.append({text: suffixInside});
621             }
622         }
623         if(suffixOutside.length > 0) {
624             wrapperElement.after({text: suffixOutside});
625         }
626         return wrapperElement;
627     },
628
629     trigger: function() {
630         //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
631         Backbone.Events.trigger.apply(this, arguments);
632     },
633
634     getNodeInsertion: function(node) {
635         var insertion = {};
636         if(node instanceof DocumentNode) {
637             insertion.ofNode = node;
638             insertion.insertsNew = !this.containsNode(node);
639         } else {
640           insertion.ofNode = this.createDocumentNode(node);
641           insertion.insertsNew = true;
642         }
643         return insertion;
644     },
645
646     replaceRoot: function(node) {
647         var insertion = this.getNodeInsertion(node);
648         this.root.detach();
649         defineDocumentProperties(this, insertion.ofNode._$);
650         insertion.ofNode.triggerChangeEvent('nodeAdded');
651         return insertion.ofNode;
652     },
653
654     transform: function(transformationName, args) {
655         console.log('transform');
656         var Transformation, transformation, toret;
657         if(typeof transformationName === 'string') {
658             Transformation = transformations[transformationName];
659             if(Transformation) {
660                 transformation = new Transformation(args);
661             }
662         } else {
663             transformation = transformationName;
664         }
665         if(transformation) {
666             toret = transformation.run();
667             this.undoStack.push(transformation);
668             console.log('clearing redo stack');
669             this.redoStack = [];
670             return toret;
671         } else {
672             throw new Error('Transformation ' + transformationName + ' doesn\'t exist!');
673         }
674     },
675     undo: function() {
676         var transformation = this.undoStack.pop();
677         if(transformation) {
678             transformation.undo();
679             this.redoStack.push(transformation);
680         }
681     },
682     redo: function() {
683         var transformation = this.redoStack.pop();
684         if(transformation) {
685             transformation.run();
686             this.undoStack.push(transformation);
687         }
688     },
689
690     getNodeByPath: function(path) {
691         var toret = this.root;
692         path.forEach(function(idx) {
693             toret = toret.contents()[idx];
694         });
695         return toret;
696     }
697 });
698
699 var defineDocumentProperties = function(doc, $document) {
700     Object.defineProperty(doc, 'root', {get: function() {
701         return doc.createDocumentNode($document[0]);
702     }, configurable: true});
703     Object.defineProperty(doc, 'dom', {get: function() {
704         return $document[0];
705     }, configurable: true});
706 };
707
708
709 // var registerTransformationsFromObject = function(object) {
710 //     _.values(object).filter(function(val) {
711 //         return typeof val === 'function' && val._isTransformation;
712 //     })
713 //     .forEach(function(val) {
714 //         registerTransformation(val._transformationName, val, object);
715 //     });
716 // };
717 // registerTransformationsFromObject(ElementNode.prototype);
718 // registerTransformationsFromObject(TextNode.prototype);
719 // registerTransformationsFromObject(Document.prototype);
720
721 // var Transformation = function() {
722 // };
723 // $.extend(Transformation.prototype, {
724
725 // });
726
727
728 // var createDumbTransformation = function(impl, contextObject) {
729 //     var DumbTransformation = function(args) {
730 //         this.args = this.args;
731 //     };
732 //     DumbTransformation.prototype = Object.create(Transformation.prototype);
733 //     $.extend(DumbTransformation.prototype, {
734 //         run: function() {
735 //             impl.apply(contextObject, this.args);
736 //         }
737 //     });
738
739 //     return DumbTransformation;
740
741
742 // };
743
744 var transformations = {};
745 // var registerTransformation = function(name, impl, contextObject) {
746 //     if(typeof impl === 'function') {
747 //         transformations[name] = createDumbTransformation(impl, contextObject);
748 //     }
749 // };
750
751 // registerTransformation('detachx', DocumentNode.prototype.detach,  )
752
753
754 // 1. detach via totalny fallback
755 var DetachNodeTransformation = function(args) {
756     this.node = args.node;
757     this.document = this.node.document;
758 };
759 $.extend(DetachNodeTransformation.prototype, {
760     run: function() {
761         this.oldRoot = this.node.document.root.clone();
762         this.path = this.node.getPath();
763         this.node.detach(); // @TS
764         
765     },
766     undo: function() {
767         this.document.root.replaceWith(this.oldRoot); // this.getDocument?
768         this.node = this.document.getNodeByPath(this.path);
769     }
770 });
771 transformations['detach'] = DetachNodeTransformation;
772
773 //2. detach via wskazanie changeroot
774
775 var Detach2NodeTransformation = function(args) {
776     this.nodePath = args.node.getPath();
777     this.document = args.node.document;
778 };
779 $.extend(Detach2NodeTransformation.prototype, {
780     run: function() {
781         var node = this.document.getNodeByPath(this.nodePath),
782             root = node.parent() ? node.parent() : this.document.root;
783         
784         this.rootPath = root.getPath();
785         this.oldRoot = (root).clone();
786         node.detach();
787     },
788     undo: function() {
789         this.document.getNodeByPath(this.rootPath).replaceWith(this.oldRoot);
790     }
791 });
792 //transformations['detach2'] = Detach2NodeTransformation;
793
794 //2a. generyczna transformacja
795
796 var createTransformation = function(desc) {
797
798     var NodeTransformation = function(args) {
799         this.nodePath = args.node.getPath();
800         this.document = args.node.document;
801         this.args = args;
802     };
803     $.extend(NodeTransformation.prototype, {
804         run: function() {
805             var node = this.document.getNodeByPath(this.nodePath),
806                 root;
807
808             if(desc.getRoot) {
809                 root = desc.getRoot(node);
810             } else {
811                 root = this.document.root;
812             }
813             
814             this.rootPath = root.getPath();
815             this.oldRoot = (root).clone();
816             desc.impl.call(node, this.args);
817         },
818         undo: function() {
819             this.document.getNodeByPath(this.rootPath).replaceWith(this.oldRoot);
820         }
821     });
822
823     return NodeTransformation;
824 }
825
826 ///
827 var Transformation = function(args) {
828     this.args = args;
829 };
830 $.extend(Transformation.prototype, {
831     run: function() {
832         throw new Error('not implemented');
833     },
834     undo: function() {
835         throw new Error('not implemented');
836     },
837 });
838
839 var createGenericTransformation = function(desc) {
840     var GenericTransformation = function(document, args) {
841         //document.getNodeByPath(contextPath).call(this, args);
842         this.args = args;
843         this.document = document;
844     };
845     $.extend(GenericTransformation.prototype, {
846         run: function() {
847             var changeRoot = desc.getChangeRoot ? desc.getChangeRoot.call(this) : this.document.root;
848             this.snapshot = changeRoot.clone();
849             this.changeRootPath = changeRoot.getPath();
850             return desc.impl.call(this.context, this.args); // a argumenty do metody?
851         },
852         undo: function() {
853             this.document.getNodeByPath(this.changeRootPath).replaceWith(this.snapshot);
854         },
855     });
856
857     return GenericTransformation;
858 };
859
860 // var T = createGenericTransformation({impl: function() {}});
861 // var t = T(doc, {a:1,b:2,c3:3});
862
863
864 var createContextTransformation = function(desc) {
865     // mozna sie pozbyc przez przeniesienie object/context na koniec argumentow konstruktora generic transformation
866     var GenericTransformation = createGenericTransformation(desc);
867
868     var ContextTransformation = function(document, object, args) {
869         var contextPath = object.getPath();
870
871         GenericTransformation.call(this, document, args);
872         
873         Object.defineProperty(this, 'context', {
874             get: function() {
875                 return document.getNodeByPath(contextPath);
876             }
877         });
878     }
879     ContextTransformation.prototype = Object.create(GenericTransformation.prototype);
880     return ContextTransformation;
881 }
882 // var T = createContextTransformation({impl: function() {}});
883 // var t = T(doc, node, {a:1,b:2,c3:3});
884 ///
885
886 var contextTransformations = {};
887 contextTransformations['setText'] = createContextTransformation({
888     impl: function(args) {
889         this.setText(args.text);
890     },
891     getChangeRoot: function() {
892         return this.context;
893     }
894 });
895
896 contextTransformations['setAttr'] = createContextTransformation({
897     impl: function(args) {
898         this.setAttr(args.name, args.value);
899     },
900     getChangeRoot: function() {
901         return this.context;
902     }
903 });
904
905 contextTransformations['split'] = createContextTransformation({
906     impl: function(args) {
907         return this.split({offset: args.offset});
908     }//,
909     // getChangeRoot: function() {
910     //     return this.context.parent().parent();
911     // }
912 });
913
914 // var TRANSFORMATION2 = function(f, getChangeRoot, undo) {
915 //     var context = this,
916
917
918 //     var transformation = createContextTransformation({
919 //         impl: f,
920 //         getChangeRoot: getChangeRoot,
921
922 //     });
923
924 //     var toret = function() {
925 //         var 
926 //         f.apply(context, createArgs ? createArgs(arguments) : arguments)
927 //     };
928 //     return toret;
929 // }
930
931 transformations['detach2'] = createTransformation({
932     // impl: function() {
933     //     //this.setAttr('class', 'cite'); //  
934     // },
935     impl: ElementNode.prototype.detach,
936     getRoot: function(node) {
937         return node.parent();
938     }
939
940 });
941
942 transformations['setText-old'] = createTransformation({
943     impl: function(args) {
944         this.setText(args.text)
945     },
946     getRoot: function(node) {
947         return node;
948     }
949
950 });
951
952 transformations['setClass-old'] = createTransformation({
953     impl: function(args) {
954         this.setClass(args.klass);
955     },
956     getRoot: function(node) {
957         return node;
958     }
959 })
960
961 //3. detach z pełnym własnym redo
962
963 var Detach3NodeTransformation = function(args) {
964     this.node = args.node;
965     this.document = this.node.document;
966 };
967 $.extend(Detach3NodeTransformation.prototype, {
968     run: function() {
969         //this.index = this.node.getIndex();
970         //this.parent = this.node.parent();
971         
972         this.path = this.node.getPath();
973         if(this.node.isSurroundedByTextElements()) {
974             this.prevText = this.node.prev().getText();
975             this.nextText = this.node.next().getText();
976             this.merge = true;
977         } else {
978             this.prevText = this.nextText = null;
979             this.merge = false;
980         }
981
982         this.node.detach();
983     },
984     undo: function() {
985         var parent = this.document.getNodeByPath(this.path.slice(0,-1)),
986             idx = _.last(this.path);
987         var inserted = parent.insertAtIndex(this.node, idx);
988         if(this.merge) {
989             if(inserted.next()) {
990                 inserted.before({text: this.prevText});
991                 inserted.next().setText(this.nextText);
992             } else {
993                 inserted.prev().setText(this.prevText);
994                 inserted.after({text: this.nextText});
995             }
996         }
997     }
998 });
999 transformations['detach3'] = Detach3NodeTransformation;
1000
1001
1002 var registerTransformationsFromObject = function(object) {
1003     _.pairs(object).filter(function(pair) {
1004         var property = pair[1];
1005         return typeof property === 'function' && property._isTransformation;
1006     })
1007     .forEach(function(pair) {
1008         var name = pair[0],
1009             method = pair[1];
1010         object.registerTransformation(name, createContextTransformation(method));
1011     });
1012 };
1013 registerTransformationsFromObject(ElementNode.prototype);
1014 registerTransformationsFromObject(TextNode.prototype);
1015 registerTransformationsFromObject(Document.prototype);
1016
1017 return {
1018     documentFromXML: function(xml) {
1019         return new Document(xml);
1020     },
1021
1022     elementNodeFromXML: function(xml) {
1023         return this.documentFromXML(xml).root;
1024     },
1025
1026     Document: Document,
1027     DocumentNode: DocumentNode,
1028     ElementNode: ElementNode
1029 };
1030
1031 });