Last active
April 7, 2024 00:28
-
-
Save jfrancos/cbfe6aff32987ba35088045339f36cdd to your computer and use it in GitHub Desktop.
Tailwind: Calculate average oklch lightnesses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env npx tsx --experimental-network-imports --no-warnings | |
// If there was a tool for generating shades of colors meant to be used | |
// with Tailwind, it would make sense for the lightnesses of the | |
// generated colors to (by default at least) match the lightnesses of | |
// the standard colors defined by Tailwind, as much as possible | |
import { Script } from "vm"; | |
// @ts-expect-error Import module | |
import { oklch } from "https://cdn.skypack.dev/culori"; | |
const colorsUrl = | |
"https://raw.githubusercontent.com/tailwindlabs/tailwindcss/master/src/public/colors.js"; | |
const somethingWentWrong = -99999; | |
// For a better representation don't repeat similar colors | |
const selectedColors = ["red", "orange", "yellow", "green", "blue", "purple"]; | |
const fetchResult = await fetch(colorsUrl); | |
const fetchText = await fetchResult.text(); | |
// Aside from valid JSON, getting a string into an object is not straightforward | |
const objectString = fetchText.replace(/.*export default/s, "var colors ="); | |
const vmContext: { colors: Record<string, string> } = { colors: {} }; | |
new Script(objectString).runInNewContext(vmContext); | |
const { colors } = vmContext; | |
const lightnessesAverages = selectedColors | |
.map((item) => | |
Object.entries(colors[item]) | |
.sort(([a], [b]) => parseInt(a) - parseInt(b)) | |
.map(([, hex]) => oklch(hex)?.l ?? somethingWentWrong), | |
) // lightness[6][11] | |
.reduce<number[][]>( // zipped! | |
(acc, cur) => cur.map((item, i) => [...(acc[i] ?? []), item]), | |
[], | |
) // lightness[11][6] | |
.map((item) => item.reduce((acc, cur) => acc + cur, 0) / item.length); | |
console.log(lightnessesAverages); | |
/* | |
[ | |
0.9777836811575368, | |
0.9505873625296496, | |
0.9068045824232875, | |
0.8427497223494559, | |
0.760766801165325, | |
0.6849370761057076, | |
0.6057584182480391, | |
0.5206073196639761, | |
0.45005357983270206, | |
0.3962612717420128, | |
0.27470363588701435 | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment