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