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