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