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 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 getClassHierarchy: function() {
76 return getClassLists(this.getClass());
78 setClass: function(klass) {
79 if(klass !== this.klass) {
80 installObject(this, klass);
81 return this.setAttr('class', klass);
85 if(typeof query === 'string') {
86 query = {klass: query};
88 return (_.isUndefined(query.klass) || this.getClass().substr(0, query.klass.length) === query.klass) &&
89 (_.isUndefined(query.tagName) || this.getTagName() === query.tagName);
91 getMetaAttributes: function() {
92 var toret = new AttributesList(),
93 classParts = [''].concat(this.getClass().split('.')),
94 classCurrent, classDesc;
96 classParts.forEach(function(part) {
97 classCurrent = classCurrent ? classCurrent + '.' + part : part;
98 classDesc = this.document.options.wlxmlClasses[classCurrent];
100 _.keys(classDesc.attrs).forEach(function(attrName) {
101 toret[attrName] = _.extend({value: this.getAttr(attrName)}, classDesc.attrs[attrName]);
107 setMetaAttribute: function(key, value) {
108 this.setAttr(key, value);
110 getOtherAttributes: function() {
113 this.getAttrs().forEach(function(attr) {
114 if(attr.name !== 'class' && !node.isMetaAttribute(attr.name)) {
115 toret[attr.name] = {value: attr.value};
120 isMetaAttribute: function(attrName) {
121 return attrName !== 'class' &&_.contains(_.keys(this.getMetaAttributes()), attrName);
124 _getXMLDOMToDump: function() {
125 var DOM = this._$.clone(true, true),
128 DOM.find('*').addBack().each(function() {
130 parent = el.parent(),
131 contents = parent.contents(),
132 idx = contents.index(el),
136 var txt, documentNode, metaNode;
138 if(data[formatter_prefix+ 'orig_before']) {
139 txt = idx > 0 && contents[idx-1].nodeType === Node.TEXT_NODE ? contents[idx-1] : null;
140 if(txt && txt.data === data[formatter_prefix + 'orig_before_transformed']) {
141 txt.data = data[formatter_prefix+ 'orig_before_original'];
143 el.before(data[formatter_prefix+ 'orig_before']);
146 if(data[formatter_prefix+ 'orig_after']) {
147 txt = idx < contents.length-1 && contents[idx+1].nodeType === Node.TEXT_NODE ? contents[idx+1] : null;
148 if(txt && txt.data === data[formatter_prefix + 'orig_after_transformed']) {
149 txt.data = data[formatter_prefix+ 'orig_after_original'];
151 el.after(data[formatter_prefix+ 'orig_after']);
154 if(data[formatter_prefix+ 'orig_begin']) {
155 el.prepend(data[formatter_prefix+ 'orig_begin']);
157 if(data[formatter_prefix+ 'orig_end']) {
158 contents = el.contents();
159 txt = (contents.length && contents[contents.length-1].nodeType === Node.TEXT_NODE) ? contents[contents.length-1] : null;
160 if(txt && txt.data === data[formatter_prefix + 'orig_end_transformed']) {
161 txt.data = data[formatter_prefix+ 'orig_end_original'];
163 el.append(data[formatter_prefix+ 'orig_end']);
168 if(this.nodeType === Node.ELEMENT_NODE) {
169 documentNode = doc.createDocumentNode(this);
170 metaNode = $('<metadata>');
171 documentNode.getMetadata().forEach(function(row) {
172 metaNode.append('<dc:'+ row.key + '>' + row.value + '</dc:' + row.key + '>');
174 if(metaNode.children().length) {
175 $(this).prepend(metaNode);
187 // WLXMLElementNode.prototype.transformations.register(transformations.createContextTransformation({
188 // name: 'wlxml.setMetaAttribute',
189 // impl: function(args) {
190 // this.setMetaAttribute(args.name, args.value);
192 // getChangeRoot: function() {
193 // return this.context;
199 var WLXMLDocumentNode = function() {
200 smartxml.DocumentNode.apply(this, arguments);
202 WLXMLDocumentNode.prototype = Object.create(smartxml.DocumentNode.prototype);
205 var WLXMLTextNode = function() {
206 smartxml.TextNode.apply(this, arguments);
208 WLXMLTextNode.prototype = Object.create(smartxml.TextNode.prototype);
209 $.extend(WLXMLTextNode.prototype, WLXMLDocumentNodeMethods);
211 var WLXMLDocument = function(xml, options) {
212 this.classMethods = {};
213 this.classTransformations = {};
214 smartxml.Document.call(this, xml, [metadataExtension]);
215 this.options = options;
218 var formatter_prefix = '_wlxml_formatter_';
221 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
222 $.extend(WLXMLDocument.prototype, {
223 ElementNodeFactory: WLXMLElementNode,
224 TextNodeFactory: WLXMLTextNode,
225 loadXML: function(xml) {
226 smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
227 this.trigger('contentSet');
230 normalizeXML: function(nativeNode) {
232 prefixLength = 'dc:'.length;
234 $(nativeNode).find('metadata').each(function() {
235 var metadataNode = $(this),
236 owner = doc.createDocumentNode(metadataNode.parent()[0]),
237 metadata = owner.getMetadata();
239 metadataNode.children().each(function() {
240 metadata.add({key: (this.tagName).toLowerCase().substr(prefixLength), value: $(this).text()}, {undoable: false});
242 metadataNode.remove();
244 nativeNode.normalize();
246 $(nativeNode).find(':not(iframe)').addBack().contents()
247 .filter(function() {return this.nodeType === Node.TEXT_NODE;})
250 text = {original: el.text(), trimmed: $.trim(el.text())},
251 elParent = el.parent(),
252 hasSpanParent = elParent.prop('tagName') === 'SPAN',
253 hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
254 hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
257 var addInfo = function(toAdd, where, transformed, original) {
258 var parentContents = elParent.contents(),
259 idx = parentContents.index(el[0]),
260 prev = idx > 0 ? parentContents[idx-1] : null,
261 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
264 if(where === 'above') {
265 target = prev ? $(prev) : elParent;
266 key = prev ? 'orig_after' : 'orig_begin';
267 } else if(where === 'below') {
268 target = next ? $(next) : elParent;
269 key = next ? 'orig_before' : 'orig_end';
270 } else { throw new Error();}
272 target.data(formatter_prefix + key, toAdd);
273 if(transformed !== undefined) {
274 target.data(formatter_prefix + key + '_transformed', transformed);
276 if(original !== undefined) {
277 target.data(formatter_prefix + key + '_original', original);
281 text.transformed = text.trimmed;
283 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
284 var startSpace = /\s/g.test(text.original.substr(0,1)),
285 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
286 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
287 text.transformed += text.trimmed;
288 text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
290 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
291 text.transformed = ' ';
295 if(!text.transformed) {
296 addInfo(text.original, 'below');
298 return true; // continue
301 if(text.transformed !== text.original) {
302 // if(!text.trimmed) {
303 // addInfo(text.original, 'below');
305 var startingMatch = text.original.match(/^\s+/g),
306 endingMatch = text.original.match(/\s+$/g),
307 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
308 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
310 if(endingWhiteSpace) {
311 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
312 endingWhiteSpace = endingWhiteSpace.substr(1);
314 addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
317 if(startingWhiteSpace && text.trimmed) {
318 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
319 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
321 addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
325 /* globals document */
326 el.replaceWith(document.createTextNode(text.transformed));
332 registerClassTransformation: function(Transformation, className) {
333 var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || {});
334 thisClassTransformations[Transformation.prototype.name] = function() {
335 var nodeInstance = this;
336 var args = Array.prototype.slice.call(arguments, 0);
337 return nodeInstance.transform(Transformation, args);
341 registerClassMethod: function(methodName, method, className) {
342 var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
343 thisClassMethods[methodName] = method;
346 registerExtension: function(extension) {
348 smartxml.Document.prototype.registerExtension.call(this, extension);
351 _.pairs(extension.wlxmlClass).forEach(function(pair) {
352 var className = pair[0],
353 classExtension = pair[1];
355 _.pairs(classExtension.methods || {}).forEach(function(pair) {
358 doc.registerClassMethod(name, method, className);
361 _.pairs(classExtension.transformations || {}).forEach(function(pair) {
364 doc.registerClassTransformation(transformations.createContextTransformation(desc, name), className);
374 attrs: {href: {type: 'string'}}
380 WLXMLDocumentFromXML: function(xml, options, Factory) {
381 options = _.extend({wlxmlClasses: wlxmlClasses}, options);
382 Factory = Factory || WLXMLDocument;
383 return new Factory(xml, options);
386 WLXMLElementNodeFromXML: function(xml) {
387 return this.WLXMLDocumentFromXML(xml).root;
390 WLXMLDocument: WLXMLDocument,
391 getClassHierarchy: getClassLists