smartxml: only send change event when node is currently in a document tree
[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 INSERTION = function(implementation) {
15     var toret = function(node) {
16         var insertion = this.getNodeInsertion(node);
17         implementation.call(this, insertion.ofNode.nativeNode);
18         this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
19         return insertion.ofNode;
20     };
21     return toret;
22 };
23
24 var DocumentNode = function(nativeNode, document) {
25     if(!document) {
26         throw new Error('undefined document for a node');
27     }
28     this.document = document;
29     this._setNativeNode(nativeNode);
30
31 };
32
33 $.extend(DocumentNode.prototype, {
34     _setNativeNode: function(nativeNode) {
35         this.nativeNode = nativeNode;
36         this._$ = $(nativeNode);
37     },
38
39     detach: function() {
40         var parent = this.parent();
41         this._$.detach();
42         this.triggerChangeEvent('nodeDetached', {parent: parent});
43         return this;
44     },
45
46     sameNode: function(otherNode) {
47         return otherNode && this.nativeNode === otherNode.nativeNode;
48     },
49
50     parent: function() {
51         var parentNode = this.nativeNode.parentNode;
52         if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
53             return this.document.createElementNode(parentNode);
54         }
55         return null;
56     },
57
58     parents: function() {
59         var parent = this.parent(),
60             parents = parent ? parent.parents() : [];
61         if(parent) {
62             parents.unshift(parent);
63         }
64         return parents;
65     },
66
67     after: INSERTION(function(nativeNode) {
68         return this._$.after(nativeNode);
69     }),
70
71     before: INSERTION(function(nativeNode) {
72         return this._$.before(nativeNode);
73     }),
74
75     wrapWith: function(node) {
76         node = node instanceof ElementNode ? node : this.document.createElementNode(node);
77
78         if(this.parent()) {
79             this.before(node);
80         }
81         node.append(this);
82         return node;
83     },
84
85     triggerChangeEvent: function(type, metaData) {
86         var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
87         if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
88             this.document.trigger('change', event);
89         }
90     },
91     
92     getNodeInsertion: function(node) {
93         var insertion = {};
94         if(node instanceof DocumentNode) {
95             insertion.ofNode = node;
96             insertion.insertsNew = !this.document.containsNode(node);
97         } else {
98           insertion.ofNode = this.document.createElementNode(node);
99           insertion.insertsNew = true;
100         }
101         return insertion;
102     },
103
104     getIndex: function() {
105         return this.parent().indexOf(this);
106     }
107 });
108
109 var ElementNode = function(nativeNode, document) {
110     DocumentNode.call(this, nativeNode, document);
111 };
112 ElementNode.prototype = Object.create(DocumentNode.prototype);
113
114 $.extend(ElementNode.prototype, {
115     nodeType: Node.ELEMENT_NODE,
116
117     setData: function(key, value) {
118         if(value !== undefined) {
119             this._$.data(key, value);
120         } else {
121             this._$.removeData(_.keys(this._$.data()));
122             this._$.data(key);
123         }
124     },
125
126     getData: function(key) {
127         if(key) {
128             return this._$.data(key);
129         }
130         return this._$.data();
131     },
132
133     getTagName: function() {
134         return this.nativeNode.tagName.toLowerCase();
135     },
136
137     contents: function() {
138         var toret = [],
139             document = this.document;
140         this._$.contents().each(function() {
141             if(this.nodeType === Node.ELEMENT_NODE) {
142                 toret.push(document.createElementNode(this));
143             }
144             else if(this.nodeType === Node.TEXT_NODE) {
145                 toret.push(document.createTextNode(this));
146             }
147         });
148         return toret;
149     },
150
151     indexOf: function(node) {
152         return this._$.contents().index(node._$);
153     },
154
155     setTag: function(tagName) {
156         var node = this.document.createElementNode({tagName: tagName}),
157             oldTagName = this.getTagName(),
158             myContents = this._$.contents();
159
160         this.getAttrs().forEach(function(attribute) {
161             node.setAttr(attribute.name, attribute.value, true);
162         });
163         node.setData(this.getData());
164
165         if(this.sameNode(this.document.root)) {
166             defineDocumentProperties(this.document, node._$);
167         }
168         this._$.replaceWith(node._$);
169         this._setNativeNode(node._$[0]);
170         this._$.append(myContents);
171         this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
172     },
173
174     getAttr: function(name) {
175         return this._$.attr(name);
176     },
177
178     setAttr: function(name, value, silent) {
179         var oldVal = this.getAttr(name);
180         this._$.attr(name, value);
181         if(!silent) {
182             this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
183         }
184     },
185
186     getAttrs: function() {
187         var toret = [];
188         for(var i = 0; i < this.nativeNode.attributes.length; i++) {
189             toret.push(this.nativeNode.attributes[i]);
190         }
191         return toret;
192     },
193
194     append: INSERTION(function(nativeNode) {
195         this._$.append(nativeNode);
196     }),
197
198     prepend: INSERTION(function(nativeNode) {
199         this._$.prepend(nativeNode);
200     }),
201
202     unwrapContent: function() {
203         var parent = this.parent();
204         if(!parent) {
205             return;
206         }
207
208         var parentContents = parent.contents(),
209             myContents = this.contents(),
210             myIdx = parent.indexOf(this);
211
212         if(myContents.length === 0) {
213             return this.detach();
214         }
215
216         var moveLeftRange, moveRightRange, leftMerged;
217
218         if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
219             parentContents[myIdx-1].appendText(myContents[0].getText());
220             myContents[0].detach();
221             moveLeftRange = true;
222             leftMerged = true;
223         } else {
224             leftMerged = false;
225         }
226
227         if(!(leftMerged && myContents.length === 1)) {
228             if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
229                 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
230                 myContents[myContents.length-1].detach();
231                 moveRightRange = true;
232             }
233         }
234
235         var childrenLength = this.contents().length;
236         this.contents().forEach(function(child) {
237             this.before(child);
238         }.bind(this));
239
240         this.detach();
241
242         return {
243             element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
244             element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
245         };
246     },
247
248     wrapText: function(params) {
249         return this.document._wrapText(_.extend({inside: this}, params));
250     },
251
252     toXML: function() {
253         var wrapper = $('<div>');
254         wrapper.append(this._getXMLDOMToDump());
255         return wrapper.html();
256     },
257     
258     _getXMLDOMToDump: function() {
259         return this._$;
260     }
261 });
262
263 var TextNode = function(nativeNode, document) {
264     DocumentNode.call(this, nativeNode, document);
265 };
266 TextNode.prototype = Object.create(DocumentNode.prototype);
267
268 $.extend(TextNode.prototype, {
269     nodeType: Node.TEXT_NODE,
270
271     getText: function() {
272         return this.nativeNode.data;
273     },
274
275     setText: function(text) {
276         this.nativeNode.data = text;
277         this.triggerTextChangeEvent();
278     },
279
280     appendText: function(text) {
281         this.nativeNode.data = this.nativeNode.data + text;
282         this.triggerTextChangeEvent();
283     },
284
285     prependText: function(text) {
286         this.nativeNode.data = text + this.nativeNode.data;
287         this.triggerTextChangeEvent();
288     },
289
290     wrapWith: function(desc) {
291         if(typeof desc.start === 'number' && typeof desc.end === 'number') {
292             return this.document._wrapText({
293                 inside: this.parent(),
294                 textNodeIdx: this.parent().indexOf(this),
295                 offsetStart: Math.min(desc.start, desc.end),
296                 offsetEnd: Math.max(desc.start, desc.end),
297                 _with: {tagName: desc.tagName, attrs: desc.attrs}
298             });
299         } else {
300             return DocumentNode.prototype.wrapWith.call(this, desc);
301         }
302     },
303
304     triggerTextChangeEvent: function() {
305         var event = new events.ChangeEvent('nodeTextChange', {node: this});
306         this.document.trigger('change', event);
307     }
308 });
309
310
311 var parseXML = function(xml) {
312     return $(xml)[0];
313 };
314
315 var Document = function(xml) {
316     this.loadXML(xml);
317 };
318
319 $.extend(Document.prototype, Backbone.Events, {
320     ElementNodeFactory: ElementNode,
321     TextNodeFactory: TextNode,
322
323     createElementNode: function(from) {
324         if(!(from instanceof HTMLElement)) {
325             if(from.text) {
326                 from = document.createTextNode(from.text);
327             } else {
328                 var node = $('<' + from.tagName + '>');
329
330                 _.keys(from.attrs || {}).forEach(function(key) {
331                     node.attr(key, from.attrs[key]);
332                 });
333
334                 from = node[0];
335             }
336         }
337         var Factory;
338         if(from.nodeType === Node.TEXT_NODE) {
339             Factory = this.TextNodeFactory;
340         } else if(from.nodeType === Node.ELEMENT_NODE) {
341             Factory = this.ElementNodeFactory;
342         }
343         return new Factory(from, this);
344     },
345
346     createTextNode: function(nativeNode) {
347         return new this.TextNodeFactory(nativeNode, this);
348     },
349
350     loadXML: function(xml, options) {
351         options = options || {};
352         defineDocumentProperties(this, $(parseXML(xml)));
353         if(!options.silent) {
354             this.trigger('contentSet');
355         }
356     },
357
358     toXML: function() {
359         return this.root.toXML();
360     },
361
362     containsNode: function(node) {
363         return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
364     },
365
366     wrapNodes: function(params) {
367         if(!(params.element1.parent().sameNode(params.element2.parent()))) {
368             throw new Error('Wrapping non-sibling nodes not supported.');
369         }
370
371         var parent = params.element1.parent(),
372             parentContents = parent.contents(),
373             wrapper = this.createElementNode({
374                 tagName: params._with.tagName,
375                 attrs: params._with.attrs}),
376             idx1 = parent.indexOf(params.element1),
377             idx2 = parent.indexOf(params.element2);
378
379         if(idx1 > idx2) {
380             var tmp = idx1;
381             idx1 = idx2;
382             idx2 = tmp;
383         }
384
385         var insertingMethod, insertingTarget;
386         if(idx1 === 0) {
387             insertingMethod = 'prepend';
388             insertingTarget = parent;
389         } else {
390             insertingMethod = 'after';
391             insertingTarget = parentContents[idx1-1];
392         }
393
394         for(var i = idx1; i <= idx2; i++) {
395             wrapper.append(parentContents[i].detach());
396         }
397
398         insertingTarget[insertingMethod](wrapper);
399         return wrapper;
400     },
401
402     getSiblingParents: function(params) {
403         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
404             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
405             noSiblingParents = null;
406
407         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
408             return noSiblingParents;
409         }
410
411         var i;
412         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
413             if(parents1[i].sameNode(parents2[i])) {
414                 continue;
415             }
416             break;
417         }
418         return {node1: parents1[i], node2: parents2[i]};
419     },
420
421     _wrapText: function(params) {
422         params = _.extend({textNodeIdx: 0}, params);
423         if(typeof params.textNodeIdx === 'number') {
424             params.textNodeIdx = [params.textNodeIdx];
425         }
426         
427         var contentsInside = params.inside.contents(),
428             idx1 = Math.min.apply(Math, params.textNodeIdx),
429             idx2 = Math.max.apply(Math, params.textNodeIdx),
430             textNode1 = contentsInside[idx1],
431             textNode2 = contentsInside[idx2],
432             sameNode = textNode1.sameNode(textNode2),
433             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
434             prefixInside = textNode1.getText().substr(params.offsetStart),
435             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
436             suffixOutside = textNode2.getText().substr(params.offsetEnd)
437         ;
438
439         if(!(textNode1.parent().sameNode(textNode2.parent()))) {
440             throw new Error('Wrapping text in non-sibling text nodes not supported.');
441         }
442         
443         var wrapperElement = this.createElementNode({tagName: params._with.tagName, attrs: params._with.attrs});
444         textNode1.after(wrapperElement);
445         textNode1.detach();
446         
447         if(prefixOutside.length > 0) {
448             wrapperElement.before({text:prefixOutside});
449         }
450         if(sameNode) {
451             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
452             wrapperElement.append({text: core});
453         } else {
454             textNode2.detach();
455             if(prefixInside.length > 0) {
456                 wrapperElement.append({text: prefixInside});
457             }
458             for(var i = idx1 + 1; i < idx2; i++) {
459                 wrapperElement.append(contentsInside[i]);
460             }
461             if(suffixInside.length > 0) {
462                 wrapperElement.append({text: suffixInside});
463             }
464         }
465         if(suffixOutside.length > 0) {
466             wrapperElement.after({text: suffixOutside});
467         }
468         return wrapperElement;
469     },
470
471     trigger: function() {
472         //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
473         Backbone.Events.trigger.apply(this, arguments);
474     }
475 });
476
477 var defineDocumentProperties = function(doc, $document) {
478     Object.defineProperty(doc, 'root', {get: function() {
479         return doc.createElementNode($document[0]);
480     }, configurable: true});
481     Object.defineProperty(doc, 'dom', {get: function() {
482         return $document[0];
483     }, configurable: true});
484 };
485
486 return {
487     documentFromXML: function(xml) {
488         return new Document(parseXML(xml));
489     },
490
491     elementNodeFromXML: function(xml) {
492         return this.documentFromXML(xml).root;
493     },
494
495     Document: Document,
496     DocumentNode: DocumentNode,
497     ElementNode: ElementNode
498 };
499
500 });