5 'smartxml/transformations',
6 'wlxml/extensions/metadata/metadata',
7 'wlxml/extensions/comments/comments'
8 ], function($, _, smartxml, transformations, metadataExtension, commentExtension) {
15 var WLXMLDocumentNodeMethods = {
16 isInside: function(query) {
17 var parent = this.getParent(query);
20 getParent: function(query) {
22 var me = this.nodeType === Node.ELEMENT_NODE ? [this] : [],
24 me.concat(this.parents()).some(function(node) {
34 var AttributesList = function() {};
35 AttributesList.prototype = Object.create({});
36 AttributesList.prototype.keys = function() {
40 var getClassLists = function(klassName) {
42 classParts = [''].concat(klassName.split('.')),
45 classParts.forEach(function(part) {
46 classCurrent = classCurrent ? classCurrent + '.' + part : part;
47 toret.push(classCurrent);
52 var installObject = function(instance, klass) {
56 getClassLists(klass).forEach(function(klassName) {
57 _.extend(methods, instance.document.classMethods[klassName] || {});
58 _.extend(methods, instance.document.classTransformations[klassName] || {});
60 instance.object = Object.create(_.extend({}, methods, transformations));
61 _.keys(methods).concat(_.keys(transformations)).forEach(function(key) {
62 if(_.isFunction(instance.object[key])) {
63 instance.object[key] = _.bind(instance.object[key], instance);
68 var WLXMLElementNode = function(nativeNode, document) {
69 smartxml.ElementNode.call(this, nativeNode, document);
70 installObject(this, this.getClass());
72 WLXMLElementNode.prototype = Object.create(smartxml.ElementNode.prototype);
74 $.extend(WLXMLElementNode.prototype, WLXMLDocumentNodeMethods, smartxml.ElementNode.prototype, {
75 getClass: function() {
76 return this.getAttr('class') || '';
78 getClassHierarchy: function() {
79 return getClassLists(this.getClass());
81 setClass: function(klass) {
82 if(klass !== this.klass) {
83 installObject(this, klass);
84 return this.setAttr('class', klass);
88 if(typeof query === 'string') {
89 query = {klass: query};
91 return (_.isUndefined(query.klass) || this.getClass().substr(0, query.klass.length) === query.klass) &&
92 (_.isUndefined(query.tagName) || this.getTagName() === query.tagName);
94 getMetaAttributes: function() {
95 var toret = new AttributesList(),
96 classParts = [''].concat(this.getClass().split('.')),
97 classCurrent, classDesc;
99 classParts.forEach(function(part) {
100 classCurrent = classCurrent ? classCurrent + '.' + part : part;
101 classDesc = this.document.options.wlxmlClasses[classCurrent];
103 _.keys(classDesc.attrs).forEach(function(attrName) {
104 toret[attrName] = _.extend({value: this.getAttr(attrName)}, classDesc.attrs[attrName]);
110 setMetaAttribute: function(key, value) {
111 this.setAttr(key, value);
113 getOtherAttributes: function() {
116 this.getAttrs().forEach(function(attr) {
117 if(attr.name !== 'class' && !node.isMetaAttribute(attr.name)) {
118 toret[attr.name] = {value: attr.value};
123 isMetaAttribute: function(attrName) {
124 return attrName !== 'class' &&_.contains(_.keys(this.getMetaAttributes()), attrName);
127 _getXMLDOMToDump: function() {
128 var DOM = this._$.clone(true, true),
131 DOM.find('*').addBack().each(function() {
133 parent = el.parent(),
134 contents = parent.contents(),
135 idx = contents.index(el),
139 var txt, documentNode, metaNode;
141 if(data[formatter_prefix+ 'orig_before']) {
142 txt = idx > 0 && contents[idx-1].nodeType === Node.TEXT_NODE ? contents[idx-1] : null;
143 if(txt && txt.data === data[formatter_prefix + 'orig_before_transformed']) {
144 txt.data = data[formatter_prefix+ 'orig_before_original'];
146 el.before(data[formatter_prefix+ 'orig_before']);
149 if(data[formatter_prefix+ 'orig_after']) {
150 txt = idx < contents.length-1 && contents[idx+1].nodeType === Node.TEXT_NODE ? contents[idx+1] : null;
151 if(txt && txt.data === data[formatter_prefix + 'orig_after_transformed']) {
152 txt.data = data[formatter_prefix+ 'orig_after_original'];
154 el.after(data[formatter_prefix+ 'orig_after']);
157 if(data[formatter_prefix+ 'orig_begin']) {
158 el.prepend(data[formatter_prefix+ 'orig_begin']);
160 if(data[formatter_prefix+ 'orig_end']) {
161 contents = el.contents();
162 txt = (contents.length && contents[contents.length-1].nodeType === Node.TEXT_NODE) ? contents[contents.length-1] : null;
163 if(txt && txt.data === data[formatter_prefix + 'orig_end_transformed']) {
164 txt.data = data[formatter_prefix+ 'orig_end_original'];
166 el.append(data[formatter_prefix+ 'orig_end']);
171 if(this.nodeType === Node.ELEMENT_NODE) {
172 documentNode = doc.createDocumentNode(this);
173 metaNode = $('<metadata>');
174 documentNode.getMetadata().forEach(function(row) {
175 metaNode.append('<dc:'+ row.key + '>' + row.value + '</dc:' + row.key + '>');
177 if(metaNode.children().length) {
178 $(this).prepend(metaNode);
190 // WLXMLElementNode.prototype.transformations.register(transformations.createContextTransformation({
191 // name: 'wlxml.setMetaAttribute',
192 // impl: function(args) {
193 // this.setMetaAttribute(args.name, args.value);
195 // getChangeRoot: function() {
196 // return this.context;
202 var WLXMLDocumentNode = function() {
203 smartxml.DocumentNode.apply(this, arguments);
205 WLXMLDocumentNode.prototype = Object.create(smartxml.DocumentNode.prototype);
208 var WLXMLTextNode = function() {
209 smartxml.TextNode.apply(this, arguments);
211 WLXMLTextNode.prototype = Object.create(smartxml.TextNode.prototype);
212 $.extend(WLXMLTextNode.prototype, WLXMLDocumentNodeMethods);
214 var WLXMLDocument = function(xml, options) {
215 this.classMethods = {};
216 this.classTransformations = {};
217 smartxml.Document.call(this, xml, [metadataExtension, commentExtension]);
218 this.options = options;
221 var formatter_prefix = '_wlxml_formatter_';
224 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
225 $.extend(WLXMLDocument.prototype, {
226 ElementNodeFactory: WLXMLElementNode,
227 TextNodeFactory: WLXMLTextNode,
228 loadXML: function(xml) {
229 smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
230 this.trigger('contentSet');
233 normalizeXML: function(nativeNode) {
235 prefixLength = 'dc:'.length;
237 $(nativeNode).find('metadata').each(function() {
238 var metadataNode = $(this),
239 owner = doc.createDocumentNode(metadataNode.parent()[0]),
240 metadata = owner.getMetadata();
242 metadataNode.children().each(function() {
243 metadata.add({key: (this.tagName).toLowerCase().substr(prefixLength), value: $(this).text()}, {undoable: false});
245 metadataNode.remove();
247 nativeNode.normalize();
249 $(nativeNode).find(':not(iframe)').addBack().contents()
250 .filter(function() {return this.nodeType === Node.TEXT_NODE;})
253 text = {original: el.text(), trimmed: $.trim(el.text())},
254 elParent = el.parent(),
255 hasSpanParent = elParent.prop('tagName') === 'SPAN',
256 hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
257 hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
260 var addInfo = function(toAdd, where, transformed, original) {
261 var parentContents = elParent.contents(),
262 idx = parentContents.index(el[0]),
263 prev = idx > 0 ? parentContents[idx-1] : null,
264 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
267 if(where === 'above') {
268 target = prev ? $(prev) : elParent;
269 key = prev ? 'orig_after' : 'orig_begin';
270 } else if(where === 'below') {
271 target = next ? $(next) : elParent;
272 key = next ? 'orig_before' : 'orig_end';
273 } else { throw new Error();}
275 target.data(formatter_prefix + key, toAdd);
276 if(transformed !== undefined) {
277 target.data(formatter_prefix + key + '_transformed', transformed);
279 if(original !== undefined) {
280 target.data(formatter_prefix + key + '_original', original);
284 text.transformed = text.trimmed;
286 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
287 var startSpace = /\s/g.test(text.original.substr(0,1)),
288 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
289 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
290 text.transformed += text.trimmed;
291 text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
293 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
294 text.transformed = ' ';
298 if(!text.transformed) {
299 addInfo(text.original, 'below');
301 return true; // continue
304 if(text.transformed !== text.original) {
305 // if(!text.trimmed) {
306 // addInfo(text.original, 'below');
308 var startingMatch = text.original.match(/^\s+/g),
309 endingMatch = text.original.match(/\s+$/g),
310 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
311 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
313 if(endingWhiteSpace) {
314 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
315 endingWhiteSpace = endingWhiteSpace.substr(1);
317 addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
320 if(startingWhiteSpace && text.trimmed) {
321 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
322 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
324 addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
328 /* globals document */
329 el.replaceWith(document.createTextNode(text.transformed));
335 registerClassTransformation: function(Transformation, className) {
336 var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || {});
337 thisClassTransformations[Transformation.prototype.name] = function() {
338 var nodeInstance = this;
339 var args = Array.prototype.slice.call(arguments, 0);
340 return nodeInstance.transform(Transformation, args);
344 registerClassMethod: function(methodName, method, className) {
345 var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
346 thisClassMethods[methodName] = method;
349 registerExtension: function(extension) {
351 smartxml.Document.prototype.registerExtension.call(this, extension);
354 _.pairs(extension.wlxmlClass).forEach(function(pair) {
355 var className = pair[0],
356 classExtension = pair[1];
358 _.pairs(classExtension.methods || {}).forEach(function(pair) {
361 doc.registerClassMethod(name, method, className);
364 _.pairs(classExtension.transformations || {}).forEach(function(pair) {
367 doc.registerClassTransformation(transformations.createContextTransformation(desc, name), className);
377 attrs: {href: {type: 'string'}}
383 WLXMLDocumentFromXML: function(xml, options, Factory) {
384 options = _.extend({wlxmlClasses: wlxmlClasses}, options);
385 Factory = Factory || WLXMLDocument;
386 return new Factory(xml, options);
389 WLXMLElementNodeFromXML: function(xml) {
390 return this.WLXMLDocumentFromXML(xml).root;
393 WLXMLDocument: WLXMLDocument,
394 getClassHierarchy: getClassLists