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