5 'smartxml/transformations',
6 'wlxml/extensions/metadata/metadata',
7 'wlxml/extensions/comments/comments',
8 'wlxml/extensions/edumed/edumed'
9 ], function($, _, smartxml, transformations, metadataExtension, commentExtension, edumedExtension) {
16 var WLXMLDocumentNodeMethods = {
17 isInside: function(query) {
18 var parent = this.getParent(query);
21 getParent: function(query) {
23 var me = this.nodeType === Node.ELEMENT_NODE ? [this] : [],
25 me.concat(this.parents()).some(function(node) {
29 return !!toret || (!node.sameNode(this) && node.isContextRoot());
34 isContextRoot: function() {
35 var me = this.nodeType === Node.ELEMENT_NODE ? [this] : [],
40 me.concat(this.parents()).some(function(node) {
41 if(_.isFunction(node.object.isContextRoot) && node.object.isContextRoot(this)) {
48 getContextRoot: function() {
50 [this].concat(this.parents()).some(function(n) {
51 if(n.isContextRoot()) {
58 hasSameContextRoot: function(other) {
59 return this.getContextRoot().sameNode(other.getContextRoot());
63 var getClassLists = function(klassName) {
65 classParts = [''].concat(klassName.split('.')),
68 classParts.forEach(function(part) {
69 classCurrent = classCurrent ? classCurrent + '.' + part : part;
70 toret.push(classCurrent);
75 var installObject = function(instance, klass) {
79 getClassLists(klass).forEach(function(klassName) {
80 _.extend(methods, instance.document.classMethods[klassName] || {});
81 _.extend(methods, instance.document.classTransformations[klassName] || {});
83 instance.object = Object.create(_.extend({}, methods, transformations));
84 _.keys(methods).concat(_.keys(transformations)).forEach(function(key) {
85 if(_.isFunction(instance.object[key])) {
86 instance.object[key] = _.bind(instance.object[key], instance);
91 var WLXMLElementNode = function(nativeNode, document) {
92 smartxml.ElementNode.call(this, nativeNode, document);
93 installObject(this, this.getClass());
95 WLXMLElementNode.prototype = Object.create(smartxml.ElementNode.prototype);
97 $.extend(WLXMLElementNode.prototype, WLXMLDocumentNodeMethods, smartxml.ElementNode.prototype, {
98 getClass: function() {
99 return this.getAttr('class') || '';
101 getClassHierarchy: function() {
102 return getClassLists(this.getClass());
104 setClass: function(klass) {
105 if(klass !== this.klass) {
106 installObject(this, klass);
107 return this.setAttr('class', klass);
110 is: function(query) {
111 if(typeof query === 'string') {
112 query = {klass: query};
114 return (_.isUndefined(query.klass) || this.getClass().substr(0, query.klass.length) === query.klass) &&
115 (_.isUndefined(query.tagName) || this.getTagName() === query.tagName);
117 hasChild: function(query) {
118 return this.contents().some(function(child) {
119 return child.is(query);
122 find: function(query) {
123 var doc = this.document;
124 return this._$.find('*')
126 return doc.createDocumentNode(this);
129 return this.is(query);
133 _getXMLDOMToDump: function() {
134 var DOM = this._$.clone(true, true),
137 DOM.find('*').addBack().each(function() {
139 parent = el.parent(),
140 contents = parent.contents(),
141 idx = contents.index(el),
145 var txt, documentNode, metaNode;
147 if(data[formatter_prefix+ 'orig_before']) {
148 txt = idx > 0 && contents[idx-1].nodeType === Node.TEXT_NODE ? contents[idx-1] : null;
149 if(txt && txt.data === data[formatter_prefix + 'orig_before_transformed']) {
150 txt.data = data[formatter_prefix+ 'orig_before_original'];
152 el.before(data[formatter_prefix+ 'orig_before']);
155 if(data[formatter_prefix+ 'orig_after']) {
156 txt = idx < contents.length-1 && contents[idx+1].nodeType === Node.TEXT_NODE ? contents[idx+1] : null;
157 if(txt && txt.data === data[formatter_prefix + 'orig_after_transformed']) {
158 txt.data = data[formatter_prefix+ 'orig_after_original'];
160 el.after(data[formatter_prefix+ 'orig_after']);
163 if(data[formatter_prefix+ 'orig_begin']) {
164 el.prepend(data[formatter_prefix+ 'orig_begin']);
166 if(data[formatter_prefix+ 'orig_end']) {
167 contents = el.contents();
168 txt = (contents.length && contents[contents.length-1].nodeType === Node.TEXT_NODE) ? contents[contents.length-1] : null;
169 if(txt && txt.data === data[formatter_prefix + 'orig_end_transformed']) {
170 txt.data = data[formatter_prefix+ 'orig_end_original'];
172 el.append(data[formatter_prefix+ 'orig_end']);
177 if(this.nodeType === Node.ELEMENT_NODE) {
178 documentNode = doc.createDocumentNode(this);
179 metaNode = $('<metadata>');
180 documentNode.getMetadata().forEach(function(row) {
181 metaNode.append('<dc:'+ row.key + '>' + row.value + '</dc:' + row.key + '>');
183 if(metaNode.children().length) {
184 $(this).prepend(metaNode);
194 var WLXMLDocumentNode = function() {
195 smartxml.DocumentNode.apply(this, arguments);
197 WLXMLDocumentNode.prototype = Object.create(smartxml.DocumentNode.prototype);
199 var WLXMLTextNode = function() {
200 smartxml.TextNode.apply(this, arguments);
202 WLXMLTextNode.prototype = Object.create(smartxml.TextNode.prototype);
203 $.extend(WLXMLTextNode.prototype, WLXMLDocumentNodeMethods, {
204 is: function() { return false; }
207 var WLXMLDocument = function(xml, options) {
208 this.classMethods = {};
209 this.classTransformations = {};
210 smartxml.Document.call(this, xml, [metadataExtension, commentExtension, edumedExtension]);
211 this.options = options;
214 var formatter_prefix = '_wlxml_formatter_';
217 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
218 $.extend(WLXMLDocument.prototype, {
219 ElementNodeFactory: WLXMLElementNode,
220 TextNodeFactory: WLXMLTextNode,
221 loadXML: function(xml) {
222 smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
223 this.trigger('contentSet');
226 normalizeXML: function(nativeNode) {
228 prefixLength = 'dc:'.length;
230 $(nativeNode).find('metadata').each(function() {
231 var metadataNode = $(this),
232 owner = doc.createDocumentNode(metadataNode.parent()[0]),
233 metadata = owner.getMetadata();
235 metadataNode.children().each(function() {
236 metadata.add({key: (this.tagName).toLowerCase().substr(prefixLength), value: $(this).text()}, {undoable: false});
238 metadataNode.remove();
240 nativeNode.normalize();
241 $(nativeNode).find('*').each(function() {
242 if (this.childNodes.length === 0) {
243 var fakeTextNode = window.document.createTextNode("");
244 this.appendChild(fakeTextNode);
248 $(nativeNode).find(':not(iframe)').addBack().contents()
249 .filter(function() {return this.nodeType === Node.TEXT_NODE;})
252 text = {original: el.text(), trimmed: $.trim(el.text())},
253 elParent = el.parent(),
254 hasSpanParent = elParent.prop('tagName') === 'SPAN',
255 hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
256 hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN',
257 onlyChild = el.is(':only-child');
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 && !onlyChild) {
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) {
350 smartxml.Document.prototype.registerExtension.call(this, extension);
353 _.pairs(extension.wlxmlClass).forEach(function(pair) {
354 var className = pair[0],
355 classExtension = pair[1];
357 _.pairs(classExtension.methods || {}).forEach(function(pair) {
360 doc.registerClassMethod(name, method, className);
363 _.pairs(classExtension.transformations || {}).forEach(function(pair) {
366 doc.registerClassTransformation(transformations.createContextTransformation(desc, name), className);
375 WLXMLDocumentFromXML: function(xml, options, Factory) {
376 Factory = Factory || WLXMLDocument;
377 return new Factory(xml, options);
379 WLXMLElementNodeFromXML: function(xml) {
380 return this.WLXMLDocumentFromXML(xml).root;
383 WLXMLDocument: WLXMLDocument,
384 getClassHierarchy: getClassLists