Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Last active December 19, 2019 21:04
Show Gist options
  • Save tomhodgins/79e38dc2ec49d7cb3a4f628fc6e4066a to your computer and use it in GitHub Desktop.
Save tomhodgins/79e38dc2ec49d7cb3a4f628fc6e4066a to your computer and use it in GitHub Desktop.
import * as parseCSS from 'https://tomhodgins.github.io/parse-css/index.js'
const css = parseCSS.parseAComponentValue(
Deno.args[1].trim()
)
if (
css.type === 'FUNCTION'
&& css.name.match(/rgba?/)
) {
const colors = css.value.filter(({tokenType}) =>
['PERCENTAGE', 'NUMBER'].some(term => term === tokenType)
)
console.log(
`#${colors.map(({tokenType, value}, index) => {
// Number in the first 3 colors
if (
index !== 3
&& tokenType === 'NUMBER'
) {
return Math.min(Math.max(0, value), 255)
}
// Number as the last color
if (
index === 3
&& tokenType === 'NUMBER'
) {
return (Math.min(Math.max(0, value), 1) * 255)
}
// Any color that's a percentage
if (tokenType === 'PERCENTAGE') {
return Math.min(Math.max(0, ((value / 100) * 255)), 255)
}
}).map(color => Math.round(color).toString(16).padStart(2, 0)).join('')}`
)
}
/* These are all equivalent to #808080 */
rgb(50% 50% 50% / .5)
rgb(50% 50% 50% / 50%)
rgb(128 128 128 / .5)
rgb(128 128 128 / 50%)
rgb(50%, 50%, 50%, .5)
rgb(50%, 50%, 50%, 50%)
rgb(128, 128, 128, .5)
rgb(128, 128, 128, 50%)
rgba(50% 50% 50% / .5)
rgba(50% 50% 50% / 50%)
rgba(128 128 128 / .5)
rgba(128 128 128 / 50%)
rgba(50%, 50%, 50%, .5)
rgba(50%, 50%, 50%, 50%)
rgba(128, 128, 128, .5)
rgba(128, 128, 128, 50%)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment