wlxml: inheritance in meta attributes keys, sligthly changed meta attrs api
[fnpeditor.git] / src / wlxml / wlxml.js
1 define([
2     'libs/jquery',
3     'libs/underscore',
4     'smartxml/smartxml'
5 ], function($, _, smartxml) {
6     
7 'use strict';
8
9 // utils
10
11 var isMetaAttribute = function(attrName) {
12     return attrName.substr(0, 5) === 'meta-';
13 };
14
15 //
16
17 var AttributesList = function() {};
18 AttributesList.prototype = Object.create({});
19 AttributesList.prototype.keys = function() {
20     return _.keys(this);
21 };
22
23
24 var WLXMLElementNode = function(nativeNode, document) {
25     smartxml.ElementNode.call(this, nativeNode, document);
26 };
27 WLXMLElementNode.prototype = Object.create(smartxml.ElementNode.prototype);
28
29 $.extend(WLXMLElementNode.prototype, smartxml.ElementNode.prototype, {
30     getClass: function() {
31         return this.getAttr('class') || '';
32     },
33     setClass: function(klass) {
34         return this.setAttr('class', klass);
35     },
36     getMetaAttributes: function() {
37         var toret = new AttributesList(),
38             classParts = [''].concat(this.getClass().split('.')),
39             classCurrent, classDesc;
40
41         classParts.forEach(function(part) {
42             classCurrent = classCurrent ? classCurrent + '.' + part : part;
43             classDesc = this.document.options.wlxmlClasses[classCurrent];
44             if(classDesc) {
45                 _.keys(classDesc.attrs).forEach(function(attrName) {
46                     toret[attrName] = _.extend({value: this.getAttr('meta-' + attrName)}, classDesc.attrs[attrName]);
47                 }.bind(this));
48             }
49         }.bind(this));
50         return toret;
51     },
52     getOtherAttributes: function() {
53         var toret = {};
54         this.getAttrs().forEach(function(attr) {
55             if(attr.name !== 'class' && !isMetaAttribute(attr.name)) {
56                 toret[attr.name] = attr.value;
57             }
58         });
59         return toret;
60     },
61
62     _getXMLDOMToDump: function() {
63         var DOM = this._$.clone(true, true);
64
65         DOM.find('*').addBack().each(function() {
66             var el = $(this),
67                 parent = el.parent(),
68                 contents = parent.contents(),
69                 idx = contents.index(el),
70                 data = el.data();
71
72
73             var txt;
74
75             if(data[formatter_prefix+ 'orig_before']) {
76                 txt = idx > 0 && contents[idx-1].nodeType === Node.TEXT_NODE ? contents[idx-1] : null;
77                 if(txt && txt.data === data[formatter_prefix + 'orig_before_transformed']) {
78                     txt.data = data[formatter_prefix+ 'orig_before_original'];
79                 } else {
80                     el.before(data[formatter_prefix+ 'orig_before']);
81                 }
82             }
83             if(data[formatter_prefix+ 'orig_after']) {
84                 txt = idx < contents.length-1 && contents[idx+1].nodeType === Node.TEXT_NODE ? contents[idx+1] : null;
85                 if(txt && txt.data === data[formatter_prefix + 'orig_after_transformed']) {
86                     txt.data = data[formatter_prefix+ 'orig_after_original'];
87                 } else {
88                     el.after(data[formatter_prefix+ 'orig_after']);
89                 }
90             }
91             if(data[formatter_prefix+ 'orig_begin']) {
92                 el.prepend(data[formatter_prefix+ 'orig_begin']);
93             }
94             if(data[formatter_prefix+ 'orig_end']) {
95                 contents = el.contents();
96                 txt = (contents.length && contents[contents.length-1].nodeType === Node.TEXT_NODE) ? contents[contents.length-1] : null;
97                 if(txt && txt.data === data[formatter_prefix + 'orig_end_transformed']) {
98                     txt.data = data[formatter_prefix+ 'orig_end_original'];
99                 } else {
100                     el.append(data[formatter_prefix+ 'orig_end']);
101                 }
102             }
103         });
104
105         return DOM;
106     }
107 });
108
109
110
111
112
113 var WLXMLDocument = function(xml, options) {
114     smartxml.Document.call(this, xml);
115     this.options = options;
116 };
117
118 var formatter_prefix = '_wlxml_formatter_';
119
120 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
121 $.extend(WLXMLDocument.prototype, {
122     ElementNodeFactory: WLXMLElementNode,
123
124     loadXML: function(xml) {
125         smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
126         $(this.dom).find(':not(iframe)').addBack().contents()
127             .filter(function() {return this.nodeType === Node.TEXT_NODE;})
128             .each(function() {
129                 var el = $(this),
130                     text = {original: el.text(), trimmed: $.trim(el.text())},
131                     elParent = el.parent(),
132                     hasSpanParent = elParent.prop('tagName') === 'SPAN',
133                     hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
134                     hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
135
136
137                 var addInfo = function(toAdd, where, transformed, original) {
138                     var parentContents = elParent.contents(),
139                         idx = parentContents.index(el[0]),
140                         prev = idx > 0 ? parentContents[idx-1] : null,
141                         next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
142                         target, key;
143
144                     if(where === 'above') {
145                         target = prev ? $(prev) : elParent;
146                         key = prev ? 'orig_after' : 'orig_begin';
147                     } else if(where === 'below') {
148                         target = next ? $(next) : elParent;
149                         key = next ? 'orig_before' : 'orig_end';
150                     } else { throw new Error();}
151
152                     target.data(formatter_prefix + key, toAdd);
153                     if(transformed !== undefined) {
154                         target.data(formatter_prefix + key + '_transformed', transformed);
155                     }
156                     if(original !== undefined) {
157                         target.data(formatter_prefix + key + '_original', original);
158                     }
159                 };
160
161                 text.transformed = text.trimmed;
162
163                 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
164                     var startSpace = /\s/g.test(text.original.substr(0,1)),
165                         endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
166                     text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
167                     text.transformed += text.trimmed;
168                     text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
169                 } else {
170                     if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
171                         text.transformed = ' ';
172                     }
173                 }
174
175                 if(!text.transformed) {
176                     addInfo(text.original, 'below');
177                     el.remove();
178                     return true; // continue
179                 }
180
181                 if(text.transformed !== text.original) {
182                     // if(!text.trimmed) {
183                     //     addInfo(text.original, 'below');
184                     // } else {
185                         var startingMatch = text.original.match(/^\s+/g),
186                             endingMatch = text.original.match(/\s+$/g),
187                             startingWhiteSpace = startingMatch ? startingMatch[0] : null,
188                             endingWhiteSpace = endingMatch ? endingMatch[0] : null;
189
190                         if(endingWhiteSpace) {
191                             if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
192                                 endingWhiteSpace = endingWhiteSpace.substr(1);
193                             }
194                             addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
195                         }
196
197                         if(startingWhiteSpace && text.trimmed) {
198                             if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
199                                 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
200                             }
201                             addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
202                         }
203                     //}
204                 }
205
206                 el.replaceWith(document.createTextNode(text.transformed));
207             });
208         this.trigger('contentSet');
209     }
210
211 });
212
213 var wlxmlClasses = {
214     'uri': {
215         attrs: {uri: {type: 'string'}}
216     }
217 };
218
219 return {
220     WLXMLDocumentFromXML: function(xml, options) {
221         options = _.extend({wlxmlClasses: wlxmlClasses}, options);
222         return new WLXMLDocument(xml, options);
223     },
224
225     WLXMLElementNodeFromXML: function(xml) {
226         return this.WLXMLDocumentFromXML(xml).root;
227     }
228 };
229
230 });