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) {
28 return !!toret || (!node.sameNode(this) && node.isContextRoot());
33 isContextRoot: function() {
34 var me = this.nodeType === Node.ELEMENT_NODE ? [this] : [],
39 me.concat(this.parents()).some(function(node) {
40 if(_.isFunction(node.object.isContextRoot) && node.object.isContextRoot(this)) {
49 var getClassLists = function(klassName) {
51 classParts = [''].concat(klassName.split('.')),
54 classParts.forEach(function(part) {
55 classCurrent = classCurrent ? classCurrent + '.' + part : part;
56 toret.push(classCurrent);
61 var installObject = function(instance, klass) {
65 getClassLists(klass).forEach(function(klassName) {
66 _.extend(methods, instance.document.classMethods[klassName] || {});
67 _.extend(methods, instance.document.classTransformations[klassName] || {});
69 instance.object = Object.create(_.extend({}, methods, transformations));
70 _.keys(methods).concat(_.keys(transformations)).forEach(function(key) {
71 if(_.isFunction(instance.object[key])) {
72 instance.object[key] = _.bind(instance.object[key], instance);
77 var WLXMLElementNode = function(nativeNode, document) {
78 smartxml.ElementNode.call(this, nativeNode, document);
79 installObject(this, this.getClass());
81 WLXMLElementNode.prototype = Object.create(smartxml.ElementNode.prototype);
83 $.extend(WLXMLElementNode.prototype, WLXMLDocumentNodeMethods, smartxml.ElementNode.prototype, {
84 getClass: function() {
85 return this.getAttr('class') || '';
87 getClassHierarchy: function() {
88 return getClassLists(this.getClass());
90 setClass: function(klass) {
91 if(klass !== this.klass) {
92 installObject(this, klass);
93 return this.setAttr('class', klass);
97 if(typeof query === 'string') {
98 query = {klass: query};
100 return (_.isUndefined(query.klass) || this.getClass().substr(0, query.klass.length) === query.klass) &&
101 (_.isUndefined(query.tagName) || this.getTagName() === query.tagName);
103 hasChild: function(query) {
104 return this.contents().some(function(child) {
105 return child.is(query);
109 _getXMLDOMToDump: function() {
110 var DOM = this._$.clone(true, true),
113 DOM.find('*').addBack().each(function() {
115 parent = el.parent(),
116 contents = parent.contents(),
117 idx = contents.index(el),
121 var txt, documentNode, metaNode;
123 if(data[formatter_prefix+ 'orig_before']) {
124 txt = idx > 0 && contents[idx-1].nodeType === Node.TEXT_NODE ? contents[idx-1] : null;
125 if(txt && txt.data === data[formatter_prefix + 'orig_before_transformed']) {
126 txt.data = data[formatter_prefix+ 'orig_before_original'];
128 el.before(data[formatter_prefix+ 'orig_before']);
131 if(data[formatter_prefix+ 'orig_after']) {
132 txt = idx < contents.length-1 && contents[idx+1].nodeType === Node.TEXT_NODE ? contents[idx+1] : null;
133 if(txt && txt.data === data[formatter_prefix + 'orig_after_transformed']) {
134 txt.data = data[formatter_prefix+ 'orig_after_original'];
136 el.after(data[formatter_prefix+ 'orig_after']);
139 if(data[formatter_prefix+ 'orig_begin']) {
140 el.prepend(data[formatter_prefix+ 'orig_begin']);
142 if(data[formatter_prefix+ 'orig_end']) {
143 contents = el.contents();
144 txt = (contents.length && contents[contents.length-1].nodeType === Node.TEXT_NODE) ? contents[contents.length-1] : null;
145 if(txt && txt.data === data[formatter_prefix + 'orig_end_transformed']) {
146 txt.data = data[formatter_prefix+ 'orig_end_original'];
148 el.append(data[formatter_prefix+ 'orig_end']);
153 if(this.nodeType === Node.ELEMENT_NODE) {
154 documentNode = doc.createDocumentNode(this);
155 metaNode = $('<metadata>');
156 documentNode.getMetadata().forEach(function(row) {
157 metaNode.append('<dc:'+ row.key + '>' + row.value + '</dc:' + row.key + '>');
159 if(metaNode.children().length) {
160 $(this).prepend(metaNode);
170 var WLXMLDocumentNode = function() {
171 smartxml.DocumentNode.apply(this, arguments);
173 WLXMLDocumentNode.prototype = Object.create(smartxml.DocumentNode.prototype);
176 var WLXMLTextNode = function() {
177 smartxml.TextNode.apply(this, arguments);
179 WLXMLTextNode.prototype = Object.create(smartxml.TextNode.prototype);
180 $.extend(WLXMLTextNode.prototype, WLXMLDocumentNodeMethods, {
181 is: function() { return false; }
184 var WLXMLDocument = function(xml, options) {
185 this.classMethods = {};
186 this.classTransformations = {};
187 smartxml.Document.call(this, xml, [metadataExtension, commentExtension]);
188 this.options = options;
191 var formatter_prefix = '_wlxml_formatter_';
194 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
195 $.extend(WLXMLDocument.prototype, {
196 ElementNodeFactory: WLXMLElementNode,
197 TextNodeFactory: WLXMLTextNode,
198 loadXML: function(xml) {
199 smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
200 this.trigger('contentSet');
203 normalizeXML: function(nativeNode) {
205 prefixLength = 'dc:'.length;
207 $(nativeNode).find('metadata').each(function() {
208 var metadataNode = $(this),
209 owner = doc.createDocumentNode(metadataNode.parent()[0]),
210 metadata = owner.getMetadata();
212 metadataNode.children().each(function() {
213 metadata.add({key: (this.tagName).toLowerCase().substr(prefixLength), value: $(this).text()}, {undoable: false});
215 metadataNode.remove();
217 nativeNode.normalize();
219 $(nativeNode).find(':not(iframe)').addBack().contents()
220 .filter(function() {return this.nodeType === Node.TEXT_NODE;})
223 text = {original: el.text(), trimmed: $.trim(el.text())},
224 elParent = el.parent(),
225 hasSpanParent = elParent.prop('tagName') === 'SPAN',
226 hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
227 hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
230 var addInfo = function(toAdd, where, transformed, original) {
231 var parentContents = elParent.contents(),
232 idx = parentContents.index(el[0]),
233 prev = idx > 0 ? parentContents[idx-1] : null,
234 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
237 if(where === 'above') {
238 target = prev ? $(prev) : elParent;
239 key = prev ? 'orig_after' : 'orig_begin';
240 } else if(where === 'below') {
241 target = next ? $(next) : elParent;
242 key = next ? 'orig_before' : 'orig_end';
243 } else { throw new Error();}
245 target.data(formatter_prefix + key, toAdd);
246 if(transformed !== undefined) {
247 target.data(formatter_prefix + key + '_transformed', transformed);
249 if(original !== undefined) {
250 target.data(formatter_prefix + key + '_original', original);
254 text.transformed = text.trimmed;
256 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
257 var startSpace = /\s/g.test(text.original.substr(0,1)),
258 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
259 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
260 text.transformed += text.trimmed;
261 text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
263 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
264 text.transformed = ' ';
268 if(!text.transformed) {
269 addInfo(text.original, 'below');
271 return true; // continue
274 if(text.transformed !== text.original) {
275 // if(!text.trimmed) {
276 // addInfo(text.original, 'below');
278 var startingMatch = text.original.match(/^\s+/g),
279 endingMatch = text.original.match(/\s+$/g),
280 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
281 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
283 if(endingWhiteSpace) {
284 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
285 endingWhiteSpace = endingWhiteSpace.substr(1);
287 addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
290 if(startingWhiteSpace && text.trimmed) {
291 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
292 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
294 addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
298 /* globals document */
299 el.replaceWith(document.createTextNode(text.transformed));
305 registerClassTransformation: function(Transformation, className) {
306 var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || {});
307 thisClassTransformations[Transformation.prototype.name] = function() {
308 var nodeInstance = this;
309 var args = Array.prototype.slice.call(arguments, 0);
310 return nodeInstance.transform(Transformation, args);
314 registerClassMethod: function(methodName, method, className) {
315 var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
316 thisClassMethods[methodName] = method;
319 registerExtension: function(extension) {
320 smartxml.Document.prototype.registerExtension.call(this, extension);
323 _.pairs(extension.wlxmlClass).forEach(function(pair) {
324 var className = pair[0],
325 classExtension = pair[1];
327 _.pairs(classExtension.methods || {}).forEach(function(pair) {
330 doc.registerClassMethod(name, method, className);
333 _.pairs(classExtension.transformations || {}).forEach(function(pair) {
336 doc.registerClassTransformation(transformations.createContextTransformation(desc, name), className);
345 WLXMLDocumentFromXML: function(xml, options, Factory) {
346 Factory = Factory || WLXMLDocument;
347 return new Factory(xml, options);
349 WLXMLElementNodeFromXML: function(xml) {
350 return this.WLXMLDocumentFromXML(xml).root;
353 WLXMLDocument: WLXMLDocument,
354 getClassHierarchy: getClassLists