Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Last active February 8, 2020 21:44
Show Gist options
  • Save tomhodgins/f6121e3a6b665c8955622e8892e364fb to your computer and use it in GitHub Desktop.
Save tomhodgins/f6121e3a6b665c8955622e8892e364fb to your computer and use it in GitHub Desktop.
@--custom-units {
--finger-widths: 50px;
--smidge: 5px;
}
div {
width: 10--finger-widths;
height: 40--finger-widths;
margin-top: 1--smidge;
}
div { width: 500px; height: 2000px; margin-top: 5px; }
// Run with Deno
// $ deno --allow-read custom-units.js input.css
import {
parseAStylesheet,
parseAListOfDeclarations,
parseAComponentValue,
parseAListOfComponentValues
} from 'https://tomhodgins.github.io/parse-css/index.js'
if (Deno.args.length < 2) {
console.error('Please provide a filename')
} else {
const filename = Deno.args.slice(1)[0]
const data = new TextDecoder('utf-8').decode(Deno.readFileSync(filename))
const units = {}
// Extract units from @--custom-units at-rules
parseAStylesheet(data).value.forEach(rule => {
if (rule.type === 'AT-RULE' && rule.name === '--custom-units') {
const declarations = parseAListOfDeclarations(
rule.value.value
.map(token => token.toSource())
.join('')
)
declarations.forEach(({name, value}) =>
units[name] = value.find(({tokenType}) => tokenType === 'DIMENSION')
)
}
})
// Replace custom unit tokens in stylesheet
let css = parseAListOfComponentValues(data).reduce(
(css, token, index, list) => {
function consumeToken(tok, list) {
if (
tok.tokenType === 'DIMENSION'
&& units.hasOwnProperty(tok.unit)
) {
list.value[list.value.indexOf(tok)] = parseAComponentValue(
`${tok.value * units[tok.unit].value}${units[tok.unit].unit}`
)
}
if (Array.isArray(tok.value)) {
tok.value.map(child => consumeToken(child, tok))
}
return tok
}
css += consumeToken(token, list).toSource()
return css
},
''
)
// Output all rules but @--custom-units
console.log(
parseAStylesheet(css).value.reduce(
(css, rule) => {
if (
rule.type === 'AT-RULE'
&& rule.name === '--custom-units'
) {
// do nothing
} else {
css += rule.toSource()
}
return css
},
''
)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment