5 'smartxml/transformations',
6 'wlxml/extensions/metadata/metadata'
7 ], function($, _, smartxml, transformations, metadataExtension) {
14 var WLXMLDocumentNodeMethods = {
15 isInside: function(klass) {
16 var parent = this.getParent(klass);
19 getParent: function(klass) {
21 var me = this.nodeType === Node.ELEMENT_NODE ? [this] : [],
23 me.concat(this.parents()).some(function(node) {
33 var AttributesList = function() {};
34 AttributesList.prototype = Object.create({});
35 AttributesList.prototype.keys = function() {
39 var getClassLists = function(klassName) {
41 classParts = [''].concat(klassName.split('.')),
44 classParts.forEach(function(part) {
45 classCurrent = classCurrent ? classCurrent + '.' + part : part;
46 toret.push(classCurrent);
51 var installObject = function(instance, klass) {
55 getClassLists(klass).forEach(function(klassName) {
56 _.extend(methods, instance.document.classMethods[klassName] || {});
57 _.extend(methods, instance.document.classTransformations[klassName] || {});
59 instance.object = Object.create(_.extend({}, methods, transformations));
60 _.keys(methods).concat(_.keys(transformations)).forEach(function(key) {
61 instance.object[key] = _.bind(instance.object[key], instance);
65 var WLXMLElementNode = function(nativeNode, document) {
66 smartxml.ElementNode.call(this, nativeNode, document);
67 installObject(this, this.getClass());
69 WLXMLElementNode.prototype = Object.create(smartxml.ElementNode.prototype);
71 $.extend(WLXMLElementNode.prototype, WLXMLDocumentNodeMethods, smartxml.ElementNode.prototype, {
72 getClass: function() {
73 return this.getAttr('class') || '';
75 setClass: function(klass) {
76 if(klass !== this.klass) {
77 installObject(this, klass);
78 return this.setAttr('class', klass);
82 return this.getClass().substr(0, klass.length) === klass;
84 getMetaAttributes: function() {
85 var toret = new AttributesList(),
86 classParts = [''].concat(this.getClass().split('.')),
87 classCurrent, classDesc;
89 classParts.forEach(function(part) {
90 classCurrent = classCurrent ? classCurrent + '.' + part : part;
91 classDesc = this.document.options.wlxmlClasses[classCurrent];
93 _.keys(classDesc.attrs).forEach(function(attrName) {
94 toret[attrName] = _.extend({value: this.getAttr(attrName)}, classDesc.attrs[attrName]);
100 setMetaAttribute: function(key, value) {
101 this.setAttr(key, value);
103 getOtherAttributes: function() {
106 this.getAttrs().forEach(function(attr) {
107 if(attr.name !== 'class' && !node.isMetaAttribute(attr.name)) {
108 toret[attr.name] = {value: attr.value};
113 isMetaAttribute: function(attrName) {
114 return attrName !== 'class' &&_.contains(_.keys(this.getMetaAttributes()), attrName);
117 _getXMLDOMToDump: function() {
118 var DOM = this._$.clone(true, true),
121 DOM.find('*').addBack().each(function() {
123 parent = el.parent(),
124 contents = parent.contents(),
125 idx = contents.index(el),
129 var txt, documentNode, metaNode;
131 if(data[formatter_prefix+ 'orig_before']) {
132 txt = idx > 0 && contents[idx-1].nodeType === Node.TEXT_NODE ? contents[idx-1] : null;
133 if(txt && txt.data === data[formatter_prefix + 'orig_before_transformed']) {
134 txt.data = data[formatter_prefix+ 'orig_before_original'];
136 el.before(data[formatter_prefix+ 'orig_before']);
139 if(data[formatter_prefix+ 'orig_after']) {
140 txt = idx < contents.length-1 && contents[idx+1].nodeType === Node.TEXT_NODE ? contents[idx+1] : null;
141 if(txt && txt.data === data[formatter_prefix + 'orig_after_transformed']) {
142 txt.data = data[formatter_prefix+ 'orig_after_original'];
144 el.after(data[formatter_prefix+ 'orig_after']);
147 if(data[formatter_prefix+ 'orig_begin']) {
148 el.prepend(data[formatter_prefix+ 'orig_begin']);
150 if(data[formatter_prefix+ 'orig_end']) {
151 contents = el.contents();
152 txt = (contents.length && contents[contents.length-1].nodeType === Node.TEXT_NODE) ? contents[contents.length-1] : null;
153 if(txt && txt.data === data[formatter_prefix + 'orig_end_transformed']) {
154 txt.data = data[formatter_prefix+ 'orig_end_original'];
156 el.append(data[formatter_prefix+ 'orig_end']);
161 if(this.nodeType === Node.ELEMENT_NODE) {
162 documentNode = doc.createDocumentNode(this);
163 metaNode = $('<metadata>');
164 documentNode.getMetadata().forEach(function(row) {
165 metaNode.append('<dc:'+ row.key + '>' + row.value + '</dc:' + row.key + '>');
167 if(metaNode.children().length) {
168 $(this).prepend(metaNode);
180 // WLXMLElementNode.prototype.transformations.register(transformations.createContextTransformation({
181 // name: 'wlxml.setMetaAttribute',
182 // impl: function(args) {
183 // this.setMetaAttribute(args.name, args.value);
185 // getChangeRoot: function() {
186 // return this.context;
192 var WLXMLDocumentNode = function() {
193 smartxml.DocumentNode.apply(this, arguments);
195 WLXMLDocumentNode.prototype = Object.create(smartxml.DocumentNode.prototype);
198 var WLXMLTextNode = function() {
199 smartxml.TextNode.apply(this, arguments);
201 WLXMLTextNode.prototype = Object.create(smartxml.TextNode.prototype);
202 $.extend(WLXMLTextNode.prototype, WLXMLDocumentNodeMethods);
204 var WLXMLDocument = function(xml, options) {
205 this.classMethods = {};
206 this.classTransformations = {};
207 smartxml.Document.call(this, xml, [metadataExtension]);
208 this.options = options;
211 var formatter_prefix = '_wlxml_formatter_';
214 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
215 $.extend(WLXMLDocument.prototype, {
216 ElementNodeFactory: WLXMLElementNode,
217 TextNodeFactory: WLXMLTextNode,
218 loadXML: function(xml) {
219 smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
220 this.trigger('contentSet');
223 normalizeXML: function(nativeNode) {
225 prefixLength = 'dc:'.length;
227 $(nativeNode).find('metadata').each(function() {
228 var metadataNode = $(this),
229 owner = doc.createDocumentNode(metadataNode.parent()[0]),
230 metadata = owner.getMetadata();
232 metadataNode.children().each(function() {
233 metadata.add({key: (this.tagName).toLowerCase().substr(prefixLength), value: $(this).text()}, {undoable: false});
235 metadataNode.remove();
237 nativeNode.normalize();
239 $(nativeNode).find(':not(iframe)').addBack().contents()
240 .filter(function() {return this.nodeType === Node.TEXT_NODE;})
243 text = {original: el.text(), trimmed: $.trim(el.text())},
244 elParent = el.parent(),
245 hasSpanParent = elParent.prop('tagName') === 'SPAN',
246 hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
247 hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
250 var addInfo = function(toAdd, where, transformed, original) {
251 var parentContents = elParent.contents(),
252 idx = parentContents.index(el[0]),
253 prev = idx > 0 ? parentContents[idx-1] : null,
254 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
257 if(where === 'above') {
258 target = prev ? $(prev) : elParent;
259 key = prev ? 'orig_after' : 'orig_begin';
260 } else if(where === 'below') {
261 target = next ? $(next) : elParent;
262 key = next ? 'orig_before' : 'orig_end';
263 } else { throw new Error();}
265 target.data(formatter_prefix + key, toAdd);
266 if(transformed !== undefined) {
267 target.data(formatter_prefix + key + '_transformed', transformed);
269 if(original !== undefined) {
270 target.data(formatter_prefix + key + '_original', original);
274 text.transformed = text.trimmed;
276 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
277 var startSpace = /\s/g.test(text.original.substr(0,1)),
278 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
279 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
280 text.transformed += text.trimmed;
281 text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
283 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
284 text.transformed = ' ';
288 if(!text.transformed) {
289 addInfo(text.original, 'below');
291 return true; // continue
294 if(text.transformed !== text.original) {
295 // if(!text.trimmed) {
296 // addInfo(text.original, 'below');
298 var startingMatch = text.original.match(/^\s+/g),
299 endingMatch = text.original.match(/\s+$/g),
300 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
301 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
303 if(endingWhiteSpace) {
304 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
305 endingWhiteSpace = endingWhiteSpace.substr(1);
307 addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
310 if(startingWhiteSpace && text.trimmed) {
311 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
312 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
314 addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
318 /* globals document */
319 el.replaceWith(document.createTextNode(text.transformed));
325 registerClassTransformation: function(Transformation, className) {
326 var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || {});
327 thisClassTransformations[Transformation.prototype.name] = function() {
328 var nodeInstance = this;
329 var args = Array.prototype.slice.call(arguments, 0);
330 return nodeInstance.transform(Transformation, args);
334 registerClassMethod: function(methodName, method, className) {
335 var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
336 thisClassMethods[methodName] = method;
339 registerExtension: function(extension) {
341 smartxml.Document.prototype.registerExtension.call(this, extension);
344 _.pairs(extension.wlxmlClass).forEach(function(pair) {
345 var className = pair[0],
346 classExtension = pair[1];
348 _.pairs(classExtension.methods || {}).forEach(function(pair) {
351 doc.registerClassMethod(name, method, className);
354 _.pairs(classExtension.transformations || {}).forEach(function(pair) {
357 doc.registerClassTransformation(transformations.createContextTransformation(desc, name), className);
367 attrs: {href: {type: 'string'}}
373 WLXMLDocumentFromXML: function(xml, options, Factory) {
374 options = _.extend({wlxmlClasses: wlxmlClasses}, options);
375 Factory = Factory || WLXMLDocument;
376 return new Factory(xml, options);
379 WLXMLElementNodeFromXML: function(xml) {
380 return this.WLXMLDocumentFromXML(xml).root;
383 WLXMLDocument: WLXMLDocument