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 parentContents = parent.contents(),
257             myContents = this.contents(),
258             myIdx = parent.indexOf(this);
259
260
261         if(myContents.length === 0) {
262             return this.detach();
263         }
264
265         var moveLeftRange, moveRightRange, leftMerged;
266
267         if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
268             parentContents[myIdx-1].appendText(myContents[0].getText());
269             myContents[0].detach();
270             moveLeftRange = true;
271             leftMerged = true;
272         } else {
273             leftMerged = false;
274         }
275
276         if(!(leftMerged && myContents.length === 1)) {
277             if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
278                 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
279                 myContents[myContents.length-1].detach();
280                 moveRightRange = true;
281             }
282         }
283
284         var childrenLength = this.contents().length;
285         this.contents().forEach(function(child) {
286             this.before(child);
287         }.bind(this));
288
289         this.detach();
290
291         return {
292             element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
293             element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
294         };
295     },
296
297     wrapText: function(params) {
298         return this.document._wrapText(_.extend({inside: this}, params));
299     },
300
301     toXML: function() {
302         var wrapper = $('<div>');
303         wrapper.append(this._getXMLDOMToDump());
304         return wrapper.html();
305     },
306     
307     _getXMLDOMToDump: function() {
308         return this._$;
309     }
310 });
311
312 var TextNode = function(nativeNode, document) {
313     DocumentNode.call(this, nativeNode, document);
314 };
315 TextNode.prototype = Object.create(DocumentNode.prototype);
316
317 $.extend(TextNode.prototype, {
318     nodeType: Node.TEXT_NODE,
319
320     getText: function() {
321         return this.nativeNode.data;
322     },
323
324     setText: function(text) {
325         this.nativeNode.data = text;
326         this.triggerTextChangeEvent();
327     },
328
329     appendText: function(text) {
330         this.nativeNode.data = this.nativeNode.data + text;
331         this.triggerTextChangeEvent();
332     },
333
334     prependText: function(text) {
335         this.nativeNode.data = text + this.nativeNode.data;
336         this.triggerTextChangeEvent();
337     },
338
339     wrapWith: function(desc) {
340         if(typeof desc.start === 'number' && typeof desc.end === 'number') {
341             return this.document._wrapText({
342                 inside: this.parent(),
343                 textNodeIdx: this.parent().indexOf(this),
344                 offsetStart: Math.min(desc.start, desc.end),
345                 offsetEnd: Math.max(desc.start, desc.end),
346                 _with: {tagName: desc.tagName, attrs: desc.attrs}
347             });
348         } else {
349             return DocumentNode.prototype.wrapWith.call(this, desc);
350         }
351     },
352
353     triggerTextChangeEvent: function() {
354         var event = new events.ChangeEvent('nodeTextChange', {node: this});
355         this.document.trigger('change', event);
356     }
357 });
358
359
360 var parseXML = function(xml) {
361     return $(xml)[0];
362 };
363
364 var Document = function(xml) {
365     this.loadXML(xml);
366 };
367
368 $.extend(Document.prototype, Backbone.Events, {
369     ElementNodeFactory: ElementNode,
370     TextNodeFactory: TextNode,
371
372     createElementNode: function(from) {
373         if(!(from instanceof HTMLElement)) {
374             if(from.text) {
375                 from = document.createTextNode(from.text);
376             } else {
377                 var node = $('<' + from.tagName + '>');
378
379                 _.keys(from.attrs || {}).forEach(function(key) {
380                     node.attr(key, from.attrs[key]);
381                 });
382
383                 from = node[0];
384             }
385         }
386         var Factory;
387         if(from.nodeType === Node.TEXT_NODE) {
388             Factory = this.TextNodeFactory;
389         } else if(from.nodeType === Node.ELEMENT_NODE) {
390             Factory = this.ElementNodeFactory;
391         }
392         return new Factory(from, this);
393     },
394
395     createTextNode: function(nativeNode) {
396         return new this.TextNodeFactory(nativeNode, this);
397     },
398
399     loadXML: function(xml, options) {
400         options = options || {};
401         defineDocumentProperties(this, $(parseXML(xml)));
402         if(!options.silent) {
403             this.trigger('contentSet');
404         }
405     },
406
407     toXML: function() {
408         return this.root.toXML();
409     },
410
411     containsNode: function(node) {
412         return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
413     },
414
415     wrapNodes: function(params) {
416         if(!(params.element1.parent().sameNode(params.element2.parent()))) {
417             throw new Error('Wrapping non-sibling nodes not supported.');
418         }
419
420         var parent = params.element1.parent(),
421             parentContents = parent.contents(),
422             wrapper = this.createElementNode({
423                 tagName: params._with.tagName,
424                 attrs: params._with.attrs}),
425             idx1 = parent.indexOf(params.element1),
426             idx2 = parent.indexOf(params.element2);
427
428         if(idx1 > idx2) {
429             var tmp = idx1;
430             idx1 = idx2;
431             idx2 = tmp;
432         }
433
434         var insertingMethod, insertingTarget;
435         if(idx1 === 0) {
436             insertingMethod = 'prepend';
437             insertingTarget = parent;
438         } else {
439             insertingMethod = 'after';
440             insertingTarget = parentContents[idx1-1];
441         }
442
443         for(var i = idx1; i <= idx2; i++) {
444             wrapper.append(parentContents[i].detach());
445         }
446
447         insertingTarget[insertingMethod](wrapper);
448         return wrapper;
449     },
450
451     getSiblingParents: function(params) {
452         var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
453             parents2 = [params.node2].concat(params.node2.parents()).reverse(),
454             noSiblingParents = null;
455
456         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
457             return noSiblingParents;
458         }
459
460         var i;
461         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
462             if(parents1[i].sameNode(parents2[i])) {
463                 continue;
464             }
465             break;
466         }
467         return {node1: parents1[i], node2: parents2[i]};
468     },
469
470     _wrapText: function(params) {
471         params = _.extend({textNodeIdx: 0}, params);
472         if(typeof params.textNodeIdx === 'number') {
473             params.textNodeIdx = [params.textNodeIdx];
474         }
475         
476         var contentsInside = params.inside.contents(),
477             idx1 = Math.min.apply(Math, params.textNodeIdx),
478             idx2 = Math.max.apply(Math, params.textNodeIdx),
479             textNode1 = contentsInside[idx1],
480             textNode2 = contentsInside[idx2],
481             sameNode = textNode1.sameNode(textNode2),
482             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
483             prefixInside = textNode1.getText().substr(params.offsetStart),
484             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
485             suffixOutside = textNode2.getText().substr(params.offsetEnd)
486         ;
487
488         if(!(textNode1.parent().sameNode(textNode2.parent()))) {
489             throw new Error('Wrapping text in non-sibling text nodes not supported.');
490         }
491         
492         var wrapperElement = this.createElementNode({tagName: params._with.tagName, attrs: params._with.attrs});
493         textNode1.after(wrapperElement);
494         textNode1.detach();
495         
496         if(prefixOutside.length > 0) {
497             wrapperElement.before({text:prefixOutside});
498         }
499         if(sameNode) {
500             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
501             wrapperElement.append({text: core});
502         } else {
503             textNode2.detach();
504             if(prefixInside.length > 0) {
505                 wrapperElement.append({text: prefixInside});
506             }
507             for(var i = idx1 + 1; i < idx2; i++) {
508                 wrapperElement.append(contentsInside[i]);
509             }
510             if(suffixInside.length > 0) {
511                 wrapperElement.append({text: suffixInside});
512             }
513         }
514         if(suffixOutside.length > 0) {
515             wrapperElement.after({text: suffixOutside});
516         }
517         return wrapperElement;
518     },
519
520     trigger: function() {
521         //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
522         Backbone.Events.trigger.apply(this, arguments);
523     }
524 });
525
526 var defineDocumentProperties = function(doc, $document) {
527     Object.defineProperty(doc, 'root', {get: function() {
528         return doc.createElementNode($document[0]);
529     }, configurable: true});
530     Object.defineProperty(doc, 'dom', {get: function() {
531         return $document[0];
532     }, configurable: true});
533 };
534
535 return {
536     documentFromXML: function(xml) {
537         return new Document(parseXML(xml));
538     },
539
540     elementNodeFromXML: function(xml) {
541         return this.documentFromXML(xml).root;
542     },
543
544     Document: Document,
545     DocumentNode: DocumentNode,
546     ElementNode: ElementNode
547 };
548
549 });