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