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();
242 $(nativeNode).find(':not(iframe)').addBack().contents()
243 .filter(function() {return this.nodeType === Node.TEXT_NODE;})
246 text = {original: el.text(), trimmed: $.trim(el.text())},
247 elParent = el.parent(),
248 hasSpanParent = elParent.prop('tagName') === 'SPAN',
249 hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
250 hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
253 var addInfo = function(toAdd, where, transformed, original) {
254 var parentContents = elParent.contents(),
255 idx = parentContents.index(el[0]),
256 prev = idx > 0 ? parentContents[idx-1] : null,
257 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
260 if(where === 'above') {
261 target = prev ? $(prev) : elParent;
262 key = prev ? 'orig_after' : 'orig_begin';
263 } else if(where === 'below') {
264 target = next ? $(next) : elParent;
265 key = next ? 'orig_before' : 'orig_end';
266 } else { throw new Error();}
268 target.data(formatter_prefix + key, toAdd);
269 if(transformed !== undefined) {
270 target.data(formatter_prefix + key + '_transformed', transformed);
272 if(original !== undefined) {
273 target.data(formatter_prefix + key + '_original', original);
277 text.transformed = text.trimmed;
279 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
280 var startSpace = /\s/g.test(text.original.substr(0,1)),
281 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
282 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
283 text.transformed += text.trimmed;
284 text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
286 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
287 text.transformed = ' ';
291 if(!text.transformed) {
292 addInfo(text.original, 'below');
294 return true; // continue
297 if(text.transformed !== text.original) {
298 // if(!text.trimmed) {
299 // addInfo(text.original, 'below');
301 var startingMatch = text.original.match(/^\s+/g),
302 endingMatch = text.original.match(/\s+$/g),
303 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
304 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
306 if(endingWhiteSpace) {
307 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
308 endingWhiteSpace = endingWhiteSpace.substr(1);
310 addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
313 if(startingWhiteSpace && text.trimmed) {
314 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
315 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
317 addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
321 /* globals document */
322 el.replaceWith(document.createTextNode(text.transformed));
328 registerClassTransformation: function(Transformation, className) {
329 var thisClassTransformations = (this.classTransformations[className] = this.classTransformations[className] || {});
330 thisClassTransformations[Transformation.prototype.name] = function() {
331 var nodeInstance = this;
332 var args = Array.prototype.slice.call(arguments, 0);
333 return nodeInstance.transform(Transformation, args);
337 registerClassMethod: function(methodName, method, className) {
338 var thisClassMethods = (this.classMethods[className] = this.classMethods[className] || {});
339 thisClassMethods[methodName] = method;
342 registerExtension: function(extension) {
343 smartxml.Document.prototype.registerExtension.call(this, extension);
346 _.pairs(extension.wlxmlClass).forEach(function(pair) {
347 var className = pair[0],
348 classExtension = pair[1];
350 _.pairs(classExtension.methods || {}).forEach(function(pair) {
353 doc.registerClassMethod(name, method, className);
356 _.pairs(classExtension.transformations || {}).forEach(function(pair) {
359 doc.registerClassTransformation(transformations.createContextTransformation(desc, name), className);
368 WLXMLDocumentFromXML: function(xml, options, Factory) {
369 Factory = Factory || WLXMLDocument;
370 return new Factory(xml, options);
372 WLXMLElementNodeFromXML: function(xml) {
373 return this.WLXMLDocumentFromXML(xml).root;
376 WLXMLDocument: WLXMLDocument,
377 getClassHierarchy: getClassLists