10d058f2665f1ec97de979f4b8ed8d1c2fd9e2e5
[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         this._$.replaceWith(node._$);
103         this._setNativeNode(node._$[0]);
104         this._$.append(myContents);
105         this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
106     },
107
108
109     setAttr: function(name, value, silent) {
110         var oldVal = this.getAttr(name);
111         this._$.attr(name, value);
112         if(!silent) {
113             this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
114         }
115     },
116
117     append: INSERTION(function(nativeNode) {
118         this._$.append(nativeNode);
119     }),
120
121     prepend: INSERTION(function(nativeNode) {
122         this._$.prepend(nativeNode);
123     }),
124
125     insertAtIndex: function(nativeNode, index) {
126         var contents = this.contents();
127         if(index < contents.length) {
128             return contents[index].before(nativeNode);
129         } else if(index === contents.length) {
130             return this.append(nativeNode);
131         }
132     },
133
134     unwrapContent: function() {
135         var parent = this.parent();
136         if(!parent) {
137             return;
138         }
139
140         var myContents = this.contents(),
141             myIdx = parent.indexOf(this);
142
143
144         if(myContents.length === 0) {
145             return this.detach();
146         }
147
148         var prev = this.prev(),
149             next = this.next(),
150             moveLeftRange, moveRightRange, leftMerged;
151
152         if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
153             prev.appendText(myContents[0].getText());
154             myContents[0].detach();
155             moveLeftRange = true;
156             leftMerged = true;
157         } else {
158             leftMerged = false;
159         }
160
161         if(!(leftMerged && myContents.length === 1)) {
162             var lastContents = _.last(myContents);
163             if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
164                 next.prependText(lastContents.getText());
165                 lastContents.detach();
166                 moveRightRange = true;
167             }
168         }
169
170         var childrenLength = this.contents().length;
171         this.contents().forEach(function(child) {
172             this.before(child);
173         }.bind(this));
174
175         this.detach();
176
177         return {
178             element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
179             element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
180         };
181     },
182
183     wrapText: function(params) {
184         return this.document._wrapText(_.extend({inside: this}, params));
185     }
186 };
187
188 var textNodeTransformations = {
189     setText: function(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     divideWithElementNode: function(node, params) {
257         var insertion = this.getNodeInsertion(node),
258             myText = this.getText();
259
260         if(params.offset === myText.length) {
261             return this.after(node);
262         }
263         if(params.offset === 0) {
264             return this.before(node);
265         }
266
267         var lhsText = myText.substr(0, params.offset),
268             rhsText = myText.substr(params.offset),
269             rhsTextNode = this.document.createDocumentNode({text: rhsText});
270
271         this.setText(lhsText);
272         this.after(insertion.ofNode);
273         insertion.ofNode.after(rhsTextNode);
274         return insertion.ofNode;
275     }
276 };
277
278 var documentTransformations = {
279     wrapNodes: function(params) {
280         if(!(params.node1.parent().sameNode(params.node2.parent()))) {
281             throw new Error('Wrapping non-sibling nodes not supported.');
282         }
283
284         var parent = params.node1.parent(),
285             parentContents = parent.contents(),
286             wrapper = this.createDocumentNode({
287                 tagName: params._with.tagName,
288                 attrs: params._with.attrs}),
289             idx1 = parent.indexOf(params.node1),
290             idx2 = parent.indexOf(params.node2);
291
292         if(idx1 > idx2) {
293             var tmp = idx1;
294             idx1 = idx2;
295             idx2 = tmp;
296         }
297
298         var insertingMethod, insertingTarget;
299         if(idx1 === 0) {
300             insertingMethod = 'prepend';
301             insertingTarget = parent;
302         } else {
303             insertingMethod = 'after';
304             insertingTarget = parentContents[idx1-1];
305         }
306
307         for(var i = idx1; i <= idx2; i++) {
308             wrapper.append(parentContents[i].detach());
309         }
310
311         insertingTarget[insertingMethod](wrapper);
312         return wrapper;
313     },
314
315     _wrapText: function(params) {
316         params = _.extend({textNodeIdx: 0}, params);
317         if(typeof params.textNodeIdx === 'number') {
318             params.textNodeIdx = [params.textNodeIdx];
319         }
320         
321         var contentsInside = params.inside.contents(),
322             idx1 = Math.min.apply(Math, params.textNodeIdx),
323             idx2 = Math.max.apply(Math, params.textNodeIdx),
324             textNode1 = contentsInside[idx1],
325             textNode2 = contentsInside[idx2],
326             sameNode = textNode1.sameNode(textNode2),
327             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
328             prefixInside = textNode1.getText().substr(params.offsetStart),
329             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
330             suffixOutside = textNode2.getText().substr(params.offsetEnd)
331         ;
332
333         if(!(textNode1.parent().sameNode(textNode2.parent()))) {
334             throw new Error('Wrapping text in non-sibling text nodes not supported.');
335         }
336         
337         var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
338         textNode1.after(wrapperElement);
339         textNode1.detach();
340         
341         if(prefixOutside.length > 0) {
342             wrapperElement.before({text:prefixOutside});
343         }
344         if(sameNode) {
345             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
346             wrapperElement.append({text: core});
347         } else {
348             textNode2.detach();
349             if(prefixInside.length > 0) {
350                 wrapperElement.append({text: prefixInside});
351             }
352             for(var i = idx1 + 1; i < idx2; i++) {
353                 wrapperElement.append(contentsInside[i]);
354             }
355             if(suffixInside.length > 0) {
356                 wrapperElement.append({text: suffixInside});
357             }
358         }
359         if(suffixOutside.length > 0) {
360             wrapperElement.after({text: suffixOutside});
361         }
362         return wrapperElement;
363     },
364     replaceRoot: function(node) {
365         var insertion = this.getNodeInsertion(node);
366         this.root.detach();
367         this._defineDocumentProperties(insertion.ofNode._$);
368         insertion.ofNode.triggerChangeEvent('nodeAdded');
369         return insertion.ofNode;
370     }
371 };
372
373 return {
374     document: {
375         transformations: documentTransformations
376     },
377     documentNode: {
378         transformations: documentNodeTransformations
379     },
380     elementNode: {
381         transformations: elementNodeTransformations
382     },
383     textNode: {
384         transformations: textNodeTransformations
385     }
386 };
387
388 });