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