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