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