Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make font destructuring more reliable #305

Open
bartveneman opened this issue Mar 5, 2023 · 1 comment
Open

Make font destructuring more reliable #305

bartveneman opened this issue Mar 5, 2023 · 1 comment
Labels
✨ enhancement New feature or request

Comments

@bartveneman
Copy link
Member

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,
	}
}
@bartveneman bartveneman added the ✨ enhancement New feature or request label Mar 5, 2023
@bartveneman
Copy link
Member Author

bartveneman commented Mar 7, 2023

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

@bartveneman bartveneman linked a pull request Jun 12, 2023 that will close this issue
1 task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
✨ enhancement New feature or request
Development

Successfully merging a pull request may close this issue.

1 participant