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