wlxml: WLXMLElementNode.setMetaAttribute
[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     setMetaAttribute: function(key, value) {
53         this.setAttr('meta-'+key, value);
54     },
55     getOtherAttributes: function() {
56         var toret = {};
57         this.getAttrs().forEach(function(attr) {
58             if(attr.name !== 'class' && !isMetaAttribute(attr.name)) {
59                 toret[attr.name] = attr.value;
60             }
61         });
62         return toret;
63     },
64
65     _getXMLDOMToDump: function() {
66         var DOM = this._$.clone(true, true);
67
68         DOM.find('*').addBack().each(function() {
69             var el = $(this),
70                 parent = el.parent(),
71                 contents = parent.contents(),
72                 idx = contents.index(el),
73                 data = el.data();
74
75
76             var txt;
77
78             if(data[formatter_prefix+ 'orig_before']) {
79                 txt = idx > 0 && contents[idx-1].nodeType === Node.TEXT_NODE ? contents[idx-1] : null;
80                 if(txt && txt.data === data[formatter_prefix + 'orig_before_transformed']) {
81                     txt.data = data[formatter_prefix+ 'orig_before_original'];
82                 } else {
83                     el.before(data[formatter_prefix+ 'orig_before']);
84                 }
85             }
86             if(data[formatter_prefix+ 'orig_after']) {
87                 txt = idx < contents.length-1 && contents[idx+1].nodeType === Node.TEXT_NODE ? contents[idx+1] : null;
88                 if(txt && txt.data === data[formatter_prefix + 'orig_after_transformed']) {
89                     txt.data = data[formatter_prefix+ 'orig_after_original'];
90                 } else {
91                     el.after(data[formatter_prefix+ 'orig_after']);
92                 }
93             }
94             if(data[formatter_prefix+ 'orig_begin']) {
95                 el.prepend(data[formatter_prefix+ 'orig_begin']);
96             }
97             if(data[formatter_prefix+ 'orig_end']) {
98                 contents = el.contents();
99                 txt = (contents.length && contents[contents.length-1].nodeType === Node.TEXT_NODE) ? contents[contents.length-1] : null;
100                 if(txt && txt.data === data[formatter_prefix + 'orig_end_transformed']) {
101                     txt.data = data[formatter_prefix+ 'orig_end_original'];
102                 } else {
103                     el.append(data[formatter_prefix+ 'orig_end']);
104                 }
105             }
106         });
107
108         return DOM;
109     }
110 });
111
112
113
114
115
116 var WLXMLDocument = function(xml, options) {
117     smartxml.Document.call(this, xml);
118     this.options = options;
119 };
120
121 var formatter_prefix = '_wlxml_formatter_';
122
123 WLXMLDocument.prototype = Object.create(smartxml.Document.prototype);
124 $.extend(WLXMLDocument.prototype, {
125     ElementNodeFactory: WLXMLElementNode,
126
127     loadXML: function(xml) {
128         smartxml.Document.prototype.loadXML.call(this, xml, {silent: true});
129         $(this.dom).find(':not(iframe)').addBack().contents()
130             .filter(function() {return this.nodeType === Node.TEXT_NODE;})
131             .each(function() {
132                 var el = $(this),
133                     text = {original: el.text(), trimmed: $.trim(el.text())},
134                     elParent = el.parent(),
135                     hasSpanParent = elParent.prop('tagName') === 'SPAN',
136                     hasSpanBefore = el.prev().length && $(el.prev()).prop('tagName') === 'SPAN',
137                     hasSpanAfter = el.next().length && $(el.next()).prop('tagName') === 'SPAN';
138
139
140                 var addInfo = function(toAdd, where, transformed, original) {
141                     var parentContents = elParent.contents(),
142                         idx = parentContents.index(el[0]),
143                         prev = idx > 0 ? parentContents[idx-1] : null,
144                         next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
145                         target, key;
146
147                     if(where === 'above') {
148                         target = prev ? $(prev) : elParent;
149                         key = prev ? 'orig_after' : 'orig_begin';
150                     } else if(where === 'below') {
151                         target = next ? $(next) : elParent;
152                         key = next ? 'orig_before' : 'orig_end';
153                     } else { throw new Error();}
154
155                     target.data(formatter_prefix + key, toAdd);
156                     if(transformed !== undefined) {
157                         target.data(formatter_prefix + key + '_transformed', transformed);
158                     }
159                     if(original !== undefined) {
160                         target.data(formatter_prefix + key + '_original', original);
161                     }
162                 };
163
164                 text.transformed = text.trimmed;
165
166                 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
167                     var startSpace = /\s/g.test(text.original.substr(0,1)),
168                         endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
169                     text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '');
170                     text.transformed += text.trimmed;
171                     text.transformed += (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
172                 } else {
173                     if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1) {
174                         text.transformed = ' ';
175                     }
176                 }
177
178                 if(!text.transformed) {
179                     addInfo(text.original, 'below');
180                     el.remove();
181                     return true; // continue
182                 }
183
184                 if(text.transformed !== text.original) {
185                     // if(!text.trimmed) {
186                     //     addInfo(text.original, 'below');
187                     // } else {
188                         var startingMatch = text.original.match(/^\s+/g),
189                             endingMatch = text.original.match(/\s+$/g),
190                             startingWhiteSpace = startingMatch ? startingMatch[0] : null,
191                             endingWhiteSpace = endingMatch ? endingMatch[0] : null;
192
193                         if(endingWhiteSpace) {
194                             if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ') {
195                                 endingWhiteSpace = endingWhiteSpace.substr(1);
196                             }
197                             addInfo(endingWhiteSpace, 'below', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
198                         }
199
200                         if(startingWhiteSpace && text.trimmed) {
201                             if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ') {
202                                 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
203                             }
204                             addInfo(startingWhiteSpace, 'above', !text.trimmed ? text.transformed : undefined, !text.trimmed ? text.original : undefined);
205                         }
206                     //}
207                 }
208
209                 el.replaceWith(document.createTextNode(text.transformed));
210             });
211         this.trigger('contentSet');
212     }
213
214 });
215
216 var wlxmlClasses = {
217     'uri': {
218         attrs: {uri: {type: 'string'}}
219     }
220 };
221
222 return {
223     WLXMLDocumentFromXML: function(xml, options) {
224         options = _.extend({wlxmlClasses: wlxmlClasses}, options);
225         return new WLXMLDocument(xml, options);
226     },
227
228     WLXMLElementNodeFromXML: function(xml) {
229         return this.WLXMLDocumentFromXML(xml).root;
230     }
231 };
232
233 });