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