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] : [],
36 me.concat(this.parents()).some(function(node) {
37 if(_.isFunction(node.object.isContextRoot) && node.object.isContextRoot(this)) {
46 var getClassLists = function(klassName) {
48 classParts = [''].concat(klassName.split('.')),
51 classParts.forEach(function(part) {
52 classCurrent = classCurrent ? classCurrent + '.' + part : part;
53 toret.push(classCurrent);
58 var installObject = function(instance, klass) {
62 getClassLists(klass).forEach(function(klassName) {
63 _.extend(methods, instance.document.classMethods[klassName] || {});
64 _.extend(methods, instance.document.classTransformations[klassName] || {});
66 instance.object = Object.create(_.extend({}, methods, transformations));
67 _.keys(methods).concat(_.keys(transformations)).forEach(function(key) {
68 if(_.isFunction(instance.object[key])) {
69 instance.object[key] = _.bind(instance.object[key], instance);
74 var WLXMLElementNode = function(nativeNode, document) {
75 smartxml.ElementNode.call(this, nativeNode, document);
76 installObject(this, this.getClass());
78 WLXMLElementNode.prototype = Object.create(smartxml.ElementNode.prototype);
80 $.extend(WLXMLElementNode.prototype, WLXMLDocumentNodeMethods, smartxml.ElementNode.prototype, {
81 getClass: function() {
82 return this.getAttr('class') || '';
84 getClassHierarchy: function() {
85 return getClassLists(this.getClass());
87 setClass: function(klass) {
88 if(klass !== this.klass) {
89 installObject(this, klass);
90 return this.setAttr('class', klass);
94 if(typeof query === 'string') {
95 query = {klass: query};
97 return (_.isUndefined(query.klass) || this.getClass().substr(0, query.klass.length) === query.klass) &&
98 (_.isUndefined(query.tagName) || this.getTagName() === query.tagName);
100 hasChild: function(query) {
101 return this.contents().some(function(child) {
102 return child.is(query);
106 _getXMLDOMToDump: function() {
107 var DOM = this._$.clone(true, true),
110 DOM.find('*').addBack().each(function() {
112 parent = el.parent(),
113 contents = parent.contents(),
114 idx = contents.index(el),
118 var txt, documentNode, metaNode;
120 if(data[formatter_prefix+ 'orig_before']) {
121 txt = idx > 0 && contents[idx-1].nodeType === Node.TEXT_NODE ? contents[idx-1] : null;
122 if(txt && txt.data === data[formatter_prefix + 'orig_before_transformed']) {
123 txt.data = data[formatter_prefix+ 'orig_before_original'];
125 el.before(data[formatter_prefix+ 'orig_before']);
128 if(data[formatter_prefix+ 'orig_after']) {
129 txt = idx < contents.length-1 && contents[idx+1].nodeType === Node.TEXT_NODE ? contents[idx+1] : null;
130 if(txt && txt.data === data[formatter_prefix + 'orig_after_transformed']) {
131 txt.data = data[formatter_prefix+ 'orig_after_original'];
133 el.after(data[formatter_prefix+ 'orig_after']);
136 if(data[formatter_prefix+ 'orig_begin']) {
137 el.prepend(data[formatter_prefix+ 'orig_begin']);
139 if(data[formatter_prefix+ 'orig_end']) {
140 contents = el.contents();
141 txt = (contents.length && contents[contents.length-1].nodeType === Node.TEXT_NODE) ? contents[contents.length-1] : null;
142 if(txt && txt.data === data[formatter_prefix + 'orig_end_transformed']) {
143 txt.data = data[formatter_prefix+ 'orig_end_original'];
145 el.append(data[formatter_prefix+ 'orig_end']);
150 if(this.nodeType === Node.ELEMENT_NODE) {
151 documentNode = doc.createDocumentNode(this);
152 metaNode = $('<metadata>');
153 documentNode.getMetadata().forEach(function(row) {
154 metaNode.append('<dc:'+ row.key + '>' + row.value + '</dc:' + row.key + '>');
156 if(metaNode.children().length) {
157 $(this).prepend(metaNode);
167 var WLXMLDocumentNode = function() {
168 smartxml.DocumentNode.apply(this, arguments);
170 WLXMLDocumentNode.prototype = Object.create(smartxml.DocumentNode.prototype);
173 var WLXMLTextNode = function() {
174 smartxml.TextNode.apply(this, arguments);
176 WLXMLTextNode.prototype = Object.create(smartxml.TextNode.prototype);
177 $.extend(WLXMLTextNode.prototype, WLXMLDocumentNodeMethods, {
178 is: function() { return false; }
181 var WLXMLDocument = function(xml, options) {
182 this.classMethods = {};
183 this.classTransformations = {};
184 smartxml.Document.call(this, xml, [metadataExtension, commentExtension]);
185 this.options = options;
188 var formatter_prefix = '_wlxml_formatter_';
191 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
192 $.extend(WLXMLDocument.prototype, {
193 ElementNodeFactory: WLXMLElementNode,
194 TextNodeFactory: WLXMLTextNode,
195 loadXML: function(xml) {
196 smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
197 this.trigger('contentSet');
200 normalizeXML: function(nativeNode) {
202 prefixLength = 'dc:'.length;
204 $(nativeNode).find('metadata').each(function() {
205 var metadataNode = $(this),
206 owner = doc.createDocumentNode(metadataNode.parent()[0]),
207 metadata = owner.getMetadata();
209 metadataNode.children().each(function() {
210 metadata.add({key: (this.tagName).toLowerCase().substr(prefixLength), value: $(this).text()}, {undoable: false});
212 metadataNode.remove();
214 nativeNode.normalize();
216 $(nativeNode).find(':not(iframe)').addBack().contents()
217 .filter(function() {return this.nodeType === Node.TEXT_NODE;})
220 text = {original: el.text(), trimmed: $.trim(el.text())},
221 elParent = el.parent(),
222 hasSpanParent = elParent.prop('tagName') === 'SPAN',
223 hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
224 hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
227 var addInfo = function(toAdd, where, transformed, original) {
228 var parentContents = elParent.contents(),
229 idx = parentContents.index(el[0]),
230 prev = idx > 0 ? parentContents[idx-1] : null,
231 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
234 if(where === 'above') {
235 target = prev ? $(prev) : elParent;
236 key = prev ? 'orig_after' : 'orig_begin';
237 } else if(where === 'below') {
238 target = next ? $(next) : elParent;
239 key = next ? 'orig_before' : 'orig_end';
240 } else { throw new Error();}
242 target.data(formatter_prefix + key, toAdd);
243 if(transformed !== undefined) {
244 target.data(formatter_prefix + key + '_transformed', transformed);
246 if(original !== undefined) {
247 target.data(formatter_prefix + key + '_original', original);
251 text.transformed = text.trimmed;
253 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
254 var startSpace = /\s/g.test(text.original.substr(0,1)),
255 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
256 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
257 text.transformed += text.trimmed;
258 text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
260 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
261 text.transformed = ' ';
265 if(!text.transformed) {
266 addInfo(text.original, 'below');
268 return true; // continue
271 if(text.transformed !== text.original) {
272 // if(!text.trimmed) {
273 // addInfo(text.original, 'below');
275 var startingMatch = text.original.match(/^\s+/g),
276 endingMatch = text.original.match(/\s+$/g),
277 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
278 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
280 if(endingWhiteSpace) {
281 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
282 endingWhiteSpace = endingWhiteSpace.substr(1);
284 addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
287 if(startingWhiteSpace && text.trimmed) {
288 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
289 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
291 addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
295 /* globals document */
296 el.replaceWith(document.createTextNode(text.transformed));
302 registerClassTransformation: function(Transformation, className) {
303 var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || {});
304 thisClassTransformations[Transformation.prototype.name] = function() {
305 var nodeInstance = this;
306 var args = Array.prototype.slice.call(arguments, 0);
307 return nodeInstance.transform(Transformation, args);
311 registerClassMethod: function(methodName, method, className) {
312 var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
313 thisClassMethods[methodName] = method;
316 registerExtension: function(extension) {
317 smartxml.Document.prototype.registerExtension.call(this, extension);
320 _.pairs(extension.wlxmlClass).forEach(function(pair) {
321 var className = pair[0],
322 classExtension = pair[1];
324 _.pairs(classExtension.methods || {}).forEach(function(pair) {
327 doc.registerClassMethod(name, method, className);
330 _.pairs(classExtension.transformations || {}).forEach(function(pair) {
333 doc.registerClassTransformation(transformations.createContextTransformation(desc, name), className);
342 WLXMLDocumentFromXML: function(xml, options, Factory) {
343 Factory = Factory || WLXMLDocument;
344 return new Factory(xml, options);
346 WLXMLElementNodeFromXML: function(xml) {
347 return this.WLXMLDocumentFromXML(xml).root;
350 WLXMLDocument: WLXMLDocument,
351 getClassHierarchy: getClassLists