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