5 'smartxml/transformations'
6 ], function($, _, smartxml, transformations) {
12 var isMetaAttribute = function(attrName) {
13 return attrName.substr(0, 5) === 'meta-';
18 var AttributesList = function() {};
19 AttributesList.prototype = Object.create({});
20 AttributesList.prototype.keys = function() {
24 var installObject = function(instance, klass) {
25 var methods = instance.document.classMethods[klass] || instance.document.classTransformations;
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),
33 transformation = new Transformation(instance.document, instance, args);
35 return instance.document.transform(transformation);
38 _.keys(methods).forEach(function(key) {
39 instance.object[key] = _.bind(instance.object[key], instance);
44 var WLXMLElementNode = function(nativeNode, document) {
45 smartxml.ElementNode.call(this, nativeNode, document);
46 installObject(this, this.getClass());
48 WLXMLElementNode.prototype = Object.create(smartxml.ElementNode.prototype);
50 $.extend(WLXMLElementNode.prototype, smartxml.ElementNode.prototype, {
51 getClass: function() {
52 return this.getAttr('class') || '';
54 setClass: function(klass) {
56 if(klass !== this.klass) {
57 installObject(this, klass);
58 return this.setAttr('class', klass);
62 return this.getClass().substr(0, klass.length) === klass;
64 getMetaAttributes: function() {
65 var toret = new AttributesList(),
66 classParts = [''].concat(this.getClass().split('.')),
67 classCurrent, classDesc;
69 classParts.forEach(function(part) {
70 classCurrent = classCurrent ? classCurrent + '.' + part : part;
71 classDesc = this.document.options.wlxmlClasses[classCurrent];
73 _.keys(classDesc.attrs).forEach(function(attrName) {
74 toret[attrName] = _.extend({value: this.getAttr('meta-' + attrName)}, classDesc.attrs[attrName]);
80 setMetaAttribute: function(key, value) {
81 this.setAttr('meta-'+key, value);
83 getOtherAttributes: function() {
85 this.getAttrs().forEach(function(attr) {
86 if(attr.name !== 'class' && !isMetaAttribute(attr.name)) {
87 toret[attr.name] = attr.value;
93 _getXMLDOMToDump: function() {
94 var DOM = this._$.clone(true, true);
96 DOM.find('*').addBack().each(function() {
99 contents = parent.contents(),
100 idx = contents.index(el),
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'];
111 el.before(data[formatter_prefix+ 'orig_before']);
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'];
119 el.after(data[formatter_prefix+ 'orig_after']);
122 if(data[formatter_prefix+ 'orig_begin']) {
123 el.prepend(data[formatter_prefix+ 'orig_begin']);
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'];
131 el.append(data[formatter_prefix+ 'orig_end']);
140 WLXMLElementNode.prototype.transformations.register(transformations.createContextTransformation({
141 name: 'wlxml.setMetaAttribute',
142 impl: function(args) {
143 this.setMetaAttribute(args.name, args.value);
145 getChangeRoot: function() {
152 var WLXMLDocumentNode = function() {
153 smartxml.DocumentNode.apply(this, arguments);
155 WLXMLDocumentNode.prototype = Object.create(smartxml.DocumentNode.prototype);
157 var WLXMLDocument = function(xml, options) {
158 smartxml.Document.call(this, xml);
159 this.options = options;
161 // this.DocumentNodeFactory = function() {
162 // WLXMLDocumentNode.apply(this, arguments);
165 // this.DocumentNodeFactory.prototype = Object.create(WLXMLDocumentNode.prototype);
167 this.ElementNodeFactory = function() {
168 WLXMLElementNode.apply(this, arguments);
170 this.ElementNodeFactory.prototype = Object.create(WLXMLElementNode.prototype);
171 this.ElementNodeFactory.prototype.transformations = new transformations.TransformationStorage();
172 this.ElementNodeFactory.prototype.registerTransformation = function(Transformation) {
173 return this.transformations.register(Transformation);
176 this.TextNodeFactory = function() {
177 smartxml.TextNode.apply(this, arguments);
179 this.TextNodeFactory.prototype = Object.create(smartxml.TextNode.prototype);
180 this.TextNodeFactory.prototype.transformations = new transformations.TransformationStorage();
181 this.TextNodeFactory.prototype.registerTransformation = function(Transformation) {
182 return this.transformations.register(Transformation);
185 this.classMethods = {};
186 this.classTransformations = {};
189 var formatter_prefix = '_wlxml_formatter_';
192 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
193 $.extend(WLXMLDocument.prototype, {
194 ElementNodeFactory: WLXMLElementNode,
195 loadXML: function(xml) {
196 smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
197 $(this.dom).find(':not(iframe)').addBack().contents()
198 .filter(function() {return this.nodeType === Node.TEXT_NODE;})
201 text = {original: el.text(), trimmed: $.trim(el.text())},
202 elParent = el.parent(),
203 hasSpanParent = elParent.prop('tagName') === 'SPAN',
204 hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
205 hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
208 var addInfo = function(toAdd, where, transformed, original) {
209 var parentContents = elParent.contents(),
210 idx = parentContents.index(el[0]),
211 prev = idx > 0 ? parentContents[idx-1] : null,
212 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
215 if(where === 'above') {
216 target = prev ? $(prev) : elParent;
217 key = prev ? 'orig_after' : 'orig_begin';
218 } else if(where === 'below') {
219 target = next ? $(next) : elParent;
220 key = next ? 'orig_before' : 'orig_end';
221 } else { throw new Error();}
223 target.data(formatter_prefix + key, toAdd);
224 if(transformed !== undefined) {
225 target.data(formatter_prefix + key + '_transformed', transformed);
227 if(original !== undefined) {
228 target.data(formatter_prefix + key + '_original', original);
232 text.transformed = text.trimmed;
234 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
235 var startSpace = /\s/g.test(text.original.substr(0,1)),
236 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
237 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
238 text.transformed += text.trimmed;
239 text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
241 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
242 text.transformed = ' ';
246 if(!text.transformed) {
247 addInfo(text.original, 'below');
249 return true; // continue
252 if(text.transformed !== text.original) {
253 // if(!text.trimmed) {
254 // addInfo(text.original, 'below');
256 var startingMatch = text.original.match(/^\s+/g),
257 endingMatch = text.original.match(/\s+$/g),
258 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
259 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
261 if(endingWhiteSpace) {
262 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
263 endingWhiteSpace = endingWhiteSpace.substr(1);
265 addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
268 if(startingWhiteSpace && text.trimmed) {
269 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
270 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
272 addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
277 el.replaceWith(document.createTextNode(text.transformed));
279 this.trigger('contentSet');
282 registerTransformation: function(Transformation) {
283 return this.transformations.register(Transformation);
286 registerClassTransformation: function(Transformation, className) {
287 var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || new transformations.TransformationStorage());
288 return thisClassTransformations.register(Transformation);
291 registerClassMethod: function(methodName, method, className) {
292 var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
293 thisClassMethods[methodName] = method;
296 registerExtension: function(extension) {
299 existingPropertyNames = _.values(this);
301 var getTrans = function(desc, methodName) {
302 if(typeof desc === 'function') {
306 throw new Error('Got transformation description without implementation.')
308 desc.name = desc.name || methodName;
313 {source: extension.document, target: doc},
314 {source: extension.documentNode, target: [doc.ElementNodeFactory.prototype, doc.TextNodeFactory.prototype]},
316 ].forEach(function(mapping) {
318 if(mapping.source.methods) {
319 existingPropertyNames = _.values(mapping.target)
320 _.pairs(mapping.source.methods).forEach(function(pair) {
321 var methodName = pair[0],
323 targets = _.isArray(mapping.target) ? mapping.target : [mapping.target];
324 if(_.contains(existingPropertyNames, methodName)) {
325 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
326 .replace('{target}', mapping.target)
327 .replace('{methodName}', methodName)
330 targets.forEach(function(target) {
331 target[methodName] = method;
336 if(mapping.source.transformations) {
337 _.pairs(mapping.source.transformations).forEach(function(pair) {
338 var transformation = getTrans(pair[1], pair[0]),
339 targets = _.isArray(mapping.target) ? mapping.target : [mapping.target];
340 targets.forEach(function(target) {
341 target.registerTransformation(transformations.createContextTransformation(transformation));
348 _.pairs(extension.wlxmlClass).forEach(function(pair) {
349 var className = pair[0],
350 classExtension = pair[1];
352 _.pairs(classExtension.methods || {}).forEach(function(pair) {
355 doc.registerClassMethod(name, method, className);
358 _.pairs(classExtension.transformations || {}).forEach(function(pair) {
359 var transformation = getTrans(pair[1], pair[0]);
360 doc.registerClassTransformation(transformations.createContextTransformation(transformation), className);
370 attrs: {uri: {type: 'string'}}
374 var classMethods = {};
377 WLXMLDocumentFromXML: function(xml, options) {
378 options = _.extend({wlxmlClasses: wlxmlClasses}, options);
379 return new WLXMLDocument(xml, options);
382 WLXMLElementNodeFromXML: function(xml) {
383 return this.WLXMLDocumentFromXML(xml).root;
386 registerExtension: function(extension) {
388 if(extension.documentTransformations) {
389 extension.documentTransformations.forEach(function(method) {
390 WLXMLDocument.prototype.transformations.register(transformations.createContextTransformation(method));
394 _.pairs(extension.classMethods).forEach(function(pair) {
395 var className = pair[0],
397 _.pairs(methods).forEach(function(pair) {
398 var methodName = pair[0],
400 classMethods[className] = classMethods[className] || {};
401 classMethods[className][methodName] = method;
406 _.extend(WLXMLDocument.prototype, extension.documentMethods);