empty text nodes after spans
[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             var emptyNode = this.childNodes.length === 0;
243             var endsWithSpan = !emptyNode && this.childNodes[this.childNodes.length - 1].nodeName.toLowerCase() === 'span';
244             if(emptyNode || endsWithSpan) {
245                 var fakeTextNode = window.document.createTextNode("");
246                 this.appendChild(fakeTextNode);
247             }
248         });
249
250         $(nativeNode).find(':not(iframe)').addBack().contents()
251             .filter(function() {return this.nodeType === Node.TEXT_NODE;})
252             .each(function() {
253                 var el = $(this),
254                     text = {original: el.text(), trimmed: $.trim(el.text())},
255                     elParent = el.parent(),
256                     hasSpanParent = elParent.prop('tagName') === 'SPAN',
257                     hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
258                     hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN',
259                     onlyChild = el.is(':only-child');
260
261
262                 var addInfo = function(toAdd, where, transformed, original) {
263                     var parentContents = elParent.contents(),
264                         idx = parentContents.index(el[0]),
265                         prev = idx > 0 ? parentContents[idx-1] : null,
266                         next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
267                         target, key;
268
269                     if(where === 'above') {
270                         target = prev ? $(prev) : elParent;
271                         key = prev ? 'orig_after' : 'orig_begin';
272                     } else if(where === 'below') {
273                         target = next ? $(next) : elParent;
274                         key = next ? 'orig_before' : 'orig_end';
275                     } else { throw new Error();}
276
277                     target.data(formatter_prefix + key, toAdd);
278                     if(transformed !== undefined) {
279                         target.data(formatter_prefix + key + '_transformed', transformed);
280                     }
281                     if(original !== undefined) {
282                         target.data(formatter_prefix + key + '_original', original);
283                     }
284                 };
285
286                 text.transformed = text.trimmed;
287
288                 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
289                     var startSpace = /\s/g.test(text.original.substr(0,1)),
290                         endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
291                     text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
292                     text.transformed += text.trimmed;
293                     text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
294                 } else {
295                     if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
296                         text.transformed = ' ';
297                     }
298                 }
299
300                 if(!text.transformed && !(el.is(':only-child') || (el.is(':last-child') && hasSpanBefore))) {
301                     addInfo(text.original, 'below');
302                     el.remove();
303                     return true; // continue
304                 }
305
306                 if(text.transformed !== text.original) {
307                     // if(!text.trimmed) {
308                     //     addInfo(text.original, 'below');
309                     // } else {
310                         var startingMatch = text.original.match(/^\s+/g),
311                             endingMatch = text.original.match(/\s+$/g),
312                             startingWhiteSpace = startingMatch ? startingMatch[0] : null,
313                             endingWhiteSpace = endingMatch ? endingMatch[0] : null;
314
315                         if(endingWhiteSpace) {
316                             if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
317                                 endingWhiteSpace = endingWhiteSpace.substr(1);
318                             }
319                             addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
320                         }
321
322                         if(startingWhiteSpace && text.trimmed) {
323                             if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
324                                 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
325                             }
326                             addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
327                         }
328                     //}
329                 }
330                 /* globals document */
331                 el.replaceWith(document.createTextNode(text.transformed));
332             });
333         
334
335     },
336
337     registerClassTransformation: function(Transformation, className) {
338         var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || {});
339         thisClassTransformations[Transformation.prototype.name] = function() {
340             var nodeInstance = this;
341             var args = Array.prototype.slice.call(arguments, 0);
342             return nodeInstance.transform(Transformation, args);
343         };
344     },
345
346     registerClassMethod: function(methodName, method, className) {
347         var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
348         thisClassMethods[methodName] = method;
349     },
350
351     registerExtension: function(extension) {
352         smartxml.Document.prototype.registerExtension.call(this, extension);
353         var doc = this;
354
355         _.pairs(extension.wlxmlClass).forEach(function(pair) {
356             var className = pair[0],
357                 classExtension = pair[1];
358
359             _.pairs(classExtension.methods || {}).forEach(function(pair) {
360                 var name = pair[0],
361                     method = pair[1];
362                 doc.registerClassMethod(name, method, className);
363             });
364
365             _.pairs(classExtension.transformations || {}).forEach(function(pair) {
366                 var name = pair[0],
367                     desc = pair[1];
368                 doc.registerClassTransformation(transformations.createContextTransformation(desc, name), className);
369             });
370         });
371
372     }
373
374 });
375
376 return {
377     WLXMLDocumentFromXML: function(xml, options, Factory) {
378         Factory = Factory || WLXMLDocument;
379         return new Factory(xml, options);
380     },
381     WLXMLElementNodeFromXML: function(xml) {
382         return this.WLXMLDocumentFromXML(xml).root;
383     },
384
385     WLXMLDocument: WLXMLDocument,
386     getClassHierarchy: getClassLists
387 };
388
389 });