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