/
attributeToStyle.js
90 lines (68 loc) · 2.61 KB
/
attributeToStyle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const posthtml = require('posthtml')
const parseAttrs = require('posthtml-attrs-parser')
const {get, forEach, intersection, keys, isEmpty} = require('lodash')
module.exports = async (html, config = {}, direct = false) => {
const posthtmlOptions = get(config, 'build.posthtml.options', {})
const attributes = get(config, 'inlineCSS.attributeToStyle', false)
if (typeof attributes === 'boolean' && attributes) {
return posthtml([attributesToStyle()]).process(html, posthtmlOptions).then(result => result.html)
}
if (Array.isArray(attributes) && !isEmpty(attributes)) {
return posthtml([attributesToStyle({attributes})]).process(html, posthtmlOptions).then(result => result.html)
}
if (direct) {
return posthtml([
attributesToStyle({
attributes: Array.isArray(config) ? config : []
})
]).process(html, posthtmlOptions).then(result => result.html)
}
return html
}
const attributesToStyle = (options = {}) => tree => {
options.attributes = options.attributes || ['width', 'height', 'bgcolor', 'background', 'align', 'valign']
const process = node => {
const nodeAttributes = parseAttrs(node.attrs)
const matches = intersection(keys(nodeAttributes), options.attributes)
const nodeStyle = get(node.attrs, 'style')
const cssToInline = []
forEach(matches, attribute => {
let value = get(node.attrs, attribute)
switch (attribute) {
case 'bgcolor':
cssToInline.push(`background-color: ${value}`)
break
case 'background':
cssToInline.push(`background-image: url('${value}')`)
break
case 'width':
value = Number.parseInt(value, 10) + (value.match(/px|%/) || 'px')
cssToInline.push(`width: ${value}`)
break
case 'height':
value = Number.parseInt(value, 10) + (value.match(/px|%/) || 'px')
cssToInline.push(`height: ${value}`)
break
case 'align':
if (node.tag !== 'table') {
return cssToInline.push(`text-align: ${value}`)
}
if (['left', 'right'].includes(value)) {
cssToInline.push(`float: ${value}`)
}
if (value === 'center') {
cssToInline.push('margin-left: auto', 'margin-right: auto')
}
break
case 'valign':
cssToInline.push(`vertical-align: ${value}`)
break
// No default
}
})
nodeAttributes.style = nodeStyle ? `${nodeStyle} ${cssToInline.join('; ')}` : `${cssToInline.join('; ')}`
node.attrs = nodeAttributes.compose()
return node
}
return tree.walk(process)
}