dzialacy remove+text
[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         console.log('smartxml: ' + text);
387         this.nativeNode.data = text;
388         this.triggerTextChangeEvent();
389     },
390
391     appendText: function(text) {
392         this.nativeNode.data = this.nativeNode.data + text;
393         this.triggerTextChangeEvent();
394     },
395
396     prependText: function(text) {
397         this.nativeNode.data = text + this.nativeNode.data;
398         this.triggerTextChangeEvent();
399     },
400
401     wrapWith: function(desc) {
402         if(typeof desc.start === 'number' && typeof desc.end === 'number') {
403             return this.document._wrapText({
404                 inside: this.parent(),
405                 textNodeIdx: this.parent().indexOf(this),
406                 offsetStart: Math.min(desc.start, desc.end),
407                 offsetEnd: Math.max(desc.start, desc.end),
408                 _with: {tagName: desc.tagName, attrs: desc.attrs}
409             });
410         } else {
411             return DocumentNode.prototype.wrapWith.call(this, desc);
412         }
413     },
414
415     split: function(params) {
416         var parentElement = this.parent(),
417             passed = false,
418             succeedingChildren = [],
419             prefix = this.getText().substr(0, params.offset),
420             suffix = this.getText().substr(params.offset);
421
422         parentElement.contents().forEach(function(child) {
423             if(passed) {
424                 succeedingChildren.push(child);
425             }
426             if(child.sameNode(this)) {
427                 passed = true;
428             }
429         }.bind(this));
430
431         if(prefix.length > 0) {
432             this.setText(prefix);
433         }
434         else {
435             this.detach();
436         }
437
438         var attrs = {};
439         parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
440         var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
441         parentElement.after(newElement);
442
443         if(suffix.length > 0) {
444             newElement.append({text: suffix});
445         }
446         succeedingChildren.forEach(function(child) {
447             newElement.append(child);
448         });
449
450         return {first: parentElement, second: newElement};
451     },
452
453     triggerTextChangeEvent: function() {
454         var event = new events.ChangeEvent('nodeTextChange', {node: this});
455         this.document.trigger('change', event);
456     }
457 });
458
459
460 var parseXML = function(xml) {
461     return $($.trim(xml))[0];
462 };
463
464 var Document = function(xml) {
465     this.loadXML(xml);
466     this.undoStack = [];
467     this.redoStack = [];
468 };
469
470 $.extend(Document.prototype, Backbone.Events, {
471     ElementNodeFactory: ElementNode,
472     TextNodeFactory: TextNode,
473
474     createDocumentNode: function(from) {
475         if(!(from instanceof Node)) {
476             if(from.text !== undefined) {
477                 /* globals document */
478                 from = document.createTextNode(from.text);
479             } else {
480                 var node = $('<' + from.tagName + '>');
481
482                 _.keys(from.attrs || {}).forEach(function(key) {
483                     node.attr(key, from.attrs[key]);
484                 });
485
486                 from = node[0];
487             }
488         }
489         var Factory;
490         if(from.nodeType === Node.TEXT_NODE) {
491             Factory = this.TextNodeFactory;
492         } else if(from.nodeType === Node.ELEMENT_NODE) {
493             Factory = this.ElementNodeFactory;
494         }
495         return new Factory(from, this);
496     },
497
498     loadXML: function(xml, options) {
499         options = options || {};
500         defineDocumentProperties(this, $(parseXML(xml)));
501         if(!options.silent) {
502             this.trigger('contentSet');
503         }
504     },
505
506     toXML: function() {
507         return this.root.toXML();
508     },
509
510     containsNode: function(node) {
511         return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
512     },
513
514     wrapNodes: function(params) {
515         if(!(params.node1.parent().sameNode(params.node2.parent()))) {
516             throw new Error('Wrapping non-sibling nodes not supported.');
517         }
518
519         var parent = params.node1.parent(),
520             parentContents = parent.contents(),
521             wrapper = this.createDocumentNode({
522                 tagName: params._with.tagName,
523                 attrs: params._with.attrs}),
524             idx1 = parent.indexOf(params.node1),
525             idx2 = parent.indexOf(params.node2);
526
527         if(idx1 > idx2) {
528             var tmp = idx1;
529             idx1 = idx2;
530             idx2 = tmp;
531         }
532
533         var insertingMethod, insertingTarget;
534         if(idx1 === 0) {
535             insertingMethod = 'prepend';
536             insertingTarget = parent;
537         } else {
538             insertingMethod = 'after';
539             insertingTarget = parentContents[idx1-1];
540         }
541
542         for(var i = idx1; i <= idx2; i++) {
543             wrapper.append(parentContents[i].detach());
544         }
545
546         insertingTarget[insertingMethod](wrapper);
547         return wrapper;
548     },
549
550     getSiblingParents: function(params) {
551         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
552             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
553             noSiblingParents = null;
554
555         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
556             return noSiblingParents;
557         }
558
559         var i;
560         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
561             if(parents1[i].sameNode(parents2[i])) {
562                 continue;
563             }
564             break;
565         }
566         return {node1: parents1[i], node2: parents2[i]};
567     },
568
569     _wrapText: function(params) {
570         params = _.extend({textNodeIdx: 0}, params);
571         if(typeof params.textNodeIdx === 'number') {
572             params.textNodeIdx = [params.textNodeIdx];
573         }
574         
575         var contentsInside = params.inside.contents(),
576             idx1 = Math.min.apply(Math, params.textNodeIdx),
577             idx2 = Math.max.apply(Math, params.textNodeIdx),
578             textNode1 = contentsInside[idx1],
579             textNode2 = contentsInside[idx2],
580             sameNode = textNode1.sameNode(textNode2),
581             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
582             prefixInside = textNode1.getText().substr(params.offsetStart),
583             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
584             suffixOutside = textNode2.getText().substr(params.offsetEnd)
585         ;
586
587         if(!(textNode1.parent().sameNode(textNode2.parent()))) {
588             throw new Error('Wrapping text in non-sibling text nodes not supported.');
589         }
590         
591         var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
592         textNode1.after(wrapperElement);
593         textNode1.detach();
594         
595         if(prefixOutside.length > 0) {
596             wrapperElement.before({text:prefixOutside});
597         }
598         if(sameNode) {
599             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
600             wrapperElement.append({text: core});
601         } else {
602             textNode2.detach();
603             if(prefixInside.length > 0) {
604                 wrapperElement.append({text: prefixInside});
605             }
606             for(var i = idx1 + 1; i < idx2; i++) {
607                 wrapperElement.append(contentsInside[i]);
608             }
609             if(suffixInside.length > 0) {
610                 wrapperElement.append({text: suffixInside});
611             }
612         }
613         if(suffixOutside.length > 0) {
614             wrapperElement.after({text: suffixOutside});
615         }
616         return wrapperElement;
617     },
618
619     trigger: function() {
620         //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
621         Backbone.Events.trigger.apply(this, arguments);
622     },
623
624     getNodeInsertion: function(node) {
625         var insertion = {};
626         if(node instanceof DocumentNode) {
627             insertion.ofNode = node;
628             insertion.insertsNew = !this.containsNode(node);
629         } else {
630           insertion.ofNode = this.createDocumentNode(node);
631           insertion.insertsNew = true;
632         }
633         return insertion;
634     },
635
636     replaceRoot: function(node) {
637         var insertion = this.getNodeInsertion(node);
638         this.root.detach();
639         defineDocumentProperties(this, insertion.ofNode._$);
640         insertion.ofNode.triggerChangeEvent('nodeAdded');
641         return insertion.ofNode;
642     },
643
644     transform: function(transformationName, args) {
645         console.log('transform');
646         var Transformation = transformations[transformationName],
647             transformation;
648         if(Transformation) {
649             transformation = new Transformation(args);
650             transformation.run();
651             this.undoStack.push(transformation);
652             console.log('clearing redo stack');
653             this.redoStack = [];
654         } else {
655             throw new Error('Transformation ' + transformationName + ' doesn\'t exist!');
656         }
657     },
658     undo: function() {
659         var transformation = this.undoStack.pop();
660         if(transformation) {
661             transformation.undo();
662             this.redoStack.push(transformation);
663         }
664     },
665     redo: function() {
666         var transformation = this.redoStack.pop();
667         if(transformation) {
668             transformation.run();
669             this.undoStack.push(transformation);
670         }
671     },
672
673     getNodeByPath: function(path) {
674         var toret = this.root;
675         path.forEach(function(idx) {
676             toret = toret.contents()[idx];
677         });
678         return toret;
679     }
680 });
681
682 var defineDocumentProperties = function(doc, $document) {
683     Object.defineProperty(doc, 'root', {get: function() {
684         return doc.createDocumentNode($document[0]);
685     }, configurable: true});
686     Object.defineProperty(doc, 'dom', {get: function() {
687         return $document[0];
688     }, configurable: true});
689 };
690
691
692 // var registerTransformationsFromObject = function(object) {
693 //     _.values(object).filter(function(val) {
694 //         return typeof val === 'function' && val._isTransformation;
695 //     })
696 //     .forEach(function(val) {
697 //         registerTransformation(val._transformationName, val, object);
698 //     });
699 // };
700 // registerTransformationsFromObject(ElementNode.prototype);
701 // registerTransformationsFromObject(TextNode.prototype);
702 // registerTransformationsFromObject(Document.prototype);
703
704 // var Transformation = function() {
705 // };
706 // $.extend(Transformation.prototype, {
707
708 // });
709
710
711 // var createDumbTransformation = function(impl, contextObject) {
712 //     var DumbTransformation = function(args) {
713 //         this.args = this.args;
714 //     };
715 //     DumbTransformation.prototype = Object.create(Transformation.prototype);
716 //     $.extend(DumbTransformation.prototype, {
717 //         run: function() {
718 //             impl.apply(contextObject, this.args);
719 //         }
720 //     });
721
722 //     return DumbTransformation;
723
724
725 // };
726
727 var transformations = {};
728 // var registerTransformation = function(name, impl, contextObject) {
729 //     if(typeof impl === 'function') {
730 //         transformations[name] = createDumbTransformation(impl, contextObject);
731 //     }
732 // };
733
734 // registerTransformation('detachx', DocumentNode.prototype.detach,  )
735
736
737 // 1. detach via totalny fallback
738 var DetachNodeTransformation = function(args) {
739     this.node = args.node;
740     this.document = this.node.document;
741 };
742 $.extend(DetachNodeTransformation.prototype, {
743     run: function() {
744         this.oldRoot = this.node.document.root.clone();
745         this.path = this.node.getPath();
746         this.node.detach(); // @TS
747         
748     },
749     undo: function() {
750         this.document.root.replaceWith(this.oldRoot); // this.getDocument?
751         this.node = this.document.getNodeByPath(this.path);
752     }
753 });
754 transformations['detach'] = DetachNodeTransformation;
755
756 //2. detach via wskazanie changeroot
757
758 var Detach2NodeTransformation = function(args) {
759     this.nodePath = args.node.getPath();
760     this.document = args.node.document;
761 };
762 $.extend(Detach2NodeTransformation.prototype, {
763     run: function() {
764         var node = this.document.getNodeByPath(this.nodePath),
765             root = node.parent() ? node.parent() : this.document.root;
766         
767         this.rootPath = root.getPath();
768         this.oldRoot = (root).clone();
769         node.detach();
770     },
771     undo: function() {
772         this.document.getNodeByPath(this.rootPath).replaceWith(this.oldRoot);
773     }
774 });
775 //transformations['detach2'] = Detach2NodeTransformation;
776
777 //2a. generyczna transformacja
778
779 var createTransformation = function(desc) {
780
781     var NodeTransformation = function(args) {
782         this.nodePath = args.node.getPath();
783         this.document = args.node.document;
784         this.args = args;
785     };
786     $.extend(NodeTransformation.prototype, {
787         run: function() {
788             var node = this.document.getNodeByPath(this.nodePath),
789                 root;
790
791             if(desc.getRoot) {
792                 root = desc.getRoot(node);
793             } else {
794                 root = this.document.root;
795             }
796             
797             this.rootPath = root.getPath();
798             this.oldRoot = (root).clone();
799             desc.impl.call(node, this.args);
800         },
801         undo: function() {
802             this.document.getNodeByPath(this.rootPath).replaceWith(this.oldRoot);
803         }
804     });
805
806     return NodeTransformation;
807 }
808
809 transformations['detach2'] = createTransformation({
810     // impl: function() {
811     //     //this.setAttr('class', 'cite'); //  
812     // },
813     impl: ElementNode.prototype.detach,
814     getRoot: function(node) {
815         return node.parent();
816     }
817
818 });
819
820 transformations['setText'] = createTransformation({
821     impl: function(args) {
822         this.setText(args.text)
823     },
824     getRoot: function(node) {
825         return node;
826     }
827
828 });
829
830 //3. detach z pełnym własnym redo
831
832 var Detach3NodeTransformation = function(args) {
833     this.node = args.node;
834     this.document = this.node.document;
835 };
836 $.extend(Detach3NodeTransformation.prototype, {
837     run: function() {
838         //this.index = this.node.getIndex();
839         //this.parent = this.node.parent();
840         
841         this.path = this.node.getPath();
842         if(this.node.isSurroundedByTextElements()) {
843             this.prevText = this.node.prev().getText();
844             this.nextText = this.node.next().getText();
845             this.merge = true;
846         } else {
847             this.prevText = this.nextText = null;
848             this.merge = false;
849         }
850
851         this.node.detach();
852     },
853     undo: function() {
854         var parent = this.document.getNodeByPath(this.path.slice(0,-1)),
855             idx = _.last(this.path);
856         var inserted = parent.insertAtIndex(this.node, idx);
857         if(this.merge) {
858             if(inserted.next()) {
859                 inserted.before({text: this.prevText});
860                 inserted.next().setText(this.nextText);
861             } else {
862                 inserted.prev().setText(this.prevText);
863                 inserted.after({text: this.nextText});
864             }
865         }
866     }
867 });
868 transformations['detach3'] = Detach3NodeTransformation;
869
870 return {
871     documentFromXML: function(xml) {
872         return new Document(xml);
873     },
874
875     elementNodeFromXML: function(xml) {
876         return this.documentFromXML(xml).root;
877     },
878
879     Document: Document,
880     DocumentNode: DocumentNode,
881     ElementNode: ElementNode
882 };
883
884 });