wlxml: metadata wip - first approach
[fnpeditor.git] / src / wlxml / wlxml.js
1 define([
2     'libs/jquery',
3     'libs/underscore',
4     'smartxml/smartxml',
5     'smartxml/transformations'
6 ], function($, _, smartxml, transformations) {
7     
8 'use strict';
9
10 /* globals Node */
11 var metadataKey = 'wlxml.metadata';
12
13
14 var AttributesList = function() {};
15 AttributesList.prototype = Object.create({});
16 AttributesList.prototype.keys = function() {
17     return _.keys(this);
18 };
19
20 var installObject = function(instance, klass) {
21     var methods = instance.document.classMethods[klass] || {},
22         transformations = instance.document.classTransformations[klass] || {};
23
24     instance.object = Object.create(_.extend({}, methods, transformations));
25     _.keys(methods).concat(_.keys(transformations)).forEach(function(key) {
26         instance.object[key] = _.bind(instance.object[key], instance);
27     });
28 };
29
30 var WLXMLElementNode = function(nativeNode, document) {
31     smartxml.ElementNode.call(this, nativeNode, document);
32     installObject(this, this.getClass());
33 };
34 WLXMLElementNode.prototype = Object.create(smartxml.ElementNode.prototype);
35
36 $.extend(WLXMLElementNode.prototype, smartxml.ElementNode.prototype, {
37     getClass: function() {
38         return this.getAttr('class') || '';
39     },
40     setClass: function(klass) {
41         if(klass !== this.klass) {
42             installObject(this, klass);
43             return this.setAttr('class', klass);
44         }
45     },
46     is: function(klass) {
47         return this.getClass().substr(0, klass.length) === klass;
48     },
49     getMetaAttributes: function() {
50         var toret = new AttributesList(),
51             classParts = [''].concat(this.getClass().split('.')),
52             classCurrent, classDesc;
53
54         classParts.forEach(function(part) {
55             classCurrent = classCurrent ? classCurrent + '.' + part : part;
56             classDesc = this.document.options.wlxmlClasses[classCurrent];
57             if(classDesc) {
58                 _.keys(classDesc.attrs).forEach(function(attrName) {
59                     toret[attrName] = _.extend({value: this.getAttr(attrName)}, classDesc.attrs[attrName]);
60                 }.bind(this));
61             }
62         }.bind(this));
63         return toret;
64     },
65     setMetaAttribute: function(key, value) {
66         this.setAttr(key, value);
67     },
68     getOtherAttributes: function() {
69         var toret = {},
70             node = this;
71         this.getAttrs().forEach(function(attr) {
72             if(attr.name !== 'class' && !node.isMetaAttribute(attr.name)) {
73                 toret[attr.name] = {value: attr.value};
74             }
75         });
76         return toret;
77     },
78     isMetaAttribute: function(attrName) {
79         return attrName !== 'class' &&_.contains(_.keys(this.getMetaAttributes()), attrName);
80     },
81
82     getMetadata: function() {
83         return this.getData(metadataKey) || [];
84     },
85
86     addMetadataRow: function(row) {
87         this.setMetadataRow(null, row);
88     },
89
90     setMetadataRow: function(index, row) {
91         var metadata = this.getData(metadataKey) || [];
92         if(typeof index !== 'number' || index > metadata.length - 1) {
93             metadata.push(row);
94             index = metadata.length - 1;
95         } else {
96             metadata[index] = _.extend(metadata[index], row);
97         }
98         this.setData(metadataKey, metadata);
99         this.triggerChangeEvent('metadataChange', {index: index});
100     },
101
102     _getXMLDOMToDump: function() {
103         var DOM = this._$.clone(true, true),
104             doc = this.document;
105
106         DOM.find('*').addBack().each(function() {
107             var el = $(this),
108                 parent = el.parent(),
109                 contents = parent.contents(),
110                 idx = contents.index(el),
111                 data = el.data();
112
113
114             var txt, documentNode, metaNode;
115
116             if(data[formatter_prefix+ 'orig_before']) {
117                 txt = idx > 0 && contents[idx-1].nodeType === Node.TEXT_NODE ? contents[idx-1] : null;
118                 if(txt && txt.data === data[formatter_prefix + 'orig_before_transformed']) {
119                     txt.data = data[formatter_prefix+ 'orig_before_original'];
120                 } else {
121                     el.before(data[formatter_prefix+ 'orig_before']);
122                 }
123             }
124             if(data[formatter_prefix+ 'orig_after']) {
125                 txt = idx < contents.length-1 && contents[idx+1].nodeType === Node.TEXT_NODE ? contents[idx+1] : null;
126                 if(txt && txt.data === data[formatter_prefix + 'orig_after_transformed']) {
127                     txt.data = data[formatter_prefix+ 'orig_after_original'];
128                 } else {
129                     el.after(data[formatter_prefix+ 'orig_after']);
130                 }
131             }
132             if(data[formatter_prefix+ 'orig_begin']) {
133                 el.prepend(data[formatter_prefix+ 'orig_begin']);
134             }
135             if(data[formatter_prefix+ 'orig_end']) {
136                 contents = el.contents();
137                 txt = (contents.length && contents[contents.length-1].nodeType === Node.TEXT_NODE) ? contents[contents.length-1] : null;
138                 if(txt && txt.data === data[formatter_prefix + 'orig_end_transformed']) {
139                     txt.data = data[formatter_prefix+ 'orig_end_original'];
140                 } else {
141                     el.append(data[formatter_prefix+ 'orig_end']);
142                 }
143             }
144
145
146             if(this.nodeType === Node.ELEMENT_NODE) {
147                 documentNode = doc.createDocumentNode(this);
148                 metaNode = $('<metadata>');
149                 documentNode.getMetadata().forEach(function(row) {
150                     metaNode.append('<dc:'+ row.key + '>' + row.value + '</dc:' + row.key + '>');
151                 });
152                 if(metaNode.children().length) {
153                     $(this).prepend(metaNode);
154                 }
155             }
156
157         });
158
159         
160
161         return DOM;
162     }
163 });
164
165 // WLXMLElementNode.prototype.transformations.register(transformations.createContextTransformation({
166 //     name: 'wlxml.setMetaAttribute',
167 //     impl: function(args) {
168 //         this.setMetaAttribute(args.name, args.value);
169 //     },
170 //     getChangeRoot: function() {
171 //         return this.context;
172 //     }
173 // }));
174
175
176
177 var WLXMLDocumentNode = function() {
178     smartxml.DocumentNode.apply(this, arguments);
179 };
180 WLXMLDocumentNode.prototype = Object.create(smartxml.DocumentNode.prototype);
181
182 var WLXMLDocument = function(xml, options) {
183     this.classMethods = {};
184     this.classTransformations = {};
185     smartxml.Document.call(this, xml);
186     this.options = options;
187 };
188
189 var formatter_prefix = '_wlxml_formatter_';
190
191
192 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
193 $.extend(WLXMLDocument.prototype, {
194     ElementNodeFactory: WLXMLElementNode,
195     loadXML: function(xml) {
196         smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
197         this.trigger('contentSet');
198     },
199
200     normalizeXML: function(nativeNode) {
201         var doc = this,
202             prefixLength = 'dc:'.length;
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         $(nativeNode).find('metadata').each(function() {
288             var metadataNode = $(this),
289                 owner = doc.createDocumentNode(metadataNode.parent()[0]);
290                 
291             metadataNode.children().each(function() {
292                 owner.addMetadataRow({key: (this.tagName).toLowerCase().substr(prefixLength), value: $(this).text()});
293             });
294             metadataNode.remove();
295         });
296     },
297
298     registerClassTransformation: function(Transformation, className) {
299         var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || {});
300         thisClassTransformations[Transformation.prototype.name] = function(args) {
301             var nodeInstance = this;
302             return nodeInstance.transform(Transformation, args);
303         };
304     },
305
306     registerClassMethod: function(methodName, method, className) {
307         var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
308         thisClassMethods[methodName] = method;
309     },
310
311     registerExtension: function(extension) {
312         //debugger;
313         smartxml.Document.prototype.registerExtension.call(this, extension);
314         var doc = this;
315
316         _.pairs(extension.wlxmlClass).forEach(function(pair) {
317             var className = pair[0],
318                 classExtension = pair[1];
319
320             _.pairs(classExtension.methods || {}).forEach(function(pair) {
321                 var name = pair[0],
322                     method = pair[1];
323                 doc.registerClassMethod(name, method, className);
324             });
325
326             _.pairs(classExtension.transformations || {}).forEach(function(pair) {
327                 var name = pair[0],
328                     desc = pair[1];
329                 doc.registerClassTransformation(transformations.createContextTransformation(desc, name), className);
330             });
331         });
332
333     }
334
335 });
336
337 var wlxmlClasses = {
338     'link': {
339         attrs: {href: {type: 'string'}}
340     }
341 };
342
343
344 return {
345     WLXMLDocumentFromXML: function(xml, options) {
346         options = _.extend({wlxmlClasses: wlxmlClasses}, options);
347         return new WLXMLDocument(xml, options);
348     },
349
350     WLXMLElementNodeFromXML: function(xml) {
351         return this.WLXMLDocumentFromXML(xml).root;
352     }
353 };
354
355 });