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