Roo/htmleditor/FilterWord.js
[roojs1] / Roo / htmleditor / FilterWord.js
1 /**
2  * @class Roo.htmleditor.FilterWord
3  * try and clean up all the mess that Word generates.
4  * 
5  * This is the 'nice version' - see 'Heavy' that white lists a very short list of elements, and multi-filters 
6  
7  * @constructor
8  * Run a new Span Filter
9  * @param {Object} config Configuration options
10  */
11
12 Roo.htmleditor.FilterWord = function(cfg)
13 {
14     // no need to apply config.
15     this.replaceDocBullets(cfg.node);
16     
17     this.replaceAname(cfg.node);
18     // this is disabled as the removal is done by other filters;
19    // this.walk(cfg.node);
20     
21     
22 }
23
24 Roo.extend(Roo.htmleditor.FilterWord, Roo.htmleditor.Filter,
25 {
26     tag: true,
27      
28     
29     /**
30      * Clean up MS wordisms...
31      */
32     replaceTag : function(node)
33     {
34          
35         // no idea what this does - span with text, replaceds with just text.
36         if(
37                 node.nodeName == 'SPAN' &&
38                 !node.hasAttributes() &&
39                 node.childNodes.length == 1 &&
40                 node.firstChild.nodeName == "#text"  
41         ) {
42             var textNode = node.firstChild;
43             node.removeChild(textNode);
44             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
45                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
46             }
47             node.parentNode.insertBefore(textNode, node);
48             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
49                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
50             }
51             
52             node.parentNode.removeChild(node);
53             return false; // dont do chidren - we have remove our node - so no need to do chdhilren?
54         }
55         
56    
57         
58         if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
59             node.parentNode.removeChild(node);
60             return false; // dont do chidlren
61         }
62         //Roo.log(node.tagName);
63         // remove - but keep children..
64         if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
65             //Roo.log('-- removed');
66             while (node.childNodes.length) {
67                 var cn = node.childNodes[0];
68                 node.removeChild(cn);
69                 node.parentNode.insertBefore(cn, node);
70                 // move node to parent - and clean it..
71                 if (cn.nodeType == 1) {
72                     this.replaceTag(cn);
73                 }
74                 
75             }
76             node.parentNode.removeChild(node);
77             /// no need to iterate chidlren = it's got none..
78             //this.iterateChildren(node, this.cleanWord);
79             return false; // no need to iterate children.
80         }
81         // clean styles
82         if (node.className.length) {
83             
84             var cn = node.className.split(/\W+/);
85             var cna = [];
86             Roo.each(cn, function(cls) {
87                 if (cls.match(/Mso[a-zA-Z]+/)) {
88                     return;
89                 }
90                 cna.push(cls);
91             });
92             node.className = cna.length ? cna.join(' ') : '';
93             if (!cna.length) {
94                 node.removeAttribute("class");
95             }
96         }
97         
98         if (node.hasAttribute("lang")) {
99             node.removeAttribute("lang");
100         }
101         
102         if (node.hasAttribute("style")) {
103             
104             var styles = node.getAttribute("style").split(";");
105             var nstyle = [];
106             Roo.each(styles, function(s) {
107                 if (!s.match(/:/)) {
108                     return;
109                 }
110                 var kv = s.split(":");
111                 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
112                     return;
113                 }
114                 // what ever is left... we allow.
115                 nstyle.push(s);
116             });
117             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
118             if (!nstyle.length) {
119                 node.removeAttribute('style');
120             }
121         }
122         return true; // do children
123         
124         
125         
126     },
127     
128     styleToObject: function(node)
129     {
130         var styles = (node.getAttribute("style") || '').split(";");
131         var ret = {};
132         Roo.each(styles, function(s) {
133             if (!s.match(/:/)) {
134                 return;
135             }
136             var kv = s.split(":");
137              
138             // what ever is left... we allow.
139             ret[kv[0].trim()] = kv[1];
140         });
141         return ret;
142     },
143     
144     
145     replaceAname : function (doc)
146     {
147         // replace all the a/name without..
148         var aa = Array.from(doc.getElementsByTagName('a'));
149         for (var i = 0; i  < aa.length; i++) {
150             var a = aa[i];
151             if (a.hasAttribute("name")) {
152                 a.removeAttribute("name");
153             }
154             if (a.hasAttribute("href")) {
155                 continue;
156             }
157             // reparent children.
158             this.removeNodeKeepChildren(a);
159             
160         }
161         
162         
163         
164     },
165
166     
167     
168     replaceDocBullets : function(doc)
169     {
170         // this is a bit odd - but it appears some indents use ql-indent-1
171          Roo.log(doc.innerHTML);
172         
173         var listpara = doc.getElementsByClassName('MsoListParagraphCxSpFirst');
174         for( var i = 0; i < listpara.length; i ++) {
175             listpara.item(i).className = "MsoListParagraph";
176         }
177         
178         listpara = doc.getElementsByClassName('MsoListParagraphCxSpMiddle');
179         for( var i = 0; i < listpara.length; i ++) {
180             listpara.item(i).className = "MsoListParagraph";
181         }
182         listpara = doc.getElementsByClassName('MsoListParagraphCxSpLast');
183         for( var i = 0; i < listpara.length; i ++) {
184             listpara.item(i).className = "MsoListParagraph";
185         }
186         
187         
188         // this is a bit hacky - we had one word document where h2 had a miso-list attribute.
189         var htwo = doc.getElementsByTagName('h2');
190         for( var i = 0; i < htwo.length; i ++) {
191             if (htwo.item(i).hasAttribute('style') && htwo.item(i).getAttribute('style').match(/mso-list:/)) {
192                 htwo.item(i).className = "MsoListParagraph";
193             }
194         }
195         listpara = doc.getElementsByClassName('MsoNormal');
196         while(listpara.length) {
197             if (listpara.item(0).hasAttribute('style') && listpara.item(0).getAttribute('style').match(/mso-list:/)) {
198                 listpara.item(0).className = "MsoListParagraph";
199             } else {
200                 listpara.item(0).className = "MsoNormalx";
201             }
202         }
203         listpara = doc.getElementsByClassName('ql-indent-1');
204         while(listpara.length) {
205             this.replaceDocBullet(listpara.item(0));
206         }
207         listpara = doc.getElementsByClassName('MsoListParagraph');
208         while(listpara.length) {
209             
210             this.replaceDocBullet(listpara.item(0));
211         }
212       
213     },
214     
215      
216     
217     replaceDocBullet : function(p)
218     {
219         // gather all the siblings.
220         var ns = p,
221             parent = p.parentNode,
222             doc = parent.ownerDocument,
223             items = [];
224             
225         var listtype = 'ul';   
226         while (ns) {
227             if (ns.nodeType != 1) {
228                 ns = ns.nextSibling;
229                 continue;
230             }
231             if (!ns.className.match(/(MsoListParagraph|ql-indent-1)/i)) {
232                 break;
233             }
234             var spans = ns.getElementsByTagName('span');
235             if (ns.hasAttribute('style') && ns.getAttribute('style').match(/mso-list/)) {
236                 items.push(ns);
237                 ns = ns.nextSibling;
238                 has_list = true;
239                 if (spans.length && spans[0].hasAttribute('style')) {
240                     var  style = this.styleToObject(spans[0]);
241                     if (typeof(style['font-family']) != 'undefined' && !style['font-family'].match(/Symbol/)) {
242                         listtype = 'ol';
243                     }
244                 }
245                 
246                 continue;
247             }
248             var spans = ns.getElementsByTagName('span');
249             if (!spans.length) {
250                 break;
251             }
252             var has_list  = false;
253             for(var i = 0; i < spans.length; i++) {
254                 if (spans[i].hasAttribute('style') && spans[i].getAttribute('style').match(/mso-list/)) {
255                     has_list = true;
256                     break;
257                 }
258             }
259             if (!has_list) {
260                 break;
261             }
262             items.push(ns);
263             ns = ns.nextSibling;
264             
265             
266         }
267         if (!items.length) {
268             ns.className = "";
269             return;
270         }
271         
272         var ul = parent.ownerDocument.createElement(listtype); // what about number lists...
273         parent.insertBefore(ul, p);
274         var lvl = 0;
275         var stack = [ ul ];
276         var last_li = false;
277         
278         var margin_to_depth = {};
279         max_margins = -1;
280         
281         items.forEach(function(n, ipos) {
282             //Roo.log("got innertHMLT=" + n.innerHTML);
283             
284             var spans = n.getElementsByTagName('span');
285             if (!spans.length) {
286                 //Roo.log("No spans found");
287                  
288                 parent.removeChild(n);
289                 
290                 
291                 return; // skip it...
292             }
293            
294                 
295             var num = 1;
296             var style = {};
297             for(var i = 0; i < spans.length; i++) {
298             
299                 style = this.styleToObject(spans[i]);
300                 if (typeof(style['mso-list']) == 'undefined') {
301                     continue;
302                 }
303                 if (listtype == 'ol') {
304                    num = spans[i].innerText.replace(/[^0-9]+]/g,'')  * 1;
305                 }
306                 spans[i].parentNode.removeChild(spans[i]); // remove the fake bullet.
307                 break;
308             }
309             //Roo.log("NOW GOT innertHMLT=" + n.innerHTML);
310             style = this.styleToObject(n); // mo-list is from the parent node.
311             if (typeof(style['mso-list']) == 'undefined') {
312                 //Roo.log("parent is missing level");
313                   
314                 parent.removeChild(n);
315                  
316                 return;
317             }
318             
319             var margin = style['margin-left'];
320             if (typeof(margin_to_depth[margin]) == 'undefined') {
321                 max_margins++;
322                 margin_to_depth[margin] = max_margins;
323             }
324             nlvl = margin_to_depth[margin] ;
325              
326             if (nlvl > lvl) {
327                 //new indent
328                 var nul = doc.createElement(listtype); // what about number lists...
329                 if (!last_li) {
330                     last_li = doc.createElement('li');
331                     stack[lvl].appendChild(last_li);
332                 }
333                 last_li.appendChild(nul);
334                 stack[nlvl] = nul;
335                 
336             }
337             lvl = nlvl;
338             
339             // not starting at 1..
340             if (!stack[nlvl].hasAttribute("start") && num > 1) {
341                 stack[nlvl].setAttribute("start", num);
342             }
343             
344             var nli = stack[nlvl].appendChild(doc.createElement('li'));
345             last_li = nli;
346             nli.innerHTML = n.innerHTML;
347             //Roo.log("innerHTML = " + n.innerHTML);
348             parent.removeChild(n);
349             
350              
351              
352             
353         },this);
354         
355         
356         
357         
358     }
359     
360     
361     
362 });