smartxml: fixing changing tag of a root node
[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 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
105         this.getAttrs().forEach(function(attribute) {
106             node.setAttr(attribute.name, attribute.value, true);
107         });
108         node.setData(this.getData());
109
110         if(this.sameNode(this.document.root)) {
111             defineDocumentProperties(this.document, node._$);
112         }
113         this._$.replaceWith(node._$);
114         this._setNativeNode(node._$[0]);
115         this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
116     },
117
118     getAttr: function(name) {
119         return this._$.attr(name);
120     },
121
122     setAttr: function(name, value, silent) {
123         var oldVal = this.getAttr(name);
124         this._$.attr(name, value);
125         if(!silent) {
126             this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
127         }
128     },
129
130     getAttrs: function() {
131         var toret = [];
132         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
133             toret.push(this.nativeNode.attributes[i]);
134         }
135         return toret;
136     },
137
138     append: function(documentNode) {
139         this._$.append(documentNode.nativeNode);
140     },
141
142     unwrapContent: function() {
143         var parent = this.parent();
144         if(!parent) {
145             return;
146         }
147
148         var parentContents = parent.contents(),
149             myContents = this.contents(),
150             myIdx = parent.indexOf(this);
151
152         if(myContents.length === 0) {
153             return this.detach();
154         }
155
156         var moveLeftRange, moveRightRange, leftMerged;
157
158         if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
159             parentContents[myIdx-1].appendText(myContents[0].getText());
160             myContents[0].detach();
161             moveLeftRange = true;
162             leftMerged = true;
163         } else {
164             leftMerged = false;
165         }
166
167         if(!(leftMerged && myContents.length === 1)) {
168             if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
169                 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
170                 myContents[myContents.length-1].detach();
171                 moveRightRange = true;
172             }
173         }
174
175         var childrenLength = this.contents().length;
176         this.contents().forEach(function(child) {
177             this.before(child);
178         }.bind(this));
179
180         this.detach();
181
182         return {
183             element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
184             element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
185         };
186     },
187
188     toXML: function() {
189         var wrapper = $('<div>');
190         wrapper.append(this._$);
191         return wrapper.html();
192     }
193 });
194
195 var TextNode = function(nativeNode, document) {
196     DocumentNode.call(this, nativeNode, document);
197 };
198
199 $.extend(TextNode.prototype, DocumentNode.prototype, {
200     nodeType: Node.TEXT_NODE,
201
202     getText: function() {
203         return this.nativeNode.data;
204     },
205
206     appendText: function(text) {
207         this.nativeNode.data = this.nativeNode.data + text;
208     },
209
210     prependText: function(text) {
211         this.nativeNode.data = text + this.nativeNode.data;
212     }
213 });
214
215
216 var parseXML = function(xml) {
217     return $(xml)[0];
218 };
219
220 var Document = function(xml) {
221     this.loadXML(xml);
222 };
223
224 $.extend(Document.prototype, Backbone.Events, {
225     ElementNodeFactory: ElementNode,
226     TextNodeFactory: TextNode,
227
228     createElementNode: function(from) {
229         if(!(from instanceof HTMLElement)) {
230             from = $('<' + from.tagName + '>');
231         }
232         return new this.ElementNodeFactory(from, this);
233     },
234
235     createTextNode: function(nativeNode) {
236         return new this.TextNodeFactory(nativeNode, this);
237     },
238
239     loadXML: function(xml) {
240         defineDocumentProperties(this, $(parseXML(xml)));
241         
242         this.trigger('contentSet');
243     },
244
245     toXML: function() {
246         return this.root.toXML();
247     }
248 });
249
250 var defineDocumentProperties = function(doc, $document) {
251     Object.defineProperty(doc, 'root', {get: function() {
252         return doc.createElementNode($document[0]);
253     }, configurable: true});
254     Object.defineProperty(doc, 'dom', {get: function() {
255         return $document[0];
256     }, configurable: true});
257 };
258
259 return {
260     documentFromXML: function(xml) {
261         return new Document(parseXML(xml));
262     },
263
264     elementNodeFromXML: function(xml) {
265         return this.documentFromXML(xml).root;
266     },
267
268     Document: Document,
269     DocumentNode: DocumentNode,
270     ElementNode: ElementNode
271 };
272
273 });