smartxml: handle insertAtIndex when index out of range
[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(index < contents.length) {
278             return contents[index].before(nativeNode);
279         } else if(index === contents.length) {
280             return this.append(nativeNode);
281         }
282     },
283
284     unwrapContent: function() {
285         var parent = this.parent();
286         if(!parent) {
287             return;
288         }
289
290         var myContents = this.contents(),
291             myIdx = parent.indexOf(this);
292
293
294         if(myContents.length === 0) {
295             return this.detach();
296         }
297
298         var prev = this.prev(),
299             next = this.next(),
300             moveLeftRange, moveRightRange, leftMerged;
301
302         if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
303             prev.appendText(myContents[0].getText());
304             myContents[0].detach();
305             moveLeftRange = true;
306             leftMerged = true;
307         } else {
308             leftMerged = false;
309         }
310
311         if(!(leftMerged && myContents.length === 1)) {
312             var lastContents = _.last(myContents);
313             if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
314                 next.prependText(lastContents.getText());
315                 lastContents.detach();
316                 moveRightRange = true;
317             }
318         }
319
320         var childrenLength = this.contents().length;
321         this.contents().forEach(function(child) {
322             this.before(child);
323         }.bind(this));
324
325         this.detach();
326
327         return {
328             element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
329             element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
330         };
331     },
332
333     wrapText: function(params) {
334         return this.document._wrapText(_.extend({inside: this}, params));
335     },
336
337     toXML: function() {
338         var wrapper = $('<div>');
339         wrapper.append(this._getXMLDOMToDump());
340         return wrapper.html();
341     },
342     
343     _getXMLDOMToDump: function() {
344         return this._$;
345     }
346 });
347
348 var TextNode = function(nativeNode, document) {
349     DocumentNode.call(this, nativeNode, document);
350 };
351 TextNode.prototype = Object.create(DocumentNode.prototype);
352
353 $.extend(TextNode.prototype, {
354     nodeType: Node.TEXT_NODE,
355
356     getText: function() {
357         return this.nativeNode.data;
358     },
359
360     setText: function(text) {
361         this.nativeNode.data = text;
362         this.triggerTextChangeEvent();
363     },
364
365     appendText: function(text) {
366         this.nativeNode.data = this.nativeNode.data + text;
367         this.triggerTextChangeEvent();
368     },
369
370     prependText: function(text) {
371         this.nativeNode.data = text + this.nativeNode.data;
372         this.triggerTextChangeEvent();
373     },
374
375     wrapWith: function(desc) {
376         if(typeof desc.start === 'number' && typeof desc.end === 'number') {
377             return this.document._wrapText({
378                 inside: this.parent(),
379                 textNodeIdx: this.parent().indexOf(this),
380                 offsetStart: Math.min(desc.start, desc.end),
381                 offsetEnd: Math.max(desc.start, desc.end),
382                 _with: {tagName: desc.tagName, attrs: desc.attrs}
383             });
384         } else {
385             return DocumentNode.prototype.wrapWith.call(this, desc);
386         }
387     },
388
389     split: function(params) {
390         var parentElement = this.parent(),
391             passed = false,
392             succeedingChildren = [],
393             prefix = this.getText().substr(0, params.offset),
394             suffix = this.getText().substr(params.offset);
395
396         parentElement.contents().forEach(function(child) {
397             if(passed) {
398                 succeedingChildren.push(child);
399             }
400             if(child.sameNode(this)) {
401                 passed = true;
402             }
403         }.bind(this));
404
405         if(prefix.length > 0) {
406             this.setText(prefix);
407         }
408         else {
409             this.detach();
410         }
411
412         var attrs = {};
413         parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
414         var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
415         parentElement.after(newElement);
416
417         if(suffix.length > 0) {
418             newElement.append({text: suffix});
419         }
420         succeedingChildren.forEach(function(child) {
421             newElement.append(child);
422         });
423
424         return {first: parentElement, second: newElement};
425     },
426
427     triggerTextChangeEvent: function() {
428         var event = new events.ChangeEvent('nodeTextChange', {node: this});
429         this.document.trigger('change', event);
430     }
431 });
432
433
434 var parseXML = function(xml) {
435     return $($.trim(xml))[0];
436 };
437
438 var Document = function(xml) {
439     this.loadXML(xml);
440 };
441
442 $.extend(Document.prototype, Backbone.Events, {
443     ElementNodeFactory: ElementNode,
444     TextNodeFactory: TextNode,
445
446     createDocumentNode: function(from) {
447         if(!(from instanceof Node)) {
448             if(from.text !== undefined) {
449                 /* globals document */
450                 from = document.createTextNode(from.text);
451             } else {
452                 var node = $('<' + from.tagName + '>');
453
454                 _.keys(from.attrs || {}).forEach(function(key) {
455                     node.attr(key, from.attrs[key]);
456                 });
457
458                 from = node[0];
459             }
460         }
461         var Factory;
462         if(from.nodeType === Node.TEXT_NODE) {
463             Factory = this.TextNodeFactory;
464         } else if(from.nodeType === Node.ELEMENT_NODE) {
465             Factory = this.ElementNodeFactory;
466         }
467         return new Factory(from, this);
468     },
469
470     loadXML: function(xml, options) {
471         options = options || {};
472         defineDocumentProperties(this, $(parseXML(xml)));
473         if(!options.silent) {
474             this.trigger('contentSet');
475         }
476     },
477
478     toXML: function() {
479         return this.root.toXML();
480     },
481
482     containsNode: function(node) {
483         return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
484     },
485
486     wrapNodes: function(params) {
487         if(!(params.node1.parent().sameNode(params.node2.parent()))) {
488             throw new Error('Wrapping non-sibling nodes not supported.');
489         }
490
491         var parent = params.node1.parent(),
492             parentContents = parent.contents(),
493             wrapper = this.createDocumentNode({
494                 tagName: params._with.tagName,
495                 attrs: params._with.attrs}),
496             idx1 = parent.indexOf(params.node1),
497             idx2 = parent.indexOf(params.node2);
498
499         if(idx1 > idx2) {
500             var tmp = idx1;
501             idx1 = idx2;
502             idx2 = tmp;
503         }
504
505         var insertingMethod, insertingTarget;
506         if(idx1 === 0) {
507             insertingMethod = 'prepend';
508             insertingTarget = parent;
509         } else {
510             insertingMethod = 'after';
511             insertingTarget = parentContents[idx1-1];
512         }
513
514         for(var i = idx1; i <= idx2; i++) {
515             wrapper.append(parentContents[i].detach());
516         }
517
518         insertingTarget[insertingMethod](wrapper);
519         return wrapper;
520     },
521
522     getSiblingParents: function(params) {
523         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
524             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
525             noSiblingParents = null;
526
527         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
528             return noSiblingParents;
529         }
530
531         var i;
532         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
533             if(parents1[i].sameNode(parents2[i])) {
534                 continue;
535             }
536             break;
537         }
538         return {node1: parents1[i], node2: parents2[i]};
539     },
540
541     _wrapText: function(params) {
542         params = _.extend({textNodeIdx: 0}, params);
543         if(typeof params.textNodeIdx === 'number') {
544             params.textNodeIdx = [params.textNodeIdx];
545         }
546         
547         var contentsInside = params.inside.contents(),
548             idx1 = Math.min.apply(Math, params.textNodeIdx),
549             idx2 = Math.max.apply(Math, params.textNodeIdx),
550             textNode1 = contentsInside[idx1],
551             textNode2 = contentsInside[idx2],
552             sameNode = textNode1.sameNode(textNode2),
553             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
554             prefixInside = textNode1.getText().substr(params.offsetStart),
555             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
556             suffixOutside = textNode2.getText().substr(params.offsetEnd)
557         ;
558
559         if(!(textNode1.parent().sameNode(textNode2.parent()))) {
560             throw new Error('Wrapping text in non-sibling text nodes not supported.');
561         }
562         
563         var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
564         textNode1.after(wrapperElement);
565         textNode1.detach();
566         
567         if(prefixOutside.length > 0) {
568             wrapperElement.before({text:prefixOutside});
569         }
570         if(sameNode) {
571             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
572             wrapperElement.append({text: core});
573         } else {
574             textNode2.detach();
575             if(prefixInside.length > 0) {
576                 wrapperElement.append({text: prefixInside});
577             }
578             for(var i = idx1 + 1; i < idx2; i++) {
579                 wrapperElement.append(contentsInside[i]);
580             }
581             if(suffixInside.length > 0) {
582                 wrapperElement.append({text: suffixInside});
583             }
584         }
585         if(suffixOutside.length > 0) {
586             wrapperElement.after({text: suffixOutside});
587         }
588         return wrapperElement;
589     },
590
591     trigger: function() {
592         //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
593         Backbone.Events.trigger.apply(this, arguments);
594     },
595
596     getNodeInsertion: function(node) {
597         var insertion = {};
598         if(node instanceof DocumentNode) {
599             insertion.ofNode = node;
600             insertion.insertsNew = !this.containsNode(node);
601         } else {
602           insertion.ofNode = this.createDocumentNode(node);
603           insertion.insertsNew = true;
604         }
605         return insertion;
606     },
607
608     replaceRoot: function(node) {
609         var insertion = this.getNodeInsertion(node);
610         this.root.detach();
611         defineDocumentProperties(this, insertion.ofNode._$);
612         insertion.ofNode.triggerChangeEvent('nodeAdded');
613         return insertion.ofNode;
614     }
615 });
616
617 var defineDocumentProperties = function(doc, $document) {
618     Object.defineProperty(doc, 'root', {get: function() {
619         return doc.createDocumentNode($document[0]);
620     }, configurable: true});
621     Object.defineProperty(doc, 'dom', {get: function() {
622         return $document[0];
623     }, configurable: true});
624 };
625
626 return {
627     documentFromXML: function(xml) {
628         return new Document(xml);
629     },
630
631     elementNodeFromXML: function(xml) {
632         return this.documentFromXML(xml).root;
633     },
634
635     Document: Document,
636     DocumentNode: DocumentNode,
637     ElementNode: ElementNode
638 };
639
640 });