UNPKG

@thi.ng/color-palettes

Version:

Collection of 200+ image based color themes & composable theme query filters

97 lines (96 loc) 2.73 kB
import { isNumber } from "@thi.ng/checks/is-number"; import { css } from "@thi.ng/color/css/css"; import { argb32 } from "@thi.ng/color/int/int"; import { lch } from "@thi.ng/color/lch/lch"; import { srgb } from "@thi.ng/color/srgb/srgb"; import { assert } from "@thi.ng/errors/assert"; import { U24 } from "@thi.ng/hex"; import { BINARY, NUM_THEMES } from "./binary.js"; import { compFilter } from "./filter.js"; const asCSS = (theme, reverse = false) => { let res; if (isNumber(theme)) { __ensureID(theme); theme *= 18; res = []; for (let i = 0; i < 6; i++, theme += 3) { res.push("#" + U24(__read(theme))); } } else { res = theme.map((x) => css(x)); } return reverse ? res.reverse() : res; }; const asInt = (theme, reverse = false) => { let res; if (isNumber(theme)) { __ensureID(theme); theme *= 18; res = []; for (let i = 0; i < 6; i++, theme += 3) { res.push(__read(theme)); } } else { res = theme.map((x) => argb32(x).deref()[0]); } return reverse ? res.reverse() : res; }; const asLCH = (theme, reverse = false) => { if (isNumber(theme)) { return asRGB(theme, reverse).map((x) => lch(x)); } const res = theme.map((x) => lch(x)); return reverse ? res.reverse() : res; }; const asRGB = (theme, reverse = false) => { let res; if (isNumber(theme)) { __ensureID(theme); theme *= 18; res = []; for (let i = 0; i < 6; i++, theme += 3) { res.push( srgb( BINARY[theme] / 255, BINARY[theme + 1] / 255, BINARY[theme + 2] / 255, 1 ) ); } } else { res = theme.map((x) => srgb(x)); } return reverse ? res.reverse() : res; }; const cssThemes = (...preds) => __themes(asCSS, preds); const intThemes = (...preds) => __themes(asInt, preds); const lchThemes = (...preds) => __themes(asLCH, preds); const rgbThemes = (...preds) => __themes(asRGB, preds); const themeIDs = (...preds) => __themes(asRGB, preds, true); function* __themes(fn, preds, idOnly = false) { if (preds.length && typeof preds[0] === "function") { const pred = compFilter(...preds); for (let i = 0; i < NUM_THEMES; i++) { const theme = fn(i); if (pred(theme)) yield idOnly ? i : theme; } } else if (preds.length) { for (const id of preds) yield idOnly ? id : fn(id); } else { for (let i = 0; i < NUM_THEMES; i++) yield idOnly ? i : fn(i); } } const __ensureID = (id) => assert(id >= 0 && id < NUM_THEMES, `invalid theme ID`); const __read = (i) => (4278190080 | BINARY[i] << 16 | BINARY[i + 1] << 8 | BINARY[i + 2]) >>> 0; export { asCSS, asInt, asLCH, asRGB, cssThemes, intThemes, lchThemes, rgbThemes, themeIDs };