metamorphosis
Version:
A css variable management library that helps create and organize variables into easily configurable themes.
80 lines (79 loc) • 2.32 kB
JavaScript
import Color from "colorjs.io";
import colors from "tailwindcss/colors.js";
import { ControlVar } from "./ControlVar.js";
import { InterpolatedVars } from "./InterpolatedVars.js";
import { Theme } from "./Theme.js";
import { rem, oklch } from "./Units.js";
import { tailwindColorKeyNamer } from "./utils.js";
function unsafeColorToOklch(color) {
const c = color.oklch;
return { l: c.l ?? 0, c: c.c ?? 0, h: c.h ?? 0 };
}
const createColorJsIoInterpolator = (space) => ({ percent, state, start, end }) => {
const key = start.css + end.css;
if (state.key !== key) {
const c1 = new Color(start.css);
const c2 = new Color(end.css);
state.range = c1.range(c2, { space });
state.key = key;
}
const mixed = state.range(percent);
return unsafeColorToOklch(mixed);
};
const colorJsInterpolator = createColorJsIoInterpolator();
const spacing = new ControlVar(rem, { _: 0.25 });
const tailwindColorOpts = {
interpolator: colorJsInterpolator,
keyName: tailwindColorKeyNamer,
steps: 11
};
const createTailwindColor = (name, stops, opts = {}) => {
const controls = [];
for (const rawStop of stops) {
const stop = new Color(rawStop);
const control = new ControlVar(oklch, unsafeColorToOklch(stop));
controls.push(control);
}
return new InterpolatedVars(name, oklch, controls, { ...tailwindColorOpts, ...opts });
};
const bg = createTailwindColor("color-neutral", [
...Object.values(colors.neutral)
]);
const ok = createTailwindColor("color-ok", [
...Object.values(colors.green)
]);
const warning = createTailwindColor("color-warning", [
...Object.values(colors.yellow)
]);
const danger = createTailwindColor("color-danger", [
...Object.values(colors.red)
]);
const accent = createTailwindColor("color-accent", [
...Object.values(colors.blue)
]);
const background = new ControlVar(oklch, unsafeColorToOklch(new Color("rgb(99% 99% 99%)")));
const foreground = new ControlVar(oklch, unsafeColorToOklch(new Color("rgb(1% 1% 1%)")));
const baseTheme = new Theme({
"number-spacing": spacing,
bg,
"color-bg": background,
"color-fg": foreground,
ok,
warning,
danger,
accent
});
export {
accent,
background,
baseTheme,
bg,
createColorJsIoInterpolator,
createTailwindColor,
danger,
foreground,
ok,
spacing,
tailwindColorOpts,
warning
};