editor: handle invalid xml sent as a wlxml document
[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
13 var AttributesList = function() {};
14 AttributesList.prototype = Object.create({});
15 AttributesList.prototype.keys = function() {
16     return _.keys(this);
17 };
18
19 var installObject = function(instance, klass) {
20     var methods = instance.document.classMethods[klass] || {},
21         transformations = instance.document.classTransformations[klass] || {};
22
23     instance.object = Object.create(_.extend({}, methods, transformations));
24     _.keys(methods).concat(_.keys(transformations)).forEach(function(key) {
25         instance.object[key] = _.bind(instance.object[key], instance);
26     });
27 };
28
29 var WLXMLElementNode = function(nativeNode, document) {
30     smartxml.ElementNode.call(this, nativeNode, document);
31     installObject(this, this.getClass());
32 };
33 WLXMLElementNode.prototype = Object.create(smartxml.ElementNode.prototype);
34
35 $.extend(WLXMLElementNode.prototype, smartxml.ElementNode.prototype, {
36     getClass: function() {
37         return this.getAttr('class') || '';
38     },
39     setClass: function(klass) {
40         if(klass !== this.klass) {
41             installObject(this, klass);
42             return this.setAttr('class', klass);
43         }
44     },
45     is: function(klass) {
46         return this.getClass().substr(0, klass.length) === klass;
47     },
48     getMetaAttributes: function() {
49         var toret = new AttributesList(),
50             classParts = [''].concat(this.getClass().split('.')),
51             classCurrent, classDesc;
52
53         classParts.forEach(function(part) {
54             classCurrent = classCurrent ? classCurrent + '.' + part : part;
55             classDesc = this.document.options.wlxmlClasses[classCurrent];
56             if(classDesc) {
57                 _.keys(classDesc.attrs).forEach(function(attrName) {
58                     toret[attrName] = _.extend({value: this.getAttr(attrName)}, classDesc.attrs[attrName]);
59                 }.bind(this));
60             }
61         }.bind(this));
62         return toret;
63     },
64     setMetaAttribute: function(key, value) {
65         this.setAttr(key, value);
66     },
67     getOtherAttributes: function() {
68         var toret = {},
69             node = this;
70         this.getAttrs().forEach(function(attr) {
71             if(attr.name !== 'class' && !node.isMetaAttribute(attr.name)) {
72                 toret[attr.name] = {value: attr.value};
73             }
74         });
75         return toret;
76     },
77     isMetaAttribute: function(attrName) {
78         return attrName !== 'class' &&_.contains(_.keys(this.getMetaAttributes()), attrName);
79     },
80
81     _getXMLDOMToDump: function() {
82         var DOM = this._$.clone(true, true);
83
84         DOM.find('*').addBack().each(function() {
85             var el = $(this),
86                 parent = el.parent(),
87                 contents = parent.contents(),
88                 idx = contents.index(el),
89                 data = el.data();
90
91
92             var txt;
93
94             if(data[formatter_prefix+ 'orig_before']) {
95                 txt = idx > 0 && contents[idx-1].nodeType === Node.TEXT_NODE ? contents[idx-1] : null;
96                 if(txt && txt.data === data[formatter_prefix + 'orig_before_transformed']) {
97                     txt.data = data[formatter_prefix+ 'orig_before_original'];
98                 } else {
99                     el.before(data[formatter_prefix+ 'orig_before']);
100                 }
101             }
102             if(data[formatter_prefix+ 'orig_after']) {
103                 txt = idx < contents.length-1 && contents[idx+1].nodeType === Node.TEXT_NODE ? contents[idx+1] : null;
104                 if(txt && txt.data === data[formatter_prefix + 'orig_after_transformed']) {
105                     txt.data = data[formatter_prefix+ 'orig_after_original'];
106                 } else {
107                     el.after(data[formatter_prefix+ 'orig_after']);
108                 }
109             }
110             if(data[formatter_prefix+ 'orig_begin']) {
111                 el.prepend(data[formatter_prefix+ 'orig_begin']);
112             }
113             if(data[formatter_prefix+ 'orig_end']) {
114                 contents = el.contents();
115                 txt = (contents.length && contents[contents.length-1].nodeType === Node.TEXT_NODE) ? contents[contents.length-1] : null;
116                 if(txt && txt.data === data[formatter_prefix + 'orig_end_transformed']) {
117                     txt.data = data[formatter_prefix+ 'orig_end_original'];
118                 } else {
119                     el.append(data[formatter_prefix+ 'orig_end']);
120                 }
121             }
122         });
123
124         return DOM;
125     }
126 });
127
128 // WLXMLElementNode.prototype.transformations.register(transformations.createContextTransformation({
129 //     name: 'wlxml.setMetaAttribute',
130 //     impl: function(args) {
131 //         this.setMetaAttribute(args.name, args.value);
132 //     },
133 //     getChangeRoot: function() {
134 //         return this.context;
135 //     }
136 // }));
137
138
139
140 var WLXMLDocumentNode = function() {
141     smartxml.DocumentNode.apply(this, arguments);
142 };
143 WLXMLDocumentNode.prototype = Object.create(smartxml.DocumentNode.prototype);
144
145 var WLXMLDocument = function(xml, options) {
146     smartxml.Document.call(this, xml);
147     this.options = options;
148
149     this.classMethods = {};
150     this.classTransformations = {};
151 };
152
153 var formatter_prefix = '_wlxml_formatter_';
154
155
156 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
157 $.extend(WLXMLDocument.prototype, {
158     ElementNodeFactory: WLXMLElementNode,
159     loadXML: function(xml) {
160         smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
161         this.trigger('contentSet');
162     },
163
164     normalizeXML: function(nativeNode) {
165         $(nativeNode).find(':not(iframe)').addBack().contents()
166             .filter(function() {return this.nodeType === Node.TEXT_NODE;})
167             .each(function() {
168                 var el = $(this),
169                     text = {original: el.text(), trimmed: $.trim(el.text())},
170                     elParent = el.parent(),
171                     hasSpanParent = elParent.prop('tagName') === 'SPAN',
172                     hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
173                     hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
174
175
176                 var addInfo = function(toAdd, where, transformed, original) {
177                     var parentContents = elParent.contents(),
178                         idx = parentContents.index(el[0]),
179                         prev = idx > 0 ? parentContents[idx-1] : null,
180                         next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
181                         target, key;
182
183                     if(where === 'above') {
184                         target = prev ? $(prev) : elParent;
185                         key = prev ? 'orig_after' : 'orig_begin';
186                     } else if(where === 'below') {
187                         target = next ? $(next) : elParent;
188                         key = next ? 'orig_before' : 'orig_end';
189                     } else { throw new Error();}
190
191                     target.data(formatter_prefix + key, toAdd);
192                     if(transformed !== undefined) {
193                         target.data(formatter_prefix + key + '_transformed', transformed);
194                     }
195                     if(original !== undefined) {
196                         target.data(formatter_prefix + key + '_original', original);
197                     }
198                 };
199
200                 text.transformed = text.trimmed;
201
202                 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
203                     var startSpace = /\s/g.test(text.original.substr(0,1)),
204                         endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
205                     text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
206                     text.transformed += text.trimmed;
207                     text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
208                 } else {
209                     if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
210                         text.transformed = ' ';
211                     }
212                 }
213
214                 if(!text.transformed) {
215                     addInfo(text.original, 'below');
216                     el.remove();
217                     return true; // continue
218                 }
219
220                 if(text.transformed !== text.original) {
221                     // if(!text.trimmed) {
222                     //     addInfo(text.original, 'below');
223                     // } else {
224                         var startingMatch = text.original.match(/^\s+/g),
225                             endingMatch = text.original.match(/\s+$/g),
226                             startingWhiteSpace = startingMatch ? startingMatch[0] : null,
227                             endingWhiteSpace = endingMatch ? endingMatch[0] : null;
228
229                         if(endingWhiteSpace) {
230                             if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
231                                 endingWhiteSpace = endingWhiteSpace.substr(1);
232                             }
233                             addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
234                         }
235
236                         if(startingWhiteSpace && text.trimmed) {
237                             if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
238                                 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
239                             }
240                             addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
241                         }
242                     //}
243                 }
244                 /* globals document */
245                 el.replaceWith(document.createTextNode(text.transformed));
246             });
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     'link': {
290         attrs: {href: {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 });