smartxml: fixing inheritance to support for instanceof operator to work properly
[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() { this._$.detach(); },
30
31     sameNode: function(otherNode) {
32         return otherNode && this.nativeNode === otherNode.nativeNode;
33     },
34
35     parent: function() {
36         return this.nativeNode.parentNode ? this.document.createElementNode(this.nativeNode.parentNode) : null;
37     },
38
39     after: function(node) {
40         node = node instanceof ElementNode ? node : this.document.createElementNode(node);
41         this._$.after(node.nativeNode);
42         return node;
43     },
44
45     before: function(node) {
46         node = node instanceof ElementNode ? node : this.document.createElementNode(node);
47         this._$.before(node.nativeNode);
48         return node;
49     },
50
51     wrapWith: function(node) {
52         node = node instanceof ElementNode ? node : this.document.createElementNode(node);
53
54         if(this.parent()) {
55             this.before(node);
56         }
57         node.append(this);
58         return node;
59     },
60
61     triggerChangeEvent: function(type, metaData) {
62         var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
63         this.document.trigger('change', event);
64     },
65 });
66
67 var ElementNode = function(nativeNode, document) {
68     DocumentNode.call(this, nativeNode, document);
69 };
70 ElementNode.prototype = Object.create(DocumentNode.prototype);
71
72 $.extend(ElementNode.prototype, {
73     nodeType: Node.ELEMENT_NODE,
74
75     setData: function(key, value) {
76         if(value !== undefined) {
77             this._$.data(key, value);
78         } else {
79             this._$.removeData(_.keys(this._$.data()));
80             this._$.data(key);
81         }
82     },
83
84     getData: function(key) {
85         if(key) {
86             return this._$.data(key);
87         }
88         return this._$.data();
89     },
90
91     getTagName: function() {
92         return this.nativeNode.tagName.toLowerCase();
93     },
94
95     contents: function() {
96         var toret = [],
97             document = this.document;
98         this._$.contents().each(function() {
99             if(this.nodeType === Node.ELEMENT_NODE) {
100                 toret.push(document.createElementNode(this));
101             }
102             else if(this.nodeType === Node.TEXT_NODE) {
103                 toret.push(document.createTextNode(this));
104             }
105         });
106         return toret;
107     },
108
109     indexOf: function(node) {
110         return this._$.contents().index(node._$);
111     },
112
113     setTag: function(tagName) {
114         var node = this.document.createElementNode({tagName: tagName}),
115             oldTagName = this.getTagName(),
116             myContents = this._$.contents();
117
118         this.getAttrs().forEach(function(attribute) {
119             node.setAttr(attribute.name, attribute.value, true);
120         });
121         node.setData(this.getData());
122
123         if(this.sameNode(this.document.root)) {
124             defineDocumentProperties(this.document, node._$);
125         }
126         this._$.replaceWith(node._$);
127         this._setNativeNode(node._$[0]);
128         this._$.append(myContents);
129         this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
130     },
131
132     getAttr: function(name) {
133         return this._$.attr(name);
134     },
135
136     setAttr: function(name, value, silent) {
137         var oldVal = this.getAttr(name);
138         this._$.attr(name, value);
139         if(!silent) {
140             this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
141         }
142     },
143
144     getAttrs: function() {
145         var toret = [];
146         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
147             toret.push(this.nativeNode.attributes[i]);
148         }
149         return toret;
150     },
151
152     append: function(documentNode) {
153         this._$.append(documentNode.nativeNode);
154     },
155
156     unwrapContent: function() {
157         var parent = this.parent();
158         if(!parent) {
159             return;
160         }
161
162         var parentContents = parent.contents(),
163             myContents = this.contents(),
164             myIdx = parent.indexOf(this);
165
166         if(myContents.length === 0) {
167             return this.detach();
168         }
169
170         var moveLeftRange, moveRightRange, leftMerged;
171
172         if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
173             parentContents[myIdx-1].appendText(myContents[0].getText());
174             myContents[0].detach();
175             moveLeftRange = true;
176             leftMerged = true;
177         } else {
178             leftMerged = false;
179         }
180
181         if(!(leftMerged && myContents.length === 1)) {
182             if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
183                 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
184                 myContents[myContents.length-1].detach();
185                 moveRightRange = true;
186             }
187         }
188
189         var childrenLength = this.contents().length;
190         this.contents().forEach(function(child) {
191             this.before(child);
192         }.bind(this));
193
194         this.detach();
195
196         return {
197             element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
198             element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
199         };
200     },
201
202     toXML: function() {
203         var wrapper = $('<div>');
204         wrapper.append(this._getXMLDOMToDump());
205         return wrapper.html();
206     },
207     
208     _getXMLDOMToDump: function() {
209         return this._$;
210     }
211 });
212
213 var TextNode = function(nativeNode, document) {
214     DocumentNode.call(this, nativeNode, document);
215 };
216 TextNode.prototype = Object.create(DocumentNode.prototype);
217
218 $.extend(TextNode.prototype, {
219     nodeType: Node.TEXT_NODE,
220
221     getText: function() {
222         return this.nativeNode.data;
223     },
224
225     setText: function(text) {
226         this.nativeNode.data = text;
227         this.triggerTextChangeEvent();
228     },
229
230     appendText: function(text) {
231         this.nativeNode.data = this.nativeNode.data + text;
232         this.triggerTextChangeEvent();
233     },
234
235     prependText: function(text) {
236         this.nativeNode.data = text + this.nativeNode.data;
237         this.triggerTextChangeEvent();
238     },
239
240     triggerTextChangeEvent: function() {
241         var event = new events.ChangeEvent('nodeTextChange', {node: this});
242         this.document.trigger('change', event);
243     }
244 });
245
246
247 var parseXML = function(xml) {
248     return $(xml)[0];
249 };
250
251 var Document = function(xml) {
252     this.loadXML(xml);
253 };
254
255 $.extend(Document.prototype, Backbone.Events, {
256     ElementNodeFactory: ElementNode,
257     TextNodeFactory: TextNode,
258
259     createElementNode: function(from) {
260         if(!(from instanceof HTMLElement)) {
261             if(from.text) {
262                 from = document.createTextNode(from.text);
263             } else {
264                 from = $('<' + from.tagName + '>')[0];
265             }
266         }
267         return new this.ElementNodeFactory(from, this);
268     },
269
270     createTextNode: function(nativeNode) {
271         return new this.TextNodeFactory(nativeNode, this);
272     },
273
274     loadXML: function(xml, options) {
275         options = options || {};
276         defineDocumentProperties(this, $(parseXML(xml)));
277         if(!options.silent) {
278             this.trigger('contentSet');
279         }
280     },
281
282     toXML: function() {
283         return this.root.toXML();
284     }
285 });
286
287 var defineDocumentProperties = function(doc, $document) {
288     Object.defineProperty(doc, 'root', {get: function() {
289         return doc.createElementNode($document[0]);
290     }, configurable: true});
291     Object.defineProperty(doc, 'dom', {get: function() {
292         return $document[0];
293     }, configurable: true});
294 };
295
296 return {
297     documentFromXML: function(xml) {
298         return new Document(parseXML(xml));
299     },
300
301     elementNodeFromXML: function(xml) {
302         return this.documentFromXML(xml).root;
303     },
304
305     Document: Document,
306     DocumentNode: DocumentNode,
307     ElementNode: ElementNode
308 };
309
310 });