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