wlxml: inheritance support for WLXML class methods and transformations
[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 AttributesList = function() {};
15 AttributesList.prototype = Object.create({});
16 AttributesList.prototype.keys = function() {
17     return _.keys(this);
18 };
19
20 var getClassLists = function(klassName) {
21     var toret = [],
22         classParts = [''].concat(klassName.split('.')),
23         classCurrent;
24
25     classParts.forEach(function(part) {
26         classCurrent = classCurrent ? classCurrent + '.' + part : part;
27         toret.push(classCurrent);
28     });
29     return toret;
30 };
31
32 var installObject = function(instance, klass) {
33     var methods = {},
34         transformations = {};
35
36     getClassLists(klass).forEach(function(klassName) {
37         _.extend(methods, instance.document.classMethods[klassName] || {});
38         _.extend(methods, instance.document.classTransformations[klassName] || {});
39     });
40     instance.object = Object.create(_.extend({}, methods, transformations));
41     _.keys(methods).concat(_.keys(transformations)).forEach(function(key) {
42         instance.object[key] = _.bind(instance.object[key], instance);
43     });
44 };
45
46 var WLXMLElementNode = function(nativeNode, document) {
47     smartxml.ElementNode.call(this, nativeNode, document);
48     installObject(this, this.getClass());
49 };
50 WLXMLElementNode.prototype = Object.create(smartxml.ElementNode.prototype);
51
52 $.extend(WLXMLElementNode.prototype, smartxml.ElementNode.prototype, {
53     getClass: function() {
54         return this.getAttr('class') || '';
55     },
56     setClass: function(klass) {
57         if(klass !== this.klass) {
58             installObject(this, klass);
59             return this.setAttr('class', klass);
60         }
61     },
62     is: function(klass) {
63         return this.getClass().substr(0, klass.length) === klass;
64     },
65     getMetaAttributes: function() {
66         var toret = new AttributesList(),
67             classParts = [''].concat(this.getClass().split('.')),
68             classCurrent, classDesc;
69
70         classParts.forEach(function(part) {
71             classCurrent = classCurrent ? classCurrent + '.' + part : part;
72             classDesc = this.document.options.wlxmlClasses[classCurrent];
73             if(classDesc) {
74                 _.keys(classDesc.attrs).forEach(function(attrName) {
75                     toret[attrName] = _.extend({value: this.getAttr(attrName)}, classDesc.attrs[attrName]);
76                 }.bind(this));
77             }
78         }.bind(this));
79         return toret;
80     },
81     setMetaAttribute: function(key, value) {
82         this.setAttr(key, value);
83     },
84     getOtherAttributes: function() {
85         var toret = {},
86             node = this;
87         this.getAttrs().forEach(function(attr) {
88             if(attr.name !== 'class' && !node.isMetaAttribute(attr.name)) {
89                 toret[attr.name] = {value: attr.value};
90             }
91         });
92         return toret;
93     },
94     isMetaAttribute: function(attrName) {
95         return attrName !== 'class' &&_.contains(_.keys(this.getMetaAttributes()), attrName);
96     },
97
98     _getXMLDOMToDump: function() {
99         var DOM = this._$.clone(true, true),
100             doc = this.document;
101
102         DOM.find('*').addBack().each(function() {
103             var el = $(this),
104                 parent = el.parent(),
105                 contents = parent.contents(),
106                 idx = contents.index(el),
107                 data = el.data();
108
109
110             var txt, documentNode, metaNode;
111
112             if(data[formatter_prefix+ 'orig_before']) {
113                 txt = idx > 0 && contents[idx-1].nodeType === Node.TEXT_NODE ? contents[idx-1] : null;
114                 if(txt && txt.data === data[formatter_prefix + 'orig_before_transformed']) {
115                     txt.data = data[formatter_prefix+ 'orig_before_original'];
116                 } else {
117                     el.before(data[formatter_prefix+ 'orig_before']);
118                 }
119             }
120             if(data[formatter_prefix+ 'orig_after']) {
121                 txt = idx < contents.length-1 && contents[idx+1].nodeType === Node.TEXT_NODE ? contents[idx+1] : null;
122                 if(txt && txt.data === data[formatter_prefix + 'orig_after_transformed']) {
123                     txt.data = data[formatter_prefix+ 'orig_after_original'];
124                 } else {
125                     el.after(data[formatter_prefix+ 'orig_after']);
126                 }
127             }
128             if(data[formatter_prefix+ 'orig_begin']) {
129                 el.prepend(data[formatter_prefix+ 'orig_begin']);
130             }
131             if(data[formatter_prefix+ 'orig_end']) {
132                 contents = el.contents();
133                 txt = (contents.length && contents[contents.length-1].nodeType === Node.TEXT_NODE) ? contents[contents.length-1] : null;
134                 if(txt && txt.data === data[formatter_prefix + 'orig_end_transformed']) {
135                     txt.data = data[formatter_prefix+ 'orig_end_original'];
136                 } else {
137                     el.append(data[formatter_prefix+ 'orig_end']);
138                 }
139             }
140
141
142             if(this.nodeType === Node.ELEMENT_NODE) {
143                 documentNode = doc.createDocumentNode(this);
144                 metaNode = $('<metadata>');
145                 documentNode.getMetadata().forEach(function(row) {
146                     metaNode.append('<dc:'+ row.key + '>' + row.value + '</dc:' + row.key + '>');
147                 });
148                 if(metaNode.children().length) {
149                     $(this).prepend(metaNode);
150                 }
151             }
152
153         });
154
155         
156
157         return DOM;
158     }
159 });
160
161 // WLXMLElementNode.prototype.transformations.register(transformations.createContextTransformation({
162 //     name: 'wlxml.setMetaAttribute',
163 //     impl: function(args) {
164 //         this.setMetaAttribute(args.name, args.value);
165 //     },
166 //     getChangeRoot: function() {
167 //         return this.context;
168 //     }
169 // }));
170
171
172
173 var WLXMLDocumentNode = function() {
174     smartxml.DocumentNode.apply(this, arguments);
175 };
176 WLXMLDocumentNode.prototype = Object.create(smartxml.DocumentNode.prototype);
177
178 var WLXMLDocument = function(xml, options) {
179     this.classMethods = {};
180     this.classTransformations = {};
181     smartxml.Document.call(this, xml, [metadataExtension]);
182     this.options = options;
183 };
184
185 var formatter_prefix = '_wlxml_formatter_';
186
187
188 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
189 $.extend(WLXMLDocument.prototype, {
190     ElementNodeFactory: WLXMLElementNode,
191     loadXML: function(xml) {
192         smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
193         this.trigger('contentSet');
194     },
195
196     normalizeXML: function(nativeNode) {
197         var doc = this,
198             prefixLength = 'dc:'.length;
199
200         $(nativeNode).find('metadata').each(function() {
201             var metadataNode = $(this),
202                 owner = doc.createDocumentNode(metadataNode.parent()[0]),
203                 metadata = owner.getMetadata();
204                 
205             metadataNode.children().each(function() {
206                 metadata.add({key: (this.tagName).toLowerCase().substr(prefixLength), value: $(this).text()}, {undoable: false});
207             });
208             metadataNode.remove();
209         });
210         nativeNode.normalize();
211
212         $(nativeNode).find(':not(iframe)').addBack().contents()
213             .filter(function() {return this.nodeType === Node.TEXT_NODE;})
214             .each(function() {
215                 var el = $(this),
216                     text = {original: el.text(), trimmed: $.trim(el.text())},
217                     elParent = el.parent(),
218                     hasSpanParent = elParent.prop('tagName') === 'SPAN',
219                     hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
220                     hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
221
222
223                 var addInfo = function(toAdd, where, transformed, original) {
224                     var parentContents = elParent.contents(),
225                         idx = parentContents.index(el[0]),
226                         prev = idx > 0 ? parentContents[idx-1] : null,
227                         next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
228                         target, key;
229
230                     if(where === 'above') {
231                         target = prev ? $(prev) : elParent;
232                         key = prev ? 'orig_after' : 'orig_begin';
233                     } else if(where === 'below') {
234                         target = next ? $(next) : elParent;
235                         key = next ? 'orig_before' : 'orig_end';
236                     } else { throw new Error();}
237
238                     target.data(formatter_prefix + key, toAdd);
239                     if(transformed !== undefined) {
240                         target.data(formatter_prefix + key + '_transformed', transformed);
241                     }
242                     if(original !== undefined) {
243                         target.data(formatter_prefix + key + '_original', original);
244                     }
245                 };
246
247                 text.transformed = text.trimmed;
248
249                 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
250                     var startSpace = /\s/g.test(text.original.substr(0,1)),
251                         endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
252                     text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
253                     text.transformed += text.trimmed;
254                     text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
255                 } else {
256                     if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
257                         text.transformed = ' ';
258                     }
259                 }
260
261                 if(!text.transformed) {
262                     addInfo(text.original, 'below');
263                     el.remove();
264                     return true; // continue
265                 }
266
267                 if(text.transformed !== text.original) {
268                     // if(!text.trimmed) {
269                     //     addInfo(text.original, 'below');
270                     // } else {
271                         var startingMatch = text.original.match(/^\s+/g),
272                             endingMatch = text.original.match(/\s+$/g),
273                             startingWhiteSpace = startingMatch ? startingMatch[0] : null,
274                             endingWhiteSpace = endingMatch ? endingMatch[0] : null;
275
276                         if(endingWhiteSpace) {
277                             if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
278                                 endingWhiteSpace = endingWhiteSpace.substr(1);
279                             }
280                             addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
281                         }
282
283                         if(startingWhiteSpace && text.trimmed) {
284                             if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
285                                 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
286                             }
287                             addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
288                         }
289                     //}
290                 }
291                 /* globals document */
292                 el.replaceWith(document.createTextNode(text.transformed));
293             });
294         
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 });