01ab8697b198d7928c11844ab8389e63d3649cd7
[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];
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
173     this.TextNodeFactory = function() {
174         smartxml.TextNode.apply(this, arguments);
175     }
176     this.TextNodeFactory.prototype = Object.create(smartxml.TextNode.prototype);
177     this.TextNodeFactory.prototype.transformations = new transformations.TransformationStorage();
178
179     this.classMethods = {};
180     this.classTransformations = {};
181 };
182
183 var formatter_prefix = '_wlxml_formatter_';
184
185
186 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
187 $.extend(WLXMLDocument.prototype, {
188     ElementNodeFactory: WLXMLElementNode,
189     loadXML: function(xml) {
190         smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
191         $(this.dom).find(':not(iframe)').addBack().contents()
192             .filter(function() {return this.nodeType === Node.TEXT_NODE;})
193             .each(function() {
194                 var el = $(this),
195                     text = {original: el.text(), trimmed: $.trim(el.text())},
196                     elParent = el.parent(),
197                     hasSpanParent = elParent.prop('tagName') === 'SPAN',
198                     hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
199                     hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
200
201
202                 var addInfo = function(toAdd, where, transformed, original) {
203                     var parentContents = elParent.contents(),
204                         idx = parentContents.index(el[0]),
205                         prev = idx > 0 ? parentContents[idx-1] : null,
206                         next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
207                         target, key;
208
209                     if(where === 'above') {
210                         target = prev ? $(prev) : elParent;
211                         key = prev ? 'orig_after' : 'orig_begin';
212                     } else if(where === 'below') {
213                         target = next ? $(next) : elParent;
214                         key = next ? 'orig_before' : 'orig_end';
215                     } else { throw new Error();}
216
217                     target.data(formatter_prefix + key, toAdd);
218                     if(transformed !== undefined) {
219                         target.data(formatter_prefix + key + '_transformed', transformed);
220                     }
221                     if(original !== undefined) {
222                         target.data(formatter_prefix + key + '_original', original);
223                     }
224                 };
225
226                 text.transformed = text.trimmed;
227
228                 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
229                     var startSpace = /\s/g.test(text.original.substr(0,1)),
230                         endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
231                     text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
232                     text.transformed += text.trimmed;
233                     text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
234                 } else {
235                     if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
236                         text.transformed = ' ';
237                     }
238                 }
239
240                 if(!text.transformed) {
241                     addInfo(text.original, 'below');
242                     el.remove();
243                     return true; // continue
244                 }
245
246                 if(text.transformed !== text.original) {
247                     // if(!text.trimmed) {
248                     //     addInfo(text.original, 'below');
249                     // } else {
250                         var startingMatch = text.original.match(/^\s+/g),
251                             endingMatch = text.original.match(/\s+$/g),
252                             startingWhiteSpace = startingMatch ? startingMatch[0] : null,
253                             endingWhiteSpace = endingMatch ? endingMatch[0] : null;
254
255                         if(endingWhiteSpace) {
256                             if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
257                                 endingWhiteSpace = endingWhiteSpace.substr(1);
258                             }
259                             addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
260                         }
261
262                         if(startingWhiteSpace && text.trimmed) {
263                             if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
264                                 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
265                             }
266                             addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
267                         }
268                     //}
269                 }
270
271                 el.replaceWith(document.createTextNode(text.transformed));
272             });
273         this.trigger('contentSet');
274     },
275
276     registerExtension: function(extension) {
277         //debugger;
278         var doc = this,
279             existingPropertyNames = _.values(this);
280
281         var getTrans = function(desc, methodName) {
282             if(typeof desc === 'function') {
283                 desc = {impl: desc};
284             }
285             if(!desc.impl) {
286                 throw new Error('Got transformation description without implementation.')
287             }
288             desc.name = desc.name || methodName;
289             return desc;
290         };
291
292         [
293             {source: extension.document, target: doc},
294             {source: extension.documentNode, target: [doc.ElementNodeFactory.prototype, doc.TextNodeFactory.prototype]},
295
296         ].forEach(function(mapping) {
297             if(mapping.source) {
298                 if(mapping.source.methods) {
299                     existingPropertyNames = _.values(mapping.target)
300                     _.pairs(mapping.source.methods).forEach(function(pair) {
301                         var methodName = pair[0],
302                             method = pair[1],
303                             targets = _.isArray(mapping.target) ? mapping.target : [mapping.target];
304                         if(_.contains(existingPropertyNames, methodName)) {
305                             throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
306                                 .replace('{target}', mapping.target)
307                                 .replace('{methodName}', methodName)
308                             );
309                         }
310                         targets.forEach(function(target) {
311                             target[methodName] = method;
312                         });
313                     });
314                 }
315
316                 if(mapping.source.transformations) {
317                     _.pairs(mapping.source.transformations).forEach(function(pair) {
318                         var transformation = getTrans(pair[1], pair[0]),
319                             targets = _.isArray(mapping.target) ? mapping.target : [mapping.target];
320                         targets.forEach(function(target) {
321                             target.transformations.register(transformations.createContextTransformation(transformation));
322                         });
323                     });
324                 }
325             }
326         });
327
328         _.pairs(extension.wlxmlClass).forEach(function(pair) {
329             var className = pair[0],
330                 classExtension = pair[1],
331                 thisClassMethods = (doc.classMethods[className] = doc.classMethods[className] || {}),
332                 thisClassTransformations = (doc.classTransformations[className] = doc.classTransformations[className] || new transformations.TransformationStorage());
333     
334             _.extend(thisClassMethods, classExtension.methods || {}); //@ warning/throw on override?
335             
336
337             _.pairs(classExtension.transformations || {}).forEach(function(pair) {
338                 var transformation = getTrans(pair[1], pair[0]);
339                 thisClassTransformations.register(transformations.createContextTransformation(transformation));
340             }); 
341         });
342
343     }
344
345 });
346
347 var wlxmlClasses = {
348     'uri': {
349         attrs: {uri: {type: 'string'}}
350     }
351 };
352
353 var classMethods = {};
354
355 return {
356     WLXMLDocumentFromXML: function(xml, options) {
357         options = _.extend({wlxmlClasses: wlxmlClasses}, options);
358         return new WLXMLDocument(xml, options);
359     },
360
361     WLXMLElementNodeFromXML: function(xml) {
362         return this.WLXMLDocumentFromXML(xml).root;
363     },
364
365     registerExtension: function(extension) {
366         // @@ depracated
367         if(extension.documentTransformations) {
368             extension.documentTransformations.forEach(function(method) {
369                 WLXMLDocument.prototype.transformations.register(transformations.createContextTransformation(method));
370             });
371         }
372
373         _.pairs(extension.classMethods).forEach(function(pair) {
374             var className = pair[0],
375                 methods = pair[1];
376             _.pairs(methods).forEach(function(pair) {
377                 var methodName = pair[0],
378                     method = pair[1];
379                 classMethods[className] = classMethods[className] || {};
380                 classMethods[className][methodName] = method;
381             });
382             
383         });
384
385         _.extend(WLXMLDocument.prototype, extension.documentMethods);
386
387     }
388
389 };
390
391 });