1 | const cheerio = require('cheerio');
|
2 |
|
3 | const tableStyleAttrMap = {
|
4 | table: {
|
5 | float: 'align',
|
6 | 'background-color': 'bgcolor',
|
7 | width: 'width',
|
8 | height: 'height'
|
9 | },
|
10 | tr: {
|
11 | 'background-color': 'bgcolor',
|
12 | 'vertical-align': 'valign',
|
13 | 'text-align': 'align'
|
14 | },
|
15 | 'td,th': {
|
16 | 'background-color': 'bgcolor',
|
17 | width: 'width',
|
18 | height: 'height',
|
19 | 'vertical-align': 'valign',
|
20 | 'text-align': 'align',
|
21 | 'white-space': 'nowrap'
|
22 | },
|
23 | 'tbody,thead,tfoot': {
|
24 | 'vertical-align': 'valign',
|
25 | 'text-align': 'align'
|
26 | }
|
27 | };
|
28 |
|
29 | const attributesToRemovePxFrom = [ 'height', 'width' ];
|
30 |
|
31 | const applyStylesAsProps = ($el, styleToAttrMap) => {
|
32 | let style, styleVal, attributeValue;
|
33 |
|
34 | for (style in styleToAttrMap) {
|
35 | styleVal = $el.css(style);
|
36 |
|
37 | if (styleVal !== undefined) {
|
38 | if (attributesToRemovePxFrom.indexOf(style) > -1) {
|
39 | attributeValue = styleVal.replace(/px$/i, '');
|
40 | } else {
|
41 | attributeValue = styleVal;
|
42 | }
|
43 |
|
44 | $el.attr(styleToAttrMap[style], attributeValue);
|
45 | $el.css(style, '');
|
46 | }
|
47 | }
|
48 | };
|
49 |
|
50 | const batchApplyStylesAsProps = ($el, sel, $) => {
|
51 | $el.find(sel).each((i, childEl) => {
|
52 | applyStylesAsProps($(childEl), tableStyleAttrMap[sel]);
|
53 | });
|
54 | };
|
55 |
|
56 | cheerio.prototype.resetAttr = function (attribute) {
|
57 | if (!this.attr(attribute)) {
|
58 | this.attr(attribute, 0);
|
59 | }
|
60 | return this;
|
61 | };
|
62 |
|
63 | module.exports = (el, $) => {
|
64 | let selector;
|
65 | let $el = $(el);
|
66 |
|
67 | $el = $el.resetAttr('border')
|
68 | .resetAttr('cellpadding')
|
69 | .resetAttr('cellspacing');
|
70 |
|
71 | for (selector in tableStyleAttrMap) {
|
72 | if (selector === 'table') {
|
73 | applyStylesAsProps($el, tableStyleAttrMap.table);
|
74 | } else {
|
75 | batchApplyStylesAsProps($el, selector, $);
|
76 | }
|
77 | }
|
78 | };
|