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 var emptyNode = this.childNodes.length === 0;
243 var endsWithSpan = !emptyNode && this.childNodes[this.childNodes.length - 1].nodeName.toLowerCase() === 'span';
244 if(emptyNode || endsWithSpan) {
245 var fakeTextNode = window.document.createTextNode("");
246 this.appendChild(fakeTextNode);
250 $(nativeNode).find(':not(iframe)').addBack().contents()
251 .filter(function() {return this.nodeType === Node.TEXT_NODE;})
254 text = {original: el.text(), trimmed: $.trim(el.text())},
255 elParent = el.parent(),
256 hasSpanParent = elParent.prop('tagName') === 'SPAN',
257 hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
258 hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
261 var addInfo = function(toAdd, where, transformed, original) {
262 var parentContents = elParent.contents(),
263 idx = parentContents.index(el[0]),
264 prev = idx > 0 ? parentContents[idx-1] : null,
265 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
268 if(where === 'above') {
269 target = prev ? $(prev) : elParent;
270 key = prev ? 'orig_after' : 'orig_begin';
271 } else if(where === 'below') {
272 target = next ? $(next) : elParent;
273 key = next ? 'orig_before' : 'orig_end';
274 } else { throw new Error();}
276 target.data(formatter_prefix + key, toAdd);
277 if(transformed !== undefined) {
278 target.data(formatter_prefix + key + '_transformed', transformed);
280 if(original !== undefined) {
281 target.data(formatter_prefix + key + '_original', original);
285 text.transformed = text.trimmed;
287 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
288 var startSpace = /\s/g.test(text.original.substr(0,1)),
289 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
290 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
291 text.transformed += text.trimmed;
292 text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
294 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
295 text.transformed = ' ';
299 if(!text.transformed && !(el.is(':only-child') || (el.is(':last-child') && hasSpanBefore))) {
300 addInfo(text.original, 'below');
302 return true; // continue
305 if(text.transformed !== text.original) {
306 // if(!text.trimmed) {
307 // addInfo(text.original, 'below');
309 var startingMatch = text.original.match(/^\s+/g),
310 endingMatch = text.original.match(/\s+$/g),
311 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
312 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
314 if(endingWhiteSpace) {
315 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
316 endingWhiteSpace = endingWhiteSpace.substr(1);
318 addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
321 if(startingWhiteSpace && text.trimmed) {
322 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
323 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
325 addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
329 /* globals document */
330 el.replaceWith(document.createTextNode(text.transformed));
336 registerClassTransformation: function(Transformation, className) {
337 var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || {});
338 thisClassTransformations[Transformation.prototype.name] = function() {
339 var nodeInstance = this;
340 var args = Array.prototype.slice.call(arguments, 0);
341 return nodeInstance.transform(Transformation, args);
345 registerClassMethod: function(methodName, method, className) {
346 var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
347 thisClassMethods[methodName] = method;
350 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);
376 WLXMLDocumentFromXML: function(xml, options, Factory) {
377 Factory = Factory || WLXMLDocument;
378 return new Factory(xml, options);
380 WLXMLElementNodeFromXML: function(xml) {
381 return this.WLXMLDocumentFromXML(xml).root;
384 WLXMLDocument: WLXMLDocument,
385 getClassHierarchy: getClassLists