fix selecting nodes with no text
[fnpeditor.git] / src / wlxml / wlxml.js
1 define([
2     'libs/jquery',
3     'libs/underscore',
4     'smartxml/smartxml',
5     'smartxml/transformations',
6     'wlxml/extensions/metadata/metadata',
7     'wlxml/extensions/comments/comments',
8     'wlxml/extensions/edumed/edumed'
9 ], function($, _, smartxml, transformations, metadataExtension, commentExtension, edumedExtension) {
10     
11 'use strict';
12
13 /* globals Node */
14
15
16 var WLXMLDocumentNodeMethods =  {
17     isInside: function(query) {
18         var parent = this.getParent(query);
19         return !!parent;
20     },
21     getParent: function(query) {
22         /* globals Node */
23         var me = this.nodeType === Node.ELEMENT_NODE ? [this] : [],
24             toret;
25         me.concat(this.parents()).some(function(node) {
26             if(node.is(query)) {
27                 toret = node;
28             }
29             return !!toret || (!node.sameNode(this) && node.isContextRoot());
30         }.bind(this));
31
32         return toret;
33     },
34     isContextRoot: function() {
35         var me = this.nodeType === Node.ELEMENT_NODE ? [this] : [],
36             toret = false;
37         if(!this.parent()) {
38             return true;
39         }
40         me.concat(this.parents()).some(function(node) {
41             if(_.isFunction(node.object.isContextRoot) && node.object.isContextRoot(this)) {
42                 toret = true;
43                 return true;
44             }
45         }.bind(this));
46         return toret;
47     },
48     getContextRoot: function() {
49         var contextRoot;
50         [this].concat(this.parents()).some(function(n) {
51             if(n.isContextRoot()) {
52                 contextRoot = n;
53                 return true;
54             }
55         });
56         return contextRoot;
57     },
58     hasSameContextRoot: function(other) {
59         return this.getContextRoot().sameNode(other.getContextRoot());
60     }
61 };
62
63 var getClassLists = function(klassName) {
64     var toret = [],
65         classParts = [''].concat(klassName.split('.')),
66         classCurrent;
67
68     classParts.forEach(function(part) {
69         classCurrent = classCurrent ? classCurrent + '.' + part : part;
70         toret.push(classCurrent);
71     });
72     return toret;
73 };
74
75 var installObject = function(instance, klass) {
76     var methods = {},
77         transformations = {};
78
79     getClassLists(klass).forEach(function(klassName) {
80         _.extend(methods, instance.document.classMethods[klassName] || {});
81         _.extend(methods, instance.document.classTransformations[klassName] || {});
82     });
83     instance.object = Object.create(_.extend({}, methods, transformations));
84     _.keys(methods).concat(_.keys(transformations)).forEach(function(key) {
85         if(_.isFunction(instance.object[key])) {
86             instance.object[key] = _.bind(instance.object[key], instance);
87         }
88     });
89 };
90
91 var WLXMLElementNode = function(nativeNode, document) {
92     smartxml.ElementNode.call(this, nativeNode, document);
93     installObject(this, this.getClass());
94 };
95 WLXMLElementNode.prototype = Object.create(smartxml.ElementNode.prototype);
96
97 $.extend(WLXMLElementNode.prototype, WLXMLDocumentNodeMethods, smartxml.ElementNode.prototype, {
98     getClass: function() {
99         return this.getAttr('class') || '';
100     },
101     getClassHierarchy: function() {
102         return getClassLists(this.getClass());
103     },
104     setClass: function(klass) {
105         if(klass !== this.klass) {
106             installObject(this, klass);
107             return this.setAttr('class', klass);
108         }
109     },
110     is: function(query) {
111         if(typeof query === 'string') {
112             query = {klass: query};
113         }
114         return (_.isUndefined(query.klass) || this.getClass().substr(0, query.klass.length) === query.klass) &&
115                (_.isUndefined(query.tagName) || this.getTagName() === query.tagName);
116     },
117     hasChild: function(query) {
118         return this.contents().some(function(child) {
119             return child.is(query);
120         }.bind(this));
121     },
122     find: function(query) {
123         var doc = this.document;
124         return this._$.find('*')
125             .map(function() {
126                 return doc.createDocumentNode(this);
127             })
128             .filter(function() {
129                 return this.is(query);
130             });
131     },
132
133     _getXMLDOMToDump: function() {
134         var DOM = this._$.clone(true, true),
135             doc = this.document;
136
137         DOM.find('*').addBack().each(function() {
138             var el = $(this),
139                 parent = el.parent(),
140                 contents = parent.contents(),
141                 idx = contents.index(el),
142                 data = el.data();
143
144
145             var txt, documentNode, metaNode;
146
147             if(data[formatter_prefix+ 'orig_before']) {
148                 txt = idx > 0 && contents[idx-1].nodeType === Node.TEXT_NODE ? contents[idx-1] : null;
149                 if(txt && txt.data === data[formatter_prefix + 'orig_before_transformed']) {
150                     txt.data = data[formatter_prefix+ 'orig_before_original'];
151                 } else {
152                     el.before(data[formatter_prefix+ 'orig_before']);
153                 }
154             }
155             if(data[formatter_prefix+ 'orig_after']) {
156                 txt = idx < contents.length-1 && contents[idx+1].nodeType === Node.TEXT_NODE ? contents[idx+1] : null;
157                 if(txt && txt.data === data[formatter_prefix + 'orig_after_transformed']) {
158                     txt.data = data[formatter_prefix+ 'orig_after_original'];
159                 } else {
160                     el.after(data[formatter_prefix+ 'orig_after']);
161                 }
162             }
163             if(data[formatter_prefix+ 'orig_begin']) {
164                 el.prepend(data[formatter_prefix+ 'orig_begin']);
165             }
166             if(data[formatter_prefix+ 'orig_end']) {
167                 contents = el.contents();
168                 txt = (contents.length && contents[contents.length-1].nodeType === Node.TEXT_NODE) ? contents[contents.length-1] : null;
169                 if(txt && txt.data === data[formatter_prefix + 'orig_end_transformed']) {
170                     txt.data = data[formatter_prefix+ 'orig_end_original'];
171                 } else {
172                     el.append(data[formatter_prefix+ 'orig_end']);
173                 }
174             }
175
176
177             if(this.nodeType === Node.ELEMENT_NODE) {
178                 documentNode = doc.createDocumentNode(this);
179                 metaNode = $('<metadata>');
180                 documentNode.getMetadata().forEach(function(row) {
181                     metaNode.append('<dc:'+ row.key + '>' + row.value + '</dc:' + row.key + '>');
182                 });
183                 if(metaNode.children().length) {
184                     $(this).prepend(metaNode);
185                 }
186             }
187         });
188
189         return DOM;
190     }
191 });
192
193
194 var WLXMLDocumentNode = function() {
195     smartxml.DocumentNode.apply(this, arguments);
196 };
197 WLXMLDocumentNode.prototype = Object.create(smartxml.DocumentNode.prototype);
198
199 var WLXMLTextNode = function() {
200     smartxml.TextNode.apply(this, arguments);
201 };
202 WLXMLTextNode.prototype = Object.create(smartxml.TextNode.prototype);
203 $.extend(WLXMLTextNode.prototype, WLXMLDocumentNodeMethods, {
204     is: function() { return false; }
205 });
206
207 var WLXMLDocument = function(xml, options) {
208     this.classMethods = {};
209     this.classTransformations = {};
210     smartxml.Document.call(this, xml, [metadataExtension, commentExtension, edumedExtension]);
211     this.options = options;
212 };
213
214 var formatter_prefix = '_wlxml_formatter_';
215
216
217 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
218 $.extend(WLXMLDocument.prototype, {
219     ElementNodeFactory: WLXMLElementNode,
220     TextNodeFactory: WLXMLTextNode,
221     loadXML: function(xml) {
222         smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
223         this.trigger('contentSet');
224     },
225
226     normalizeXML: function(nativeNode) {
227         var doc = this,
228             prefixLength = 'dc:'.length;
229
230         $(nativeNode).find('metadata').each(function() {
231             var metadataNode = $(this),
232                 owner = doc.createDocumentNode(metadataNode.parent()[0]),
233                 metadata = owner.getMetadata();
234                 
235             metadataNode.children().each(function() {
236                 metadata.add({key: (this.tagName).toLowerCase().substr(prefixLength), value: $(this).text()}, {undoable: false});
237             });
238             metadataNode.remove();
239         });
240         nativeNode.normalize();
241         $(nativeNode).find('*').each(function() {
242             if (this.childNodes.length === 0) {
243                 var fakeTextNode = window.document.createTextNode("");
244                 this.appendChild(fakeTextNode);
245             }
246         });
247
248         $(nativeNode).find(':not(iframe)').addBack().contents()
249             .filter(function() {return this.nodeType === Node.TEXT_NODE;})
250             .each(function() {
251                 var el = $(this),
252                     text = {original: el.text(), trimmed: $.trim(el.text())},
253                     elParent = el.parent(),
254                     hasSpanParent = elParent.prop('tagName') === 'SPAN',
255                     hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
256                     hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN',
257                     onlyChild = el.is(':only-child');
258
259
260                 var addInfo = function(toAdd, where, transformed, original) {
261                     var parentContents = elParent.contents(),
262                         idx = parentContents.index(el[0]),
263                         prev = idx > 0 ? parentContents[idx-1] : null,
264                         next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
265                         target, key;
266
267                     if(where === 'above') {
268                         target = prev ? $(prev) : elParent;
269                         key = prev ? 'orig_after' : 'orig_begin';
270                     } else if(where === 'below') {
271                         target = next ? $(next) : elParent;
272                         key = next ? 'orig_before' : 'orig_end';
273                     } else { throw new Error();}
274
275                     target.data(formatter_prefix + key, toAdd);
276                     if(transformed !== undefined) {
277                         target.data(formatter_prefix + key + '_transformed', transformed);
278                     }
279                     if(original !== undefined) {
280                         target.data(formatter_prefix + key + '_original', original);
281                     }
282                 };
283
284                 text.transformed = text.trimmed;
285
286                 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
287                     var startSpace = /\s/g.test(text.original.substr(0,1)),
288                         endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
289                     text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
290                     text.transformed += text.trimmed;
291                     text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
292                 } else {
293                     if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
294                         text.transformed = ' ';
295                     }
296                 }
297
298                 if(!text.transformed  && !onlyChild) {
299                     addInfo(text.original, 'below');
300                     el.remove();
301                     return true; // continue
302                 }
303
304                 if(text.transformed !== text.original) {
305                     // if(!text.trimmed) {
306                     //     addInfo(text.original, 'below');
307                     // } else {
308                         var startingMatch = text.original.match(/^\s+/g),
309                             endingMatch = text.original.match(/\s+$/g),
310                             startingWhiteSpace = startingMatch ? startingMatch[0] : null,
311                             endingWhiteSpace = endingMatch ? endingMatch[0] : null;
312
313                         if(endingWhiteSpace) {
314                             if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
315                                 endingWhiteSpace = endingWhiteSpace.substr(1);
316                             }
317                             addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
318                         }
319
320                         if(startingWhiteSpace && text.trimmed) {
321                             if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
322                                 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
323                             }
324                             addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
325                         }
326                     //}
327                 }
328                 /* globals document */
329                 el.replaceWith(document.createTextNode(text.transformed));
330             });
331         
332
333     },
334
335     registerClassTransformation: function(Transformation, className) {
336         var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || {});
337         thisClassTransformations[Transformation.prototype.name] = function() {
338             var nodeInstance = this;
339             var args = Array.prototype.slice.call(arguments, 0);
340             return nodeInstance.transform(Transformation, args);
341         };
342     },
343
344     registerClassMethod: function(methodName, method, className) {
345         var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
346         thisClassMethods[methodName] = method;
347     },
348
349     registerExtension: function(extension) {
350         smartxml.Document.prototype.registerExtension.call(this, extension);
351         var doc = this;
352
353         _.pairs(extension.wlxmlClass).forEach(function(pair) {
354             var className = pair[0],
355                 classExtension = pair[1];
356
357             _.pairs(classExtension.methods || {}).forEach(function(pair) {
358                 var name = pair[0],
359                     method = pair[1];
360                 doc.registerClassMethod(name, method, className);
361             });
362
363             _.pairs(classExtension.transformations || {}).forEach(function(pair) {
364                 var name = pair[0],
365                     desc = pair[1];
366                 doc.registerClassTransformation(transformations.createContextTransformation(desc, name), className);
367             });
368         });
369
370     }
371
372 });
373
374 return {
375     WLXMLDocumentFromXML: function(xml, options, Factory) {
376         Factory = Factory || WLXMLDocument;
377         return new Factory(xml, options);
378     },
379     WLXMLElementNodeFromXML: function(xml) {
380         return this.WLXMLDocumentFromXML(xml).root;
381     },
382
383     WLXMLDocument: WLXMLDocument,
384     getClassHierarchy: getClassLists
385 };
386
387 });