smartxml: implementing merging of inserted text nodes if necessary
[fnpeditor.git] / src / smartxml / core.js
1 define(function(require) {
2     
3 'use strict';
4 /* globals Node */
5
6 var _ = require('libs/underscore'),
7     TEXT_NODE = Node.TEXT_NODE;
8
9
10 var INSERTION = function(implementation) {
11     var toret = function(node, options) {
12         var insertion = this.getNodeInsertion(node),
13             nodeWasContained = this.document.containsNode(insertion.ofNode),
14             nodeParent,
15             returned;
16         options = options || {};
17         if(!(this.document.containsNode(this))) {
18             nodeParent = insertion.ofNode.parent();
19         }
20         returned = implementation.call(this, insertion.ofNode);
21         if(!options.silent && returned.sameNode(insertion.ofNode)) {
22             this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode}, nodeParent, nodeWasContained);
23         }
24         return returned;
25     };
26     return toret;
27 };
28
29 var documentNodeTransformations = {
30     detach: function() {
31         var parent = this.parent();
32         this._$.detach();
33         this.triggerChangeEvent('nodeDetached', {parent: parent});
34         return this;
35     },
36
37     replaceWith: function(node) {
38         var toret;
39         if(this.isRoot()) {
40             return this.document.replaceRoot(node);
41         }
42         toret = this.after(node);
43         this.detach();
44         return toret;
45     },
46
47     after: INSERTION(function(node) {
48         var next = this.next();
49         if(next && next.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
50             next.setText(node.getText() + next.getText());
51             return next;
52         }
53         this._$.after(node.nativeNode);
54         return node;
55     }),
56
57     before: INSERTION(function(node) {
58         var prev = this.prev();
59         if(prev && prev.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
60             prev.setText(prev.getText() + node.getText());
61             return prev;
62         }
63         this._$.before(node.nativeNode);
64         return node;
65     }),
66
67     wrapWith: function(node) {
68         var insertion = this.getNodeInsertion(node);
69         if(this.parent()) {
70             this.before(insertion.ofNode);
71         }
72         insertion.ofNode.append(this);
73         return insertion.ofNode;
74     },
75
76     /**
77     * Removes parent of a node if node has no siblings.
78     */
79     unwrap: function() {
80         if(this.isRoot()) {
81             return;
82         }
83         var parent = this.parent(),
84             grandParent;
85         if(parent.contents().length === 1) {
86             grandParent = parent.parent();
87             parent.unwrapContent();
88             return grandParent;
89         }
90     }
91 };
92
93 var elementNodeTransformations = {
94
95     detach: function() {
96         var next;
97         if(this.parent() && this.isSurroundedByTextElements()) {
98             next = this.next();
99             this.prev().appendText(next.getText());
100             next.detach();
101         }
102         return this.__super__.detach();
103     },
104
105     setTag: function(tagName) {
106         var node = this.document.createDocumentNode({tagName: tagName}),
107             oldTagName = this.getTagName(),
108             myContents = this._$.contents();
109
110         this.getAttrs().forEach(function(attribute) {
111             node.setAttr(attribute.name, attribute.value, true);
112         });
113         node.setData(this.getData());
114
115         if(this.sameNode(this.document.root)) {
116             this.document._defineDocumentProperties(node._$);
117         }
118
119         /* TODO: This invalidates old references to this node. Caching instances on nodes would fix this. */
120         this._$.replaceWith(node._$);
121         this._setNativeNode(node._$[0]);
122         this._$.append(myContents);
123         this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
124     },
125
126
127     setAttr: function(name, value, silent) {
128         var oldVal = this.getAttr(name);
129         this._$.attr(name, value);
130         if(!silent) {
131             this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
132         }
133     },
134
135     append: INSERTION(function(node) {
136         var last = _.last(this.contents());
137         if(last && last.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
138             last.setText(last.getText() + node.getText());
139             return last;
140         } else {
141             this._$.append(node.nativeNode);
142             return node;
143         }
144     }),
145
146     prepend: INSERTION(function(node) {
147         var first = this.contents()[0];
148         if(first && first.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
149             first.setText(node.getText() + first.getText());
150             return first;
151         } else {
152             this._$.prepend(node.nativeNode);
153             return node;
154         }
155     }),
156
157     insertAtIndex: function(nativeNode, index) {
158         var contents = this.contents();
159         if(index < contents.length) {
160             return contents[index].before(nativeNode);
161         } else if(index === contents.length) {
162             return this.append(nativeNode);
163         }
164     },
165
166     unwrapContent: function() {
167         var parent = this.parent();
168         if(!parent) {
169             return;
170         }
171
172         var myContents = this.contents(),
173             myIdx = parent.indexOf(this);
174
175
176         if(myContents.length === 0) {
177             return this.detach();
178         }
179
180         var prev = this.prev(),
181             next = this.next(),
182             moveLeftRange, moveRightRange, leftMerged;
183
184         if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
185             prev.appendText(myContents[0].getText());
186             myContents[0].detach();
187             moveLeftRange = true;
188             leftMerged = true;
189         } else {
190             leftMerged = false;
191         }
192
193         if(!(leftMerged && myContents.length === 1)) {
194             var lastContents = _.last(myContents);
195             if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
196                 next.prependText(lastContents.getText());
197                 lastContents.detach();
198                 moveRightRange = true;
199             }
200         }
201
202         var childrenLength = this.contents().length;
203         this.contents().forEach(function(child) {
204             this.before(child);
205         }.bind(this));
206
207         this.detach();
208
209         return {
210             element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
211             element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
212         };
213     },
214
215     wrapText: function(params) {
216         return this.document._wrapText(_.extend({inside: this}, params));
217     }
218 };
219
220 var textNodeTransformations = {
221     setText: {
222         impl: function(t, text) {
223             t.oldText = this.getText();
224             this.nativeNode.data = text;
225             this.triggerTextChangeEvent();
226         },
227         undo: function(t) {
228             this.setText(t.oldText);
229         }
230     },
231
232     before: INSERTION(function(node) {
233         if(node.nodeType === Node.TEXT_NODE) {
234             this.prependText(node.getText());
235             return this;
236         } else {
237             return this.__super__.before(node, {silent:true});
238         }
239     }),
240
241     after: INSERTION(function(node) {
242         if(node.nodeType === Node.TEXT_NODE) {
243             this.appendText(node.getText());
244             return this;
245         } else {
246             return this.__super__.after(node, {silent:true});
247         }
248     }),
249
250     appendText: function(text) {
251         this.nativeNode.data = this.nativeNode.data + text;
252         this.triggerTextChangeEvent();
253     },
254
255     prependText: function(text) {
256         this.nativeNode.data = text + this.nativeNode.data;
257         this.triggerTextChangeEvent();
258     },
259
260     wrapWith: function(desc) {
261         if(typeof desc.start === 'number' && typeof desc.end === 'number') {
262             return this.document._wrapText({
263                 inside: this.parent(),
264                 textNodeIdx: this.parent().indexOf(this),
265                 offsetStart: Math.min(desc.start, desc.end),
266                 offsetEnd: Math.max(desc.start, desc.end),
267                 _with: {tagName: desc.tagName, attrs: desc.attrs}
268             });
269         } else {
270             return this.__super__.wrapWith.call(this, desc);
271         }
272     },
273
274     split: function(params) {
275         var parentElement = this.parent(),
276             passed = false,
277             succeedingChildren = [],
278             prefix = this.getText().substr(0, params.offset),
279             suffix = this.getText().substr(params.offset);
280
281         parentElement.contents().forEach(function(child) {
282             if(passed) {
283                 succeedingChildren.push(child);
284             }
285             if(child.sameNode(this)) {
286                 passed = true;
287             }
288         }.bind(this));
289
290         if(prefix.length > 0) {
291             this.setText(prefix);
292         }
293         else {
294             this.detach();
295         }
296
297         var attrs = {};
298         parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
299         var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
300         parentElement.after(newElement);
301
302         if(suffix.length > 0) {
303             newElement.append({text: suffix});
304         }
305         succeedingChildren.forEach(function(child) {
306             newElement.append(child);
307         });
308
309         return {first: parentElement, second: newElement};
310     },
311
312     divideWithElementNode: function(node, params) {
313         var insertion = this.getNodeInsertion(node),
314             myText = this.getText();
315
316         if(params.offset === myText.length) {
317             return this.after(node);
318         }
319         if(params.offset === 0) {
320             return this.before(node);
321         }
322
323         var lhsText = myText.substr(0, params.offset),
324             rhsText = myText.substr(params.offset),
325             rhsTextNode = this.document.createDocumentNode({text: rhsText});
326
327         this.setText(lhsText);
328         this.after(insertion.ofNode);
329         insertion.ofNode.after(rhsTextNode);
330         return insertion.ofNode;
331     }
332 };
333
334 var documentTransformations = {
335     wrapNodes: function(params) {
336         if(!(params.node1.parent().sameNode(params.node2.parent()))) {
337             throw new Error('Wrapping non-sibling nodes not supported.');
338         }
339
340         var parent = params.node1.parent(),
341             parentContents = parent.contents(),
342             wrapper = this.createDocumentNode({
343                 tagName: params._with.tagName,
344                 attrs: params._with.attrs}),
345             idx1 = parent.indexOf(params.node1),
346             idx2 = parent.indexOf(params.node2);
347
348         if(idx1 > idx2) {
349             var tmp = idx1;
350             idx1 = idx2;
351             idx2 = tmp;
352         }
353
354         var insertingMethod, insertingTarget;
355         if(idx1 === 0) {
356             insertingMethod = 'prepend';
357             insertingTarget = parent;
358         } else {
359             insertingMethod = 'after';
360             insertingTarget = parentContents[idx1-1];
361         }
362
363         for(var i = idx1; i <= idx2; i++) {
364             wrapper.append(parentContents[i].detach());
365         }
366
367         insertingTarget[insertingMethod](wrapper);
368         return wrapper;
369     },
370
371     _wrapText: function(params) {
372         params = _.extend({textNodeIdx: 0}, params);
373         if(typeof params.textNodeIdx === 'number') {
374             params.textNodeIdx = [params.textNodeIdx];
375         }
376         
377         var contentsInside = params.inside.contents(),
378             idx1 = Math.min.apply(Math, params.textNodeIdx),
379             idx2 = Math.max.apply(Math, params.textNodeIdx),
380             textNode1 = contentsInside[idx1],
381             textNode2 = contentsInside[idx2],
382             sameNode = textNode1.sameNode(textNode2),
383             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
384             prefixInside = textNode1.getText().substr(params.offsetStart),
385             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
386             suffixOutside = textNode2.getText().substr(params.offsetEnd)
387         ;
388
389         if(!(textNode1.parent().sameNode(textNode2.parent()))) {
390             throw new Error('Wrapping text in non-sibling text nodes not supported.');
391         }
392         
393         var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
394         textNode1.after(wrapperElement);
395         textNode1.detach();
396         
397         if(prefixOutside.length > 0) {
398             wrapperElement.before({text:prefixOutside});
399         }
400         if(sameNode) {
401             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
402             wrapperElement.append({text: core});
403         } else {
404             textNode2.detach();
405             if(prefixInside.length > 0) {
406                 wrapperElement.append({text: prefixInside});
407             }
408             for(var i = idx1 + 1; i < idx2; i++) {
409                 wrapperElement.append(contentsInside[i]);
410             }
411             if(suffixInside.length > 0) {
412                 wrapperElement.append({text: suffixInside});
413             }
414         }
415         if(suffixOutside.length > 0) {
416             wrapperElement.after({text: suffixOutside});
417         }
418         return wrapperElement;
419     },
420     replaceRoot: function(node) {
421         var insertion = this.getNodeInsertion(node);
422         this.root.detach();
423         this._defineDocumentProperties(insertion.ofNode._$);
424         insertion.ofNode.triggerChangeEvent('nodeAdded');
425         return insertion.ofNode;
426     }
427 };
428
429 return {
430     document: {
431         transformations: documentTransformations
432     },
433     documentNode: {
434         transformations: documentNodeTransformations
435     },
436     elementNode: {
437         transformations: elementNodeTransformations
438     },
439     textNode: {
440         transformations: textNodeTransformations
441     }
442 };
443
444 });