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