5 'smartxml/transformations',
6 'wlxml/extensions/metadata/metadata'
7 ], function($, _, smartxml, transformations, metadataExtension) {
14 var WLXMLDocumentNodeMethods = {
15 isInside: function(query) {
16 var parent = this.getParent(query);
19 getParent: function(query) {
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 if(_.isFunction(instance.object[key])) {
62 instance.object[key] = _.bind(instance.object[key], instance);
67 var WLXMLElementNode = function(nativeNode, document) {
68 smartxml.ElementNode.call(this, nativeNode, document);
69 installObject(this, this.getClass());
71 WLXMLElementNode.prototype = Object.create(smartxml.ElementNode.prototype);
73 $.extend(WLXMLElementNode.prototype, WLXMLDocumentNodeMethods, smartxml.ElementNode.prototype, {
74 getClass: function() {
75 return this.getAttr('class') || '';
77 getClassHierarchy: function() {
78 return getClassLists(this.getClass());
80 setClass: function(klass) {
81 if(klass !== this.klass) {
82 installObject(this, klass);
83 return this.setAttr('class', klass);
87 if(typeof query === 'string') {
88 query = {klass: query};
90 return (_.isUndefined(query.klass) || this.getClass().substr(0, query.klass.length) === query.klass) &&
91 (_.isUndefined(query.tagName) || this.getTagName() === query.tagName);
93 getMetaAttributes: function() {
94 var toret = new AttributesList(),
95 classParts = [''].concat(this.getClass().split('.')),
96 classCurrent, classDesc;
98 classParts.forEach(function(part) {
99 classCurrent = classCurrent ? classCurrent + '.' + part : part;
100 classDesc = this.document.options.wlxmlClasses[classCurrent];
102 _.keys(classDesc.attrs).forEach(function(attrName) {
103 toret[attrName] = _.extend({value: this.getAttr(attrName)}, classDesc.attrs[attrName]);
109 setMetaAttribute: function(key, value) {
110 this.setAttr(key, value);
112 getOtherAttributes: function() {
115 this.getAttrs().forEach(function(attr) {
116 if(attr.name !== 'class' && !node.isMetaAttribute(attr.name)) {
117 toret[attr.name] = {value: attr.value};
122 isMetaAttribute: function(attrName) {
123 return attrName !== 'class' &&_.contains(_.keys(this.getMetaAttributes()), attrName);
126 _getXMLDOMToDump: function() {
127 var DOM = this._$.clone(true, true),
130 DOM.find('*').addBack().each(function() {
132 parent = el.parent(),
133 contents = parent.contents(),
134 idx = contents.index(el),
138 var txt, documentNode, metaNode;
140 if(data[formatter_prefix+ 'orig_before']) {
141 txt = idx > 0 && contents[idx-1].nodeType === Node.TEXT_NODE ? contents[idx-1] : null;
142 if(txt && txt.data === data[formatter_prefix + 'orig_before_transformed']) {
143 txt.data = data[formatter_prefix+ 'orig_before_original'];
145 el.before(data[formatter_prefix+ 'orig_before']);
148 if(data[formatter_prefix+ 'orig_after']) {
149 txt = idx < contents.length-1 && contents[idx+1].nodeType === Node.TEXT_NODE ? contents[idx+1] : null;
150 if(txt && txt.data === data[formatter_prefix + 'orig_after_transformed']) {
151 txt.data = data[formatter_prefix+ 'orig_after_original'];
153 el.after(data[formatter_prefix+ 'orig_after']);
156 if(data[formatter_prefix+ 'orig_begin']) {
157 el.prepend(data[formatter_prefix+ 'orig_begin']);
159 if(data[formatter_prefix+ 'orig_end']) {
160 contents = el.contents();
161 txt = (contents.length && contents[contents.length-1].nodeType === Node.TEXT_NODE) ? contents[contents.length-1] : null;
162 if(txt && txt.data === data[formatter_prefix + 'orig_end_transformed']) {
163 txt.data = data[formatter_prefix+ 'orig_end_original'];
165 el.append(data[formatter_prefix+ 'orig_end']);
170 if(this.nodeType === Node.ELEMENT_NODE) {
171 documentNode = doc.createDocumentNode(this);
172 metaNode = $('<metadata>');
173 documentNode.getMetadata().forEach(function(row) {
174 metaNode.append('<dc:'+ row.key + '>' + row.value + '</dc:' + row.key + '>');
176 if(metaNode.children().length) {
177 $(this).prepend(metaNode);
189 // WLXMLElementNode.prototype.transformations.register(transformations.createContextTransformation({
190 // name: 'wlxml.setMetaAttribute',
191 // impl: function(args) {
192 // this.setMetaAttribute(args.name, args.value);
194 // getChangeRoot: function() {
195 // return this.context;
201 var WLXMLDocumentNode = function() {
202 smartxml.DocumentNode.apply(this, arguments);
204 WLXMLDocumentNode.prototype = Object.create(smartxml.DocumentNode.prototype);
207 var WLXMLTextNode = function() {
208 smartxml.TextNode.apply(this, arguments);
210 WLXMLTextNode.prototype = Object.create(smartxml.TextNode.prototype);
211 $.extend(WLXMLTextNode.prototype, WLXMLDocumentNodeMethods);
213 var WLXMLDocument = function(xml, options) {
214 this.classMethods = {};
215 this.classTransformations = {};
216 smartxml.Document.call(this, xml, [metadataExtension]);
217 this.options = options;
220 var formatter_prefix = '_wlxml_formatter_';
223 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
224 $.extend(WLXMLDocument.prototype, {
225 ElementNodeFactory: WLXMLElementNode,
226 TextNodeFactory: WLXMLTextNode,
227 loadXML: function(xml) {
228 smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
229 this.trigger('contentSet');
232 normalizeXML: function(nativeNode) {
234 prefixLength = 'dc:'.length;
236 $(nativeNode).find('metadata').each(function() {
237 var metadataNode = $(this),
238 owner = doc.createDocumentNode(metadataNode.parent()[0]),
239 metadata = owner.getMetadata();
241 metadataNode.children().each(function() {
242 metadata.add({key: (this.tagName).toLowerCase().substr(prefixLength), value: $(this).text()}, {undoable: false});
244 metadataNode.remove();
246 nativeNode.normalize();
248 $(nativeNode).find(':not(iframe)').addBack().contents()
249 .filter(function() {return this.nodeType === Node.TEXT_NODE;})
252 text = {original: el.text(), trimmed: $.trim(el.text())},
253 elParent = el.parent(),
254 hasSpanParent = elParent.prop('tagName') === 'SPAN',
255 hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
256 hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
259 var addInfo = function(toAdd, where, transformed, original) {
260 var parentContents = elParent.contents(),
261 idx = parentContents.index(el[0]),
262 prev = idx > 0 ? parentContents[idx-1] : null,
263 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
266 if(where === 'above') {
267 target = prev ? $(prev) : elParent;
268 key = prev ? 'orig_after' : 'orig_begin';
269 } else if(where === 'below') {
270 target = next ? $(next) : elParent;
271 key = next ? 'orig_before' : 'orig_end';
272 } else { throw new Error();}
274 target.data(formatter_prefix + key, toAdd);
275 if(transformed !== undefined) {
276 target.data(formatter_prefix + key + '_transformed', transformed);
278 if(original !== undefined) {
279 target.data(formatter_prefix + key + '_original', original);
283 text.transformed = text.trimmed;
285 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
286 var startSpace = /\s/g.test(text.original.substr(0,1)),
287 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
288 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
289 text.transformed += text.trimmed;
290 text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
292 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
293 text.transformed = ' ';
297 if(!text.transformed) {
298 addInfo(text.original, 'below');
300 return true; // continue
303 if(text.transformed !== text.original) {
304 // if(!text.trimmed) {
305 // addInfo(text.original, 'below');
307 var startingMatch = text.original.match(/^\s+/g),
308 endingMatch = text.original.match(/\s+$/g),
309 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
310 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
312 if(endingWhiteSpace) {
313 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
314 endingWhiteSpace = endingWhiteSpace.substr(1);
316 addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
319 if(startingWhiteSpace && text.trimmed) {
320 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
321 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
323 addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
327 /* globals document */
328 el.replaceWith(document.createTextNode(text.transformed));
334 registerClassTransformation: function(Transformation, className) {
335 var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || {});
336 thisClassTransformations[Transformation.prototype.name] = function() {
337 var nodeInstance = this;
338 var args = Array.prototype.slice.call(arguments, 0);
339 return nodeInstance.transform(Transformation, args);
343 registerClassMethod: function(methodName, method, className) {
344 var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
345 thisClassMethods[methodName] = method;
348 registerExtension: function(extension) {
350 smartxml.Document.prototype.registerExtension.call(this, extension);
353 _.pairs(extension.wlxmlClass).forEach(function(pair) {
354 var className = pair[0],
355 classExtension = pair[1];
357 _.pairs(classExtension.methods || {}).forEach(function(pair) {
360 doc.registerClassMethod(name, method, className);
363 _.pairs(classExtension.transformations || {}).forEach(function(pair) {
366 doc.registerClassTransformation(transformations.createContextTransformation(desc, name), className);
376 attrs: {href: {type: 'string'}}
382 WLXMLDocumentFromXML: function(xml, options, Factory) {
383 options = _.extend({wlxmlClasses: wlxmlClasses}, options);
384 Factory = Factory || WLXMLDocument;
385 return new Factory(xml, options);
388 WLXMLElementNodeFromXML: function(xml) {
389 return this.WLXMLDocumentFromXML(xml).root;
392 WLXMLDocument: WLXMLDocument,
393 getClassHierarchy: getClassLists