a2dd0aa1427697b1cffbb17362293155b515f7e1
[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             shiftRange, 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             shiftRange = 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             }
199         }
200
201         var childrenLength = this.contents().length;
202         this.contents().forEach(function(child) {
203             this.before(child);
204         }.bind(this));
205
206         this.detach();
207
208         return {
209             element1: parent.contents()[myIdx + (shiftRange ? -1 : 0)],
210             element2: parent.contents()[myIdx + childrenLength-1 + (shiftRange ? -1 : 0)]
211         };
212     },
213
214     wrapText: function(params) {
215         return this.document._wrapText(_.extend({inside: this}, params));
216     }
217 };
218
219 var textNodeTransformations = {
220     setText: {
221         impl: function(t, text) {
222             t.oldText = this.getText();
223             this.nativeNode.data = text;
224             this.triggerTextChangeEvent();
225         },
226         undo: function(t) {
227             this.setText(t.oldText);
228         }
229     },
230
231     before: INSERTION(function(node) {
232         if(node.nodeType === Node.TEXT_NODE) {
233             this.prependText(node.getText());
234             return this;
235         } else {
236             return this.__super__.before(node, {silent:true});
237         }
238     }),
239
240     after: INSERTION(function(node) {
241         if(node.nodeType === Node.TEXT_NODE) {
242             this.appendText(node.getText());
243             return this;
244         } else {
245             return this.__super__.after(node, {silent:true});
246         }
247     }),
248
249     appendText: function(text) {
250         this.nativeNode.data = this.nativeNode.data + text;
251         this.triggerTextChangeEvent();
252     },
253
254     prependText: function(text) {
255         this.nativeNode.data = text + this.nativeNode.data;
256         this.triggerTextChangeEvent();
257     },
258
259     wrapWith: function(desc) {
260         if(typeof desc.start === 'number' && typeof desc.end === 'number') {
261             return this.document._wrapText({
262                 inside: this.parent(),
263                 textNodeIdx: this.parent().indexOf(this),
264                 offsetStart: Math.min(desc.start, desc.end),
265                 offsetEnd: Math.max(desc.start, desc.end),
266                 _with: {tagName: desc.tagName, attrs: desc.attrs}
267             });
268         } else {
269             return this.__super__.wrapWith.call(this, desc);
270         }
271     },
272
273     split: function(params) {
274         var parentElement = this.parent(),
275             passed = false,
276             succeedingChildren = [],
277             prefix = this.getText().substr(0, params.offset),
278             suffix = this.getText().substr(params.offset);
279
280         parentElement.contents().forEach(function(child) {
281             if(passed) {
282                 succeedingChildren.push(child);
283             }
284             if(child.sameNode(this)) {
285                 passed = true;
286             }
287         }.bind(this));
288
289         if(prefix.length > 0) {
290             this.setText(prefix);
291         }
292         else {
293             this.detach();
294         }
295
296         var attrs = {};
297         parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
298         var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
299         parentElement.after(newElement);
300
301         if(suffix.length > 0) {
302             newElement.append({text: suffix});
303         }
304         succeedingChildren.forEach(function(child) {
305             newElement.append(child);
306         });
307
308         return {first: parentElement, second: newElement};
309     },
310
311     divideWithElementNode: function(node, params) {
312         var insertion = this.getNodeInsertion(node),
313             myText = this.getText();
314
315         if(params.offset === myText.length) {
316             return this.after(node);
317         }
318         if(params.offset === 0) {
319             return this.before(node);
320         }
321
322         var lhsText = myText.substr(0, params.offset),
323             rhsText = myText.substr(params.offset),
324             rhsTextNode = this.document.createDocumentNode({text: rhsText});
325
326         this.setText(lhsText);
327         this.after(insertion.ofNode);
328         insertion.ofNode.after(rhsTextNode);
329         return insertion.ofNode;
330     }
331 };
332
333 var documentTransformations = {
334     wrapNodes: function(params) {
335         if(!(params.node1.parent().sameNode(params.node2.parent()))) {
336             throw new Error('Wrapping non-sibling nodes not supported.');
337         }
338
339         var parent = params.node1.parent(),
340             parentContents = parent.contents(),
341             wrapper = this.createDocumentNode({
342                 tagName: params._with.tagName,
343                 attrs: params._with.attrs}),
344             idx1 = parent.indexOf(params.node1),
345             idx2 = parent.indexOf(params.node2);
346
347         if(idx1 > idx2) {
348             var tmp = idx1;
349             idx1 = idx2;
350             idx2 = tmp;
351         }
352
353         var insertingMethod, insertingTarget;
354         if(idx1 === 0) {
355             insertingMethod = 'prepend';
356             insertingTarget = parent;
357         } else {
358             insertingMethod = 'after';
359             insertingTarget = parentContents[idx1-1];
360         }
361
362         for(var i = idx1; i <= idx2; i++) {
363             wrapper.append(parentContents[i].detach());
364         }
365
366         insertingTarget[insertingMethod](wrapper);
367         return wrapper;
368     },
369
370     _wrapText: function(params) {
371         params = _.extend({textNodeIdx: 0}, params);
372         if(typeof params.textNodeIdx === 'number') {
373             params.textNodeIdx = [params.textNodeIdx];
374         }
375         
376         var contentsInside = params.inside.contents(),
377             idx1 = Math.min.apply(Math, params.textNodeIdx),
378             idx2 = Math.max.apply(Math, params.textNodeIdx),
379             textNode1 = contentsInside[idx1],
380             textNode2 = contentsInside[idx2],
381             sameNode = textNode1.sameNode(textNode2),
382             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
383             prefixInside = textNode1.getText().substr(params.offsetStart),
384             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
385             suffixOutside = textNode2.getText().substr(params.offsetEnd)
386         ;
387
388         if(!(textNode1.parent().sameNode(textNode2.parent()))) {
389             throw new Error('Wrapping text in non-sibling text nodes not supported.');
390         }
391         
392         var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
393         textNode1.after(wrapperElement);
394         textNode1.detach();
395         
396         if(prefixOutside.length > 0) {
397             wrapperElement.before({text:prefixOutside});
398         }
399         if(sameNode) {
400             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
401             wrapperElement.append({text: core});
402         } else {
403             textNode2.detach();
404             if(prefixInside.length > 0) {
405                 wrapperElement.append({text: prefixInside});
406             }
407             for(var i = idx1 + 1; i < idx2; i++) {
408                 wrapperElement.append(contentsInside[i]);
409             }
410             if(suffixInside.length > 0) {
411                 wrapperElement.append({text: suffixInside});
412             }
413         }
414         if(suffixOutside.length > 0) {
415             wrapperElement.after({text: suffixOutside});
416         }
417         return wrapperElement;
418     },
419     replaceRoot: function(node) {
420         var insertion = this.getNodeInsertion(node);
421         this.root.detach();
422         this._defineDocumentProperties(insertion.ofNode._$);
423         insertion.ofNode.triggerChangeEvent('nodeAdded');
424         return insertion.ofNode;
425     }
426 };
427
428 return {
429     document: {
430         transformations: documentTransformations
431     },
432     documentNode: {
433         transformations: documentNodeTransformations
434     },
435     elementNode: {
436         transformations: elementNodeTransformations
437     },
438     textNode: {
439         transformations: textNodeTransformations
440     }
441 };
442
443 });