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