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