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