linting, cleanup, removing unused code
[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.dom).find(':not(iframe)').addBack().contents()
165             .filter(function() {return this.nodeType === Node.TEXT_NODE;})
166             .each(function() {
167                 var el = $(this),
168                     text = {original: el.text(), trimmed: $.trim(el.text())},
169                     elParent = el.parent(),
170                     hasSpanParent = elParent.prop('tagName') === 'SPAN',
171                     hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
172                     hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
173
174
175                 var addInfo = function(toAdd, where, transformed, original) {
176                     var parentContents = elParent.contents(),
177                         idx = parentContents.index(el[0]),
178                         prev = idx > 0 ? parentContents[idx-1] : null,
179                         next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
180                         target, key;
181
182                     if(where === 'above') {
183                         target = prev ? $(prev) : elParent;
184                         key = prev ? 'orig_after' : 'orig_begin';
185                     } else if(where === 'below') {
186                         target = next ? $(next) : elParent;
187                         key = next ? 'orig_before' : 'orig_end';
188                     } else { throw new Error();}
189
190                     target.data(formatter_prefix + key, toAdd);
191                     if(transformed !== undefined) {
192                         target.data(formatter_prefix + key + '_transformed', transformed);
193                     }
194                     if(original !== undefined) {
195                         target.data(formatter_prefix + key + '_original', original);
196                     }
197                 };
198
199                 text.transformed = text.trimmed;
200
201                 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
202                     var startSpace = /\s/g.test(text.original.substr(0,1)),
203                         endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
204                     text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
205                     text.transformed += text.trimmed;
206                     text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
207                 } else {
208                     if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
209                         text.transformed = ' ';
210                     }
211                 }
212
213                 if(!text.transformed) {
214                     addInfo(text.original, 'below');
215                     el.remove();
216                     return true; // continue
217                 }
218
219                 if(text.transformed !== text.original) {
220                     // if(!text.trimmed) {
221                     //     addInfo(text.original, 'below');
222                     // } else {
223                         var startingMatch = text.original.match(/^\s+/g),
224                             endingMatch = text.original.match(/\s+$/g),
225                             startingWhiteSpace = startingMatch ? startingMatch[0] : null,
226                             endingWhiteSpace = endingMatch ? endingMatch[0] : null;
227
228                         if(endingWhiteSpace) {
229                             if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
230                                 endingWhiteSpace = endingWhiteSpace.substr(1);
231                             }
232                             addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
233                         }
234
235                         if(startingWhiteSpace && text.trimmed) {
236                             if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
237                                 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
238                             }
239                             addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
240                         }
241                     //}
242                 }
243                 /* globals document */
244                 el.replaceWith(document.createTextNode(text.transformed));
245             });
246         this.trigger('contentSet');
247     },
248
249     registerClassTransformation: function(Transformation, className) {
250         var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || {});
251         thisClassTransformations[Transformation.prototype.name] = function(args) {
252             var nodeInstance = this;
253             return nodeInstance.transform(Transformation, args);
254         };
255     },
256
257     registerClassMethod: function(methodName, method, className) {
258         var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
259         thisClassMethods[methodName] = method;
260     },
261
262     registerExtension: function(extension) {
263         //debugger;
264         smartxml.Document.prototype.registerExtension.call(this, extension);
265         var doc = this;
266
267         _.pairs(extension.wlxmlClass).forEach(function(pair) {
268             var className = pair[0],
269                 classExtension = pair[1];
270
271             _.pairs(classExtension.methods || {}).forEach(function(pair) {
272                 var name = pair[0],
273                     method = pair[1];
274                 doc.registerClassMethod(name, method, className);
275             });
276
277             _.pairs(classExtension.transformations || {}).forEach(function(pair) {
278                 var name = pair[0],
279                     desc = pair[1];
280                 doc.registerClassTransformation(transformations.createContextTransformation(desc, name), className);
281             });
282         });
283
284     }
285
286 });
287
288 var wlxmlClasses = {
289     'uri': {
290         attrs: {uri: {type: 'string'}}
291     }
292 };
293
294
295 return {
296     WLXMLDocumentFromXML: function(xml, options) {
297         options = _.extend({wlxmlClasses: wlxmlClasses}, options);
298         return new WLXMLDocument(xml, options);
299     },
300
301     WLXMLElementNodeFromXML: function(xml) {
302         return this.WLXMLDocumentFromXML(xml).root;
303     }
304 };
305
306 });