/
removeInlineSizes.js
44 lines (33 loc) · 1.22 KB
/
removeInlineSizes.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
const posthtml = require('posthtml')
const {get, merge, isEmpty} = require('lodash')
const parseAttrs = require('posthtml-attrs-parser')
const {toStyleString} = require('../utils/helpers')
const defaultConfig = require('../generators/posthtml/defaultConfig')
module.exports = async (html, config = {}, direct = false) => {
const settings = direct ? config : get(config, 'inlineCSS.keepOnlyAttributeSizes', {})
if (!isEmpty(settings)) {
const posthtmlOptions = merge(defaultConfig, get(config, 'build.posthtml.options', {}))
return posthtml([removeInlineSizes(settings)]).process(html, posthtmlOptions).then(result => result.html)
}
return html
}
const removeInlineSizes = (mappings = {}) => tree => {
const process = node => {
const attrs = parseAttrs(node.attrs)
const tag = node.tag ? node.tag.toUpperCase() : ''
Object.entries(mappings).forEach(([attribute, tags]) => {
tags = Object.values(tags)
if (!tags.includes(tag)) {
return node
}
tags.forEach(() => {
if (get(node, 'attrs.style')) {
delete attrs.style[attribute]
node.attrs.style = toStyleString(attrs.style)
}
})
})
return node
}
return tree.walk(process)
}