support empty tables wrapping images on word paste
[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     this.replaceImageTable(cfg.node);
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 = Array.from(doc.getElementsByClassName('MsoListParagraphCxSpFirst'));
174         for( var i = 0; i < listpara.length; i ++) {
175             listpara[i].className = "MsoListParagraph";
176         }
177         
178         listpara =  Array.from(doc.getElementsByClassName('MsoListParagraphCxSpMiddle'));
179         for( var i = 0; i < listpara.length; i ++) {
180             listpara[i].className = "MsoListParagraph";
181         }
182         listpara =  Array.from(doc.getElementsByClassName('MsoListParagraphCxSpLast'));
183         for( var i = 0; i < listpara.length; i ++) {
184             listpara[i].className = "MsoListParagraph";
185         }
186         listpara =  Array.from(doc.getElementsByClassName('ql-indent-1'));
187         for( var i = 0; i < listpara.length; i ++) {
188             listpara[i].className = "MsoListParagraph";
189         }
190         
191         // this is a bit hacky - we had one word document where h2 had a miso-list attribute.
192         var htwo =  Array.from(doc.getElementsByTagName('h2'));
193         for( var i = 0; i < htwo.length; i ++) {
194             if (htwo[i].hasAttribute('style') && htwo[i].getAttribute('style').match(/mso-list:/)) {
195                 htwo[i].className = "MsoListParagraph";
196             }
197         }
198         listpara =  Array.from(doc.getElementsByClassName('MsoNormal'));
199         for( var i = 0; i < listpara.length; i ++) {
200             if (listpara[i].hasAttribute('style') && listpara[i].getAttribute('style').match(/mso-list:/)) {
201                 listpara[i].className = "MsoListParagraph";
202             } else {
203                 listpara[i].className = "MsoNormalx";
204             }
205         }
206        
207         listpara = doc.getElementsByClassName('MsoListParagraph');
208         // Roo.log(doc.innerHTML);
209         
210         
211         
212         while(listpara.length) {
213             
214             this.replaceDocBullet(listpara.item(0));
215         }
216       
217     },
218     
219      
220     
221     replaceDocBullet : function(p)
222     {
223         // gather all the siblings.
224         var ns = p,
225             parent = p.parentNode,
226             doc = parent.ownerDocument,
227             items = [];
228          
229         //Roo.log("Parsing: " + p.innerText)    ;
230         var listtype = 'ul';   
231         while (ns) {
232             if (ns.nodeType != 1) {
233                 ns = ns.nextSibling;
234                 continue;
235             }
236             if (!ns.className.match(/(MsoListParagraph|ql-indent-1)/i)) {
237                 //Roo.log("Missing para r q1indent - got:" + ns.className);
238                 break;
239             }
240             var spans = ns.getElementsByTagName('span');
241             
242             if (ns.hasAttribute('style') && ns.getAttribute('style').match(/mso-list/)) {
243                 items.push(ns);
244                 ns = ns.nextSibling;
245                 has_list = true;
246                 if (!spans.length) {
247                     continue;
248                 }
249                 var ff = spans[0].style.fontFamily;
250                 if (!spans[0].hasAttribute('style') && spans.length  > 1 && spans[1].hasAttribute('style')) {
251                     
252                     ff = spans[1].style.fontFamily;
253                 }
254                     //var  style = this.styleToObject(spans[0]);
255                 //Roo.log("got font family: " + ff);
256                 if (typeof(ff) != 'undefined' && !ff.match(/Symbol/)) {
257                     listtype = 'ol';
258                 }
259                 
260                 continue;
261             }
262             //Roo.log("no mso-list?");
263             
264             var spans = ns.getElementsByTagName('span');
265             if (!spans.length) {
266                 break;
267             }
268             var has_list  = false;
269             for(var i = 0; i < spans.length; i++) {
270                 if (spans[i].hasAttribute('style') && spans[i].getAttribute('style').match(/mso-list/)) {
271                     has_list = true;
272                     break;
273                 }
274             }
275             if (!has_list) {
276                 break;
277             }
278             items.push(ns);
279             ns = ns.nextSibling;
280             
281             
282         }
283         if (!items.length) {
284             ns.className = "";
285             return;
286         }
287         
288         var ul = parent.ownerDocument.createElement(listtype); // what about number lists...
289         parent.insertBefore(ul, p);
290         var lvl = 0;
291         var stack = [ ul ];
292         var last_li = false;
293         
294         var margin_to_depth = {};
295         max_margins = -1;
296         
297         items.forEach(function(n, ipos) {
298             //Roo.log("got innertHMLT=" + n.innerHTML);
299             
300             var spans = n.getElementsByTagName('span');
301             if (!spans.length) {
302                 //Roo.log("No spans found");
303                  
304                 parent.removeChild(n);
305                 
306                 
307                 return; // skip it...
308             }
309            
310                 
311             var num = 1;
312             var style = {};
313             for(var i = 0; i < spans.length; i++) {
314             
315                 style = this.styleToObject(spans[i]);
316                 if (typeof(style['mso-list']) == 'undefined') {
317                     continue;
318                 }
319                 if (listtype == 'ol') {
320                    num = spans[i].innerText.replace(/[^0-9]+]/g,'')  * 1;
321                 }
322                 spans[i].parentNode.removeChild(spans[i]); // remove the fake bullet.
323                 break;
324             }
325             //Roo.log("NOW GOT innertHMLT=" + n.innerHTML);
326             style = this.styleToObject(n); // mo-list is from the parent node.
327             if (typeof(style['mso-list']) == 'undefined') {
328                 //Roo.log("parent is missing level");
329                   
330                 parent.removeChild(n);
331                  
332                 return;
333             }
334             
335             var margin = style['margin-left'];
336             if (typeof(margin_to_depth[margin]) == 'undefined') {
337                 max_margins++;
338                 margin_to_depth[margin] = max_margins;
339             }
340             nlvl = margin_to_depth[margin] ;
341              
342             if (nlvl > lvl) {
343                 //new indent
344                 var nul = doc.createElement(listtype); // what about number lists...
345                 if (!last_li) {
346                     last_li = doc.createElement('li');
347                     stack[lvl].appendChild(last_li);
348                 }
349                 last_li.appendChild(nul);
350                 stack[nlvl] = nul;
351                 
352             }
353             lvl = nlvl;
354             
355             // not starting at 1..
356             if (!stack[nlvl].hasAttribute("start") && listtype == "ol") {
357                 stack[nlvl].setAttribute("start", num);
358             }
359             
360             var nli = stack[nlvl].appendChild(doc.createElement('li'));
361             last_li = nli;
362             nli.innerHTML = n.innerHTML;
363             //Roo.log("innerHTML = " + n.innerHTML);
364             parent.removeChild(n);
365             
366              
367              
368             
369         },this);
370         
371         
372         
373         
374     },
375     
376     replaceImageTable : function(doc)
377     {
378          /*
379           <table cellpadding=0 cellspacing=0 align=left>
380   <tr>
381    <td width=423 height=0></td>
382   </tr>
383   <tr>
384    <td></td>
385    <td><img width=601 height=401
386    src="file:///C:/Users/Alan/AppData/Local/Temp/msohtmlclip1/01/clip_image002.jpg"
387    v:shapes="Picture_x0020_2"></td>
388   </tr>
389  </table>
390  */
391         var imgs = Array.from(doc.getElementsByTagName('img'));
392         Roo.each(imgs, function(img) {
393             var td = img.parentNode;
394             if (td.nodeName !=  'TD') {
395                 return;
396             }
397             var tr = td.parentNode;
398             if (tr.nodeName !=  'TR') {
399                 return;
400             }
401             var tbody = tr.parentNode;
402             if (tbody.nodeName !=  'TBODY') {
403                 return;
404             }
405             var table = tbody.parentNode;
406             if (table.nodeName !=  'TABLE') {
407                 return;
408             }
409             // first row..
410             
411             if (table.getElementsByTagName('tr').length != 2) {
412                 return;
413             }
414             if (table.getElementsByTagName('td').length != 3) {
415                 return;
416             }
417             if (table.innerText.trim() != '') {
418                 return;
419             }
420             var p = table.parentNode;
421             img.parentNode.removeChild(img);
422             p.insertBefore(img, table);
423             p.removeChild(table);
424             
425             
426             
427         });
428         
429       
430     }
431     
432 });