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