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