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