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