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