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 hasChild: function(query) {
95 return this.contents().some(function(child) {
96 return child.is(query);
99 getMetaAttributes: function() {
100 var toret = new AttributesList(),
101 classParts = [''].concat(this.getClass().split('.')),
102 classCurrent, classDesc;
104 classParts.forEach(function(part) {
105 classCurrent = classCurrent ? classCurrent + '.' + part : part;
106 classDesc = this.document.options.wlxmlClasses[classCurrent];
108 _.keys(classDesc.attrs).forEach(function(attrName) {
109 toret[attrName] = _.extend({value: this.getAttr(attrName)}, classDesc.attrs[attrName]);
115 setMetaAttribute: function(key, value) {
116 this.setAttr(key, value);
118 getOtherAttributes: function() {
121 this.getAttrs().forEach(function(attr) {
122 if(attr.name !== 'class' && !node.isMetaAttribute(attr.name)) {
123 toret[attr.name] = {value: attr.value};
128 isMetaAttribute: function(attrName) {
129 return attrName !== 'class' &&_.contains(_.keys(this.getMetaAttributes()), attrName);
132 _getXMLDOMToDump: function() {
133 var DOM = this._$.clone(true, true),
136 DOM.find('*').addBack().each(function() {
138 parent = el.parent(),
139 contents = parent.contents(),
140 idx = contents.index(el),
144 var txt, documentNode, metaNode;
146 if(data[formatter_prefix+ 'orig_before']) {
147 txt = idx > 0 && contents[idx-1].nodeType === Node.TEXT_NODE ? contents[idx-1] : null;
148 if(txt && txt.data === data[formatter_prefix + 'orig_before_transformed']) {
149 txt.data = data[formatter_prefix+ 'orig_before_original'];
151 el.before(data[formatter_prefix+ 'orig_before']);
154 if(data[formatter_prefix+ 'orig_after']) {
155 txt = idx < contents.length-1 && contents[idx+1].nodeType === Node.TEXT_NODE ? contents[idx+1] : null;
156 if(txt && txt.data === data[formatter_prefix + 'orig_after_transformed']) {
157 txt.data = data[formatter_prefix+ 'orig_after_original'];
159 el.after(data[formatter_prefix+ 'orig_after']);
162 if(data[formatter_prefix+ 'orig_begin']) {
163 el.prepend(data[formatter_prefix+ 'orig_begin']);
165 if(data[formatter_prefix+ 'orig_end']) {
166 contents = el.contents();
167 txt = (contents.length && contents[contents.length-1].nodeType === Node.TEXT_NODE) ? contents[contents.length-1] : null;
168 if(txt && txt.data === data[formatter_prefix + 'orig_end_transformed']) {
169 txt.data = data[formatter_prefix+ 'orig_end_original'];
171 el.append(data[formatter_prefix+ 'orig_end']);
176 if(this.nodeType === Node.ELEMENT_NODE) {
177 documentNode = doc.createDocumentNode(this);
178 metaNode = $('<metadata>');
179 documentNode.getMetadata().forEach(function(row) {
180 metaNode.append('<dc:'+ row.key + '>' + row.value + '</dc:' + row.key + '>');
182 if(metaNode.children().length) {
183 $(this).prepend(metaNode);
195 // WLXMLElementNode.prototype.transformations.register(transformations.createContextTransformation({
196 // name: 'wlxml.setMetaAttribute',
197 // impl: function(args) {
198 // this.setMetaAttribute(args.name, args.value);
200 // getChangeRoot: function() {
201 // return this.context;
207 var WLXMLDocumentNode = function() {
208 smartxml.DocumentNode.apply(this, arguments);
210 WLXMLDocumentNode.prototype = Object.create(smartxml.DocumentNode.prototype);
213 var WLXMLTextNode = function() {
214 smartxml.TextNode.apply(this, arguments);
216 WLXMLTextNode.prototype = Object.create(smartxml.TextNode.prototype);
217 $.extend(WLXMLTextNode.prototype, WLXMLDocumentNodeMethods, {
218 is: function() { return false; }
221 var WLXMLDocument = function(xml, options) {
222 this.classMethods = {};
223 this.classTransformations = {};
224 smartxml.Document.call(this, xml, [metadataExtension, commentExtension]);
225 this.options = options;
228 var formatter_prefix = '_wlxml_formatter_';
231 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
232 $.extend(WLXMLDocument.prototype, {
233 ElementNodeFactory: WLXMLElementNode,
234 TextNodeFactory: WLXMLTextNode,
235 loadXML: function(xml) {
236 smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
237 this.trigger('contentSet');
240 normalizeXML: function(nativeNode) {
242 prefixLength = 'dc:'.length;
244 $(nativeNode).find('metadata').each(function() {
245 var metadataNode = $(this),
246 owner = doc.createDocumentNode(metadataNode.parent()[0]),
247 metadata = owner.getMetadata();
249 metadataNode.children().each(function() {
250 metadata.add({key: (this.tagName).toLowerCase().substr(prefixLength), value: $(this).text()}, {undoable: false});
252 metadataNode.remove();
254 nativeNode.normalize();
256 $(nativeNode).find(':not(iframe)').addBack().contents()
257 .filter(function() {return this.nodeType === Node.TEXT_NODE;})
260 text = {original: el.text(), trimmed: $.trim(el.text())},
261 elParent = el.parent(),
262 hasSpanParent = elParent.prop('tagName') === 'SPAN',
263 hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
264 hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
267 var addInfo = function(toAdd, where, transformed, original) {
268 var parentContents = elParent.contents(),
269 idx = parentContents.index(el[0]),
270 prev = idx > 0 ? parentContents[idx-1] : null,
271 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
274 if(where === 'above') {
275 target = prev ? $(prev) : elParent;
276 key = prev ? 'orig_after' : 'orig_begin';
277 } else if(where === 'below') {
278 target = next ? $(next) : elParent;
279 key = next ? 'orig_before' : 'orig_end';
280 } else { throw new Error();}
282 target.data(formatter_prefix + key, toAdd);
283 if(transformed !== undefined) {
284 target.data(formatter_prefix + key + '_transformed', transformed);
286 if(original !== undefined) {
287 target.data(formatter_prefix + key + '_original', original);
291 text.transformed = text.trimmed;
293 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
294 var startSpace = /\s/g.test(text.original.substr(0,1)),
295 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
296 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
297 text.transformed += text.trimmed;
298 text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
300 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
301 text.transformed = ' ';
305 if(!text.transformed) {
306 addInfo(text.original, 'below');
308 return true; // continue
311 if(text.transformed !== text.original) {
312 // if(!text.trimmed) {
313 // addInfo(text.original, 'below');
315 var startingMatch = text.original.match(/^\s+/g),
316 endingMatch = text.original.match(/\s+$/g),
317 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
318 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
320 if(endingWhiteSpace) {
321 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
322 endingWhiteSpace = endingWhiteSpace.substr(1);
324 addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
327 if(startingWhiteSpace && text.trimmed) {
328 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
329 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
331 addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
335 /* globals document */
336 el.replaceWith(document.createTextNode(text.transformed));
342 registerClassTransformation: function(Transformation, className) {
343 var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || {});
344 thisClassTransformations[Transformation.prototype.name] = function() {
345 var nodeInstance = this;
346 var args = Array.prototype.slice.call(arguments, 0);
347 return nodeInstance.transform(Transformation, args);
351 registerClassMethod: function(methodName, method, className) {
352 var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
353 thisClassMethods[methodName] = method;
356 registerExtension: function(extension) {
358 smartxml.Document.prototype.registerExtension.call(this, extension);
361 _.pairs(extension.wlxmlClass).forEach(function(pair) {
362 var className = pair[0],
363 classExtension = pair[1];
365 _.pairs(classExtension.methods || {}).forEach(function(pair) {
368 doc.registerClassMethod(name, method, className);
371 _.pairs(classExtension.transformations || {}).forEach(function(pair) {
374 doc.registerClassTransformation(transformations.createContextTransformation(desc, name), className);
384 attrs: {href: {type: 'string'}}
390 WLXMLDocumentFromXML: function(xml, options, Factory) {
391 options = _.extend({wlxmlClasses: wlxmlClasses}, options);
392 Factory = Factory || WLXMLDocument;
393 return new Factory(xml, options);
396 WLXMLElementNodeFromXML: function(xml) {
397 return this.WLXMLDocumentFromXML(xml).root;
400 WLXMLDocument: WLXMLDocument,
401 getClassHierarchy: getClassLists