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