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