@thi.ng/color
Version:
Array-based color types, CSS parsing, conversions, transformations, declarative theme generation, gradients, presets
26 lines (25 loc) • 1 kB
JavaScript
import { isArray } from "@thi.ng/checks/is-array";
import { assert } from "@thi.ng/errors/assert";
import { unsupported } from "@thi.ng/errors/unsupported";
const CONVERSIONS = {};
const defConversions = (mode, spec) => {
for (let id in spec) {
const val = spec[id];
if (isArray(val)) {
const [a, b, c, d] = val;
spec[id] = val.length === 2 ? (out, src) => b(out, a(out, src)) : val.length === 3 ? (out, src) => c(out, b(out, a(out, src))) : (out, src) => d(out, c(out, b(out, a(out, src))));
}
}
CONVERSIONS[mode] = { ...CONVERSIONS[mode], ...spec };
};
const convert = (res, src, destMode, srcMode) => {
const spec = CONVERSIONS[destMode];
assert(!!spec, `no conversions available for ${destMode}`);
let $convert = spec[srcMode];
return $convert ? $convert(res, src) : CONVERSIONS.rgb[srcMode] ? spec.rgb(res, CONVERSIONS.rgb[srcMode]([], src)) : unsupported(`can't convert: ${srcMode} -> ${destMode}`);
};
export {
CONVERSIONS,
convert,
defConversions
};