css-analyzer
css-analyzer copied to clipboard
Make font destructuring more reliable
CSSTree has syntax matching which is really reliable and saves a lot of code. It might be a bit slower on the runtime, but that's probably worth it.
csstree.walk(ast, function (node) {
if (node.type == 'Declaration' && node.property == 'font') {
console.log(destructure(node, s))
}
})
function destructure(node, s) {
if (
node.value.children.size == 1 &&
node.value.children.first.type == 'Identifier'
) {
return { keyword: node.value.children.first.name }
}
let matchResult = csstree.lexer.matchProperty('font', node.value)
let line_height
let font_size
let font_family = [0, 0]
node.value.children.forEach(function (child) {
if (matchResult.isProperty(child, 'font-size')) {
font_size = s(child)
} else if (matchResult.isProperty(child, 'line-height')) {
line_height = s(child)
} else if (matchResult.isProperty(child, 'font-family')) {
if (!font_family[0]) {
font_family[0] = child.loc.start.offset
}
let end = child.loc.end.offset
let offset_end = font_family[1]
if (end > offset_end) {
font_family[1] = end
}
}
})
return {
font_family: css.substring(font_family[0], font_family[1]),
font_size,
line_height,
}
}
Build (before):
Build "@projectwallace/css-analyzer" to dist:
6.12 kB: analyzer.cjs.gz
5.48 kB: analyzer.cjs.br
5.61 kB: analyzer.modern.js.gz
5.05 kB: analyzer.modern.js.br
6.09 kB: analyzer.module.js.gz
5.47 kB: analyzer.module.js.br
6.21 kB: analyzer.umd.js.gz
5.58 kB: analyzer.umd.js.br
After:
Build "@projectwallace/css-analyzer" to dist:
5.95 kB: analyzer.cjs.gz
5.38 kB: analyzer.cjs.br
5.32 kB: analyzer.modern.js.gz
4.81 kB: analyzer.modern.js.br
5.81 kB: analyzer.module.js.gz
5.21 kB: analyzer.module.js.br
6.06 kB: analyzer.umd.js.gz
5.44 kB: analyzer.umd.js.br