wlxml: metadata wip - adding/removing/editing, undo, cloning support
[fnpeditor.git] / src / wlxml / wlxml.js
1 define([
2     'libs/jquery',
3     'libs/underscore',
4     'smartxml/smartxml',
5     'smartxml/transformations',
6     'wlxml/extensions/metadata/metadata'
7 ], function($, _, smartxml, transformations, metadataExtension) {
8     
9 'use strict';
10
11 /* globals Node */
12
13
14 var AttributesList = function() {};
15 AttributesList.prototype = Object.create({});
16 AttributesList.prototype.keys = function() {
17     return _.keys(this);
18 };
19
20 var installObject = function(instance, klass) {
21     var methods = instance.document.classMethods[klass] || {},
22         transformations = instance.document.classTransformations[klass] || {};
23
24     instance.object = Object.create(_.extend({}, methods, transformations));
25     _.keys(methods).concat(_.keys(transformations)).forEach(function(key) {
26         instance.object[key] = _.bind(instance.object[key], instance);
27     });
28 };
29
30 var WLXMLElementNode = function(nativeNode, document) {
31     smartxml.ElementNode.call(this, nativeNode, document);
32     installObject(this, this.getClass());
33 };
34 WLXMLElementNode.prototype = Object.create(smartxml.ElementNode.prototype);
35
36 $.extend(WLXMLElementNode.prototype, smartxml.ElementNode.prototype, {
37     getClass: function() {
38         return this.getAttr('class') || '';
39     },
40     setClass: function(klass) {
41         if(klass !== this.klass) {
42             installObject(this, klass);
43             return this.setAttr('class', klass);
44         }
45     },
46     is: function(klass) {
47         return this.getClass().substr(0, klass.length) === klass;
48     },
49     getMetaAttributes: function() {
50         var toret = new AttributesList(),
51             classParts = [''].concat(this.getClass().split('.')),
52             classCurrent, classDesc;
53
54         classParts.forEach(function(part) {
55             classCurrent = classCurrent ? classCurrent + '.' + part : part;
56             classDesc = this.document.options.wlxmlClasses[classCurrent];
57             if(classDesc) {
58                 _.keys(classDesc.attrs).forEach(function(attrName) {
59                     toret[attrName] = _.extend({value: this.getAttr(attrName)}, classDesc.attrs[attrName]);
60                 }.bind(this));
61             }
62         }.bind(this));
63         return toret;
64     },
65     setMetaAttribute: function(key, value) {
66         this.setAttr(key, value);
67     },
68     getOtherAttributes: function() {
69         var toret = {},
70             node = this;
71         this.getAttrs().forEach(function(attr) {
72             if(attr.name !== 'class' && !node.isMetaAttribute(attr.name)) {
73                 toret[attr.name] = {value: attr.value};
74             }
75         });
76         return toret;
77     },
78     isMetaAttribute: function(attrName) {
79         return attrName !== 'class' &&_.contains(_.keys(this.getMetaAttributes()), attrName);
80     },
81
82     _getXMLDOMToDump: function() {
83         var DOM = this._$.clone(true, true),
84             doc = this.document;
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, documentNode, metaNode;
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             if(this.nodeType === Node.ELEMENT_NODE) {
127                 documentNode = doc.createDocumentNode(this);
128                 metaNode = $('<metadata>');
129                 documentNode.getMetadata().forEach(function(row) {
130                     metaNode.append('<dc:'+ row.key + '>' + row.value + '</dc:' + row.key + '>');
131                 });
132                 if(metaNode.children().length) {
133                     $(this).prepend(metaNode);
134                 }
135             }
136
137         });
138
139         
140
141         return DOM;
142     }
143 });
144
145 // WLXMLElementNode.prototype.transformations.register(transformations.createContextTransformation({
146 //     name: 'wlxml.setMetaAttribute',
147 //     impl: function(args) {
148 //         this.setMetaAttribute(args.name, args.value);
149 //     },
150 //     getChangeRoot: function() {
151 //         return this.context;
152 //     }
153 // }));
154
155
156
157 var WLXMLDocumentNode = function() {
158     smartxml.DocumentNode.apply(this, arguments);
159 };
160 WLXMLDocumentNode.prototype = Object.create(smartxml.DocumentNode.prototype);
161
162 var WLXMLDocument = function(xml, options) {
163     this.classMethods = {};
164     this.classTransformations = {};
165     smartxml.Document.call(this, xml, [metadataExtension]);
166     this.options = options;
167 };
168
169 var formatter_prefix = '_wlxml_formatter_';
170
171
172 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
173 $.extend(WLXMLDocument.prototype, {
174     ElementNodeFactory: WLXMLElementNode,
175     loadXML: function(xml) {
176         smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
177         this.trigger('contentSet');
178     },
179
180     normalizeXML: function(nativeNode) {
181         var doc = this,
182             prefixLength = 'dc:'.length;
183
184         $(nativeNode).find('metadata').each(function() {
185             var metadataNode = $(this),
186                 owner = doc.createDocumentNode(metadataNode.parent()[0]),
187                 metadata = owner.getMetadata();
188                 
189             metadataNode.children().each(function() {
190                 metadata.add({key: (this.tagName).toLowerCase().substr(prefixLength), value: $(this).text()}, {undoable: false});
191             });
192             metadataNode.remove();
193         });
194         nativeNode.normalize();
195
196         $(nativeNode).find(':not(iframe)').addBack().contents()
197             .filter(function() {return this.nodeType === Node.TEXT_NODE;})
198             .each(function() {
199                 var el = $(this),
200                     text = {original: el.text(), trimmed: $.trim(el.text())},
201                     elParent = el.parent(),
202                     hasSpanParent = elParent.prop('tagName') === 'SPAN',
203                     hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
204                     hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
205
206
207                 var addInfo = function(toAdd, where, transformed, original) {
208                     var parentContents = elParent.contents(),
209                         idx = parentContents.index(el[0]),
210                         prev = idx > 0 ? parentContents[idx-1] : null,
211                         next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
212                         target, key;
213
214                     if(where === 'above') {
215                         target = prev ? $(prev) : elParent;
216                         key = prev ? 'orig_after' : 'orig_begin';
217                     } else if(where === 'below') {
218                         target = next ? $(next) : elParent;
219                         key = next ? 'orig_before' : 'orig_end';
220                     } else { throw new Error();}
221
222                     target.data(formatter_prefix + key, toAdd);
223                     if(transformed !== undefined) {
224                         target.data(formatter_prefix + key + '_transformed', transformed);
225                     }
226                     if(original !== undefined) {
227                         target.data(formatter_prefix + key + '_original', original);
228                     }
229                 };
230
231                 text.transformed = text.trimmed;
232
233                 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
234                     var startSpace = /\s/g.test(text.original.substr(0,1)),
235                         endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
236                     text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
237                     text.transformed += text.trimmed;
238                     text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
239                 } else {
240                     if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
241                         text.transformed = ' ';
242                     }
243                 }
244
245                 if(!text.transformed) {
246                     addInfo(text.original, 'below');
247                     el.remove();
248                     return true; // continue
249                 }
250
251                 if(text.transformed !== text.original) {
252                     // if(!text.trimmed) {
253                     //     addInfo(text.original, 'below');
254                     // } else {
255                         var startingMatch = text.original.match(/^\s+/g),
256                             endingMatch = text.original.match(/\s+$/g),
257                             startingWhiteSpace = startingMatch ? startingMatch[0] : null,
258                             endingWhiteSpace = endingMatch ? endingMatch[0] : null;
259
260                         if(endingWhiteSpace) {
261                             if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
262                                 endingWhiteSpace = endingWhiteSpace.substr(1);
263                             }
264                             addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
265                         }
266
267                         if(startingWhiteSpace && text.trimmed) {
268                             if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
269                                 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
270                             }
271                             addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
272                         }
273                     //}
274                 }
275                 /* globals document */
276                 el.replaceWith(document.createTextNode(text.transformed));
277             });
278         
279
280     },
281
282     registerClassTransformation: function(Transformation, className) {
283         var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || {});
284         thisClassTransformations[Transformation.prototype.name] = function(args) {
285             var nodeInstance = this;
286             return nodeInstance.transform(Transformation, args);
287         };
288     },
289
290     registerClassMethod: function(methodName, method, className) {
291         var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
292         thisClassMethods[methodName] = method;
293     },
294
295     registerExtension: function(extension) {
296         //debugger;
297         smartxml.Document.prototype.registerExtension.call(this, extension);
298         var doc = this;
299
300         _.pairs(extension.wlxmlClass).forEach(function(pair) {
301             var className = pair[0],
302                 classExtension = pair[1];
303
304             _.pairs(classExtension.methods || {}).forEach(function(pair) {
305                 var name = pair[0],
306                     method = pair[1];
307                 doc.registerClassMethod(name, method, className);
308             });
309
310             _.pairs(classExtension.transformations || {}).forEach(function(pair) {
311                 var name = pair[0],
312                     desc = pair[1];
313                 doc.registerClassTransformation(transformations.createContextTransformation(desc, name), className);
314             });
315         });
316
317     }
318
319 });
320
321 var wlxmlClasses = {
322     'link': {
323         attrs: {href: {type: 'string'}}
324     }
325 };
326
327
328 return {
329     WLXMLDocumentFromXML: function(xml, options) {
330         options = _.extend({wlxmlClasses: wlxmlClasses}, options);
331         return new WLXMLDocument(xml, options);
332     },
333
334     WLXMLElementNodeFromXML: function(xml) {
335         return this.WLXMLDocumentFromXML(xml).root;
336     }
337 };
338
339 });