smartxml: fix detaching element node with adjacent text nodes
[fnpeditor.git] / src / smartxml / smartxml.js
1 define([
2     'libs/jquery',
3     'libs/underscore',
4     'libs/backbone',
5     'smartxml/events'
6 ], function($, _, Backbone, events) {
7     
8 'use strict';
9
10
11 var TEXT_NODE = Node.TEXT_NODE;
12
13
14 var INSERTION = function(implementation) {
15     var toret = function(node) {
16         var insertion = this.getNodeInsertion(node);
17         implementation.call(this, insertion.ofNode.nativeNode);
18         this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
19         return insertion.ofNode;
20     };
21     return toret;
22 };
23
24 var DocumentNode = function(nativeNode, document) {
25     if(!document) {
26         throw new Error('undefined document for a node');
27     }
28     this.document = document;
29     this._setNativeNode(nativeNode);
30
31 };
32
33 $.extend(DocumentNode.prototype, {
34     _setNativeNode: function(nativeNode) {
35         this.nativeNode = nativeNode;
36         this._$ = $(nativeNode);
37     },
38
39     isRoot: function() {
40         return this.document.root.sameNode(this);
41     },
42
43     detach: function() {
44         var parent = this.parent();
45         this._$.detach();
46         this.triggerChangeEvent('nodeDetached', {parent: parent});
47         return this;
48     },
49
50     sameNode: function(otherNode) {
51         return otherNode && this.nativeNode === otherNode.nativeNode;
52     },
53
54     parent: function() {
55         var parentNode = this.nativeNode.parentNode;
56         if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
57             return this.document.createElementNode(parentNode);
58         }
59         return null;
60     },
61
62     parents: function() {
63         var parent = this.parent(),
64             parents = parent ? parent.parents() : [];
65         if(parent) {
66             parents.unshift(parent);
67         }
68         return parents;
69     },
70
71     prev: function() {
72         var myIdx = this.getIndex();
73         return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
74     },
75
76     next: function() {
77         if(this.isRoot()) {
78             return null;
79         }
80         var myIdx = this.getIndex(),
81             parentContents = this.parent().contents();
82         return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
83     },
84
85     after: INSERTION(function(nativeNode) {
86         return this._$.after(nativeNode);
87     }),
88
89     before: INSERTION(function(nativeNode) {
90         return this._$.before(nativeNode);
91     }),
92
93     wrapWith: function(node) {
94         node = node instanceof ElementNode ? node : this.document.createElementNode(node);
95
96         if(this.parent()) {
97             this.before(node);
98         }
99         node.append(this);
100         return node;
101     },
102
103     triggerChangeEvent: function(type, metaData) {
104         var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
105         if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
106             this.document.trigger('change', event);
107         }
108     },
109     
110     getNodeInsertion: function(node) {
111         var insertion = {};
112         if(node instanceof DocumentNode) {
113             insertion.ofNode = node;
114             insertion.insertsNew = !this.document.containsNode(node);
115         } else {
116           insertion.ofNode = this.document.createElementNode(node);
117           insertion.insertsNew = true;
118         }
119         return insertion;
120     },
121
122     getIndex: function() {
123         return this.parent().indexOf(this);
124     }
125 });
126
127 var ElementNode = function(nativeNode, document) {
128     DocumentNode.call(this, nativeNode, document);
129 };
130 ElementNode.prototype = Object.create(DocumentNode.prototype);
131
132 $.extend(ElementNode.prototype, {
133     nodeType: Node.ELEMENT_NODE,
134
135     detach: function() {
136         var prev = this.prev(),
137             next = this.next();
138         if(parent) {
139             if(prev && prev.nodeType === Node.TEXT_NODE && next && next.nodeType === Node.TEXT_NODE) {
140                 prev.appendText(next.getText());
141                 next.detach();
142             }
143         }
144         return DocumentNode.prototype.detach.call(this);
145     },
146
147     setData: function(key, value) {
148         if(value !== undefined) {
149             this._$.data(key, value);
150         } else {
151             this._$.removeData(_.keys(this._$.data()));
152             this._$.data(key);
153         }
154     },
155
156     getData: function(key) {
157         if(key) {
158             return this._$.data(key);
159         }
160         return this._$.data();
161     },
162
163     getTagName: function() {
164         return this.nativeNode.tagName.toLowerCase();
165     },
166
167     contents: function() {
168         var toret = [],
169             document = this.document;
170         this._$.contents().each(function() {
171             if(this.nodeType === Node.ELEMENT_NODE) {
172                 toret.push(document.createElementNode(this));
173             }
174             else if(this.nodeType === Node.TEXT_NODE) {
175                 toret.push(document.createTextNode(this));
176             }
177         });
178         return toret;
179     },
180
181     indexOf: function(node) {
182         return this._$.contents().index(node._$);
183     },
184
185     setTag: function(tagName) {
186         var node = this.document.createElementNode({tagName: tagName}),
187             oldTagName = this.getTagName(),
188             myContents = this._$.contents();
189
190         this.getAttrs().forEach(function(attribute) {
191             node.setAttr(attribute.name, attribute.value, true);
192         });
193         node.setData(this.getData());
194
195         if(this.sameNode(this.document.root)) {
196             defineDocumentProperties(this.document, node._$);
197         }
198         this._$.replaceWith(node._$);
199         this._setNativeNode(node._$[0]);
200         this._$.append(myContents);
201         this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
202     },
203
204     getAttr: function(name) {
205         return this._$.attr(name);
206     },
207
208     setAttr: function(name, value, silent) {
209         var oldVal = this.getAttr(name);
210         this._$.attr(name, value);
211         if(!silent) {
212             this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
213         }
214     },
215
216     getAttrs: function() {
217         var toret = [];
218         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
219             toret.push(this.nativeNode.attributes[i]);
220         }
221         return toret;
222     },
223
224     append: INSERTION(function(nativeNode) {
225         this._$.append(nativeNode);
226     }),
227
228     prepend: INSERTION(function(nativeNode) {
229         this._$.prepend(nativeNode);
230     }),
231
232     unwrapContent: function() {
233         var parent = this.parent();
234         if(!parent) {
235             return;
236         }
237
238         var parentContents = parent.contents(),
239             myContents = this.contents(),
240             myIdx = parent.indexOf(this);
241
242         if(myContents.length === 0) {
243             return this.detach();
244         }
245
246         var moveLeftRange, moveRightRange, leftMerged;
247
248         if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
249             parentContents[myIdx-1].appendText(myContents[0].getText());
250             myContents[0].detach();
251             moveLeftRange = true;
252             leftMerged = true;
253         } else {
254             leftMerged = false;
255         }
256
257         if(!(leftMerged && myContents.length === 1)) {
258             if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
259                 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
260                 myContents[myContents.length-1].detach();
261                 moveRightRange = true;
262             }
263         }
264
265         var childrenLength = this.contents().length;
266         this.contents().forEach(function(child) {
267             this.before(child);
268         }.bind(this));
269
270         this.detach();
271
272         return {
273             element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
274             element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
275         };
276     },
277
278     /**
279     * Removes parent of a node if node has no siblings.
280     */
281     unwrap: function() {
282         if(this.isRoot()) {
283             return;
284         }
285         var parent = this.parent(),
286             grandParent;
287         if(parent.contents().length === 1) {
288             grandParent = parent.parent();
289             parent.unwrapContent();
290             return grandParent;
291         }
292     },
293
294     wrapText: function(params) {
295         return this.document._wrapText(_.extend({inside: this}, params));
296     },
297
298     toXML: function() {
299         var wrapper = $('<div>');
300         wrapper.append(this._getXMLDOMToDump());
301         return wrapper.html();
302     },
303     
304     _getXMLDOMToDump: function() {
305         return this._$;
306     }
307 });
308
309 var TextNode = function(nativeNode, document) {
310     DocumentNode.call(this, nativeNode, document);
311 };
312 TextNode.prototype = Object.create(DocumentNode.prototype);
313
314 $.extend(TextNode.prototype, {
315     nodeType: Node.TEXT_NODE,
316
317     getText: function() {
318         return this.nativeNode.data;
319     },
320
321     setText: function(text) {
322         this.nativeNode.data = text;
323         this.triggerTextChangeEvent();
324     },
325
326     appendText: function(text) {
327         this.nativeNode.data = this.nativeNode.data + text;
328         this.triggerTextChangeEvent();
329     },
330
331     prependText: function(text) {
332         this.nativeNode.data = text + this.nativeNode.data;
333         this.triggerTextChangeEvent();
334     },
335
336     wrapWith: function(desc) {
337         if(typeof desc.start === 'number' && typeof desc.end === 'number') {
338             return this.document._wrapText({
339                 inside: this.parent(),
340                 textNodeIdx: this.parent().indexOf(this),
341                 offsetStart: Math.min(desc.start, desc.end),
342                 offsetEnd: Math.max(desc.start, desc.end),
343                 _with: {tagName: desc.tagName, attrs: desc.attrs}
344             });
345         } else {
346             return DocumentNode.prototype.wrapWith.call(this, desc);
347         }
348     },
349
350     triggerTextChangeEvent: function() {
351         var event = new events.ChangeEvent('nodeTextChange', {node: this});
352         this.document.trigger('change', event);
353     }
354 });
355
356
357 var parseXML = function(xml) {
358     return $(xml)[0];
359 };
360
361 var Document = function(xml) {
362     this.loadXML(xml);
363 };
364
365 $.extend(Document.prototype, Backbone.Events, {
366     ElementNodeFactory: ElementNode,
367     TextNodeFactory: TextNode,
368
369     createElementNode: function(from) {
370         if(!(from instanceof HTMLElement)) {
371             if(from.text) {
372                 from = document.createTextNode(from.text);
373             } else {
374                 var node = $('<' + from.tagName + '>');
375
376                 _.keys(from.attrs || {}).forEach(function(key) {
377                     node.attr(key, from.attrs[key]);
378                 });
379
380                 from = node[0];
381             }
382         }
383         var Factory;
384         if(from.nodeType === Node.TEXT_NODE) {
385             Factory = this.TextNodeFactory;
386         } else if(from.nodeType === Node.ELEMENT_NODE) {
387             Factory = this.ElementNodeFactory;
388         }
389         return new Factory(from, this);
390     },
391
392     createTextNode: function(nativeNode) {
393         return new this.TextNodeFactory(nativeNode, this);
394     },
395
396     loadXML: function(xml, options) {
397         options = options || {};
398         defineDocumentProperties(this, $(parseXML(xml)));
399         if(!options.silent) {
400             this.trigger('contentSet');
401         }
402     },
403
404     toXML: function() {
405         return this.root.toXML();
406     },
407
408     containsNode: function(node) {
409         return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
410     },
411
412     wrapNodes: function(params) {
413         if(!(params.element1.parent().sameNode(params.element2.parent()))) {
414             throw new Error('Wrapping non-sibling nodes not supported.');
415         }
416
417         var parent = params.element1.parent(),
418             parentContents = parent.contents(),
419             wrapper = this.createElementNode({
420                 tagName: params._with.tagName,
421                 attrs: params._with.attrs}),
422             idx1 = parent.indexOf(params.element1),
423             idx2 = parent.indexOf(params.element2);
424
425         if(idx1 > idx2) {
426             var tmp = idx1;
427             idx1 = idx2;
428             idx2 = tmp;
429         }
430
431         var insertingMethod, insertingTarget;
432         if(idx1 === 0) {
433             insertingMethod = 'prepend';
434             insertingTarget = parent;
435         } else {
436             insertingMethod = 'after';
437             insertingTarget = parentContents[idx1-1];
438         }
439
440         for(var i = idx1; i <= idx2; i++) {
441             wrapper.append(parentContents[i].detach());
442         }
443
444         insertingTarget[insertingMethod](wrapper);
445         return wrapper;
446     },
447
448     getSiblingParents: function(params) {
449         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
450             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
451             noSiblingParents = null;
452
453         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
454             return noSiblingParents;
455         }
456
457         var i;
458         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
459             if(parents1[i].sameNode(parents2[i])) {
460                 continue;
461             }
462             break;
463         }
464         return {node1: parents1[i], node2: parents2[i]};
465     },
466
467     _wrapText: function(params) {
468         params = _.extend({textNodeIdx: 0}, params);
469         if(typeof params.textNodeIdx === 'number') {
470             params.textNodeIdx = [params.textNodeIdx];
471         }
472         
473         var contentsInside = params.inside.contents(),
474             idx1 = Math.min.apply(Math, params.textNodeIdx),
475             idx2 = Math.max.apply(Math, params.textNodeIdx),
476             textNode1 = contentsInside[idx1],
477             textNode2 = contentsInside[idx2],
478             sameNode = textNode1.sameNode(textNode2),
479             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
480             prefixInside = textNode1.getText().substr(params.offsetStart),
481             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
482             suffixOutside = textNode2.getText().substr(params.offsetEnd)
483         ;
484
485         if(!(textNode1.parent().sameNode(textNode2.parent()))) {
486             throw new Error('Wrapping text in non-sibling text nodes not supported.');
487         }
488         
489         var wrapperElement = this.createElementNode({tagName: params._with.tagName, attrs: params._with.attrs});
490         textNode1.after(wrapperElement);
491         textNode1.detach();
492         
493         if(prefixOutside.length > 0) {
494             wrapperElement.before({text:prefixOutside});
495         }
496         if(sameNode) {
497             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
498             wrapperElement.append({text: core});
499         } else {
500             textNode2.detach();
501             if(prefixInside.length > 0) {
502                 wrapperElement.append({text: prefixInside});
503             }
504             for(var i = idx1 + 1; i < idx2; i++) {
505                 wrapperElement.append(contentsInside[i]);
506             }
507             if(suffixInside.length > 0) {
508                 wrapperElement.append({text: suffixInside});
509             }
510         }
511         if(suffixOutside.length > 0) {
512             wrapperElement.after({text: suffixOutside});
513         }
514         return wrapperElement;
515     },
516
517     trigger: function() {
518         //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
519         Backbone.Events.trigger.apply(this, arguments);
520     }
521 });
522
523 var defineDocumentProperties = function(doc, $document) {
524     Object.defineProperty(doc, 'root', {get: function() {
525         return doc.createElementNode($document[0]);
526     }, configurable: true});
527     Object.defineProperty(doc, 'dom', {get: function() {
528         return $document[0];
529     }, configurable: true});
530 };
531
532 return {
533     documentFromXML: function(xml) {
534         return new Document(parseXML(xml));
535     },
536
537     elementNodeFromXML: function(xml) {
538         return this.documentFromXML(xml).root;
539     },
540
541     Document: Document,
542     DocumentNode: DocumentNode,
543     ElementNode: ElementNode
544 };
545
546 });