daily-color 2.3.19 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -21,6 +21,32 @@ console.log("Today's color is:", getDailyColor());
21
21
  console.log("Another day's color is:", getDailyColor(new Date("2024-11-09")));
22
22
  ```
23
23
 
24
+ Colors that go with the day's color, worked out in OKLCH so they keep its lightness and strength (on gray days they get a little extra strength, so there's always some color):
25
+
26
+ ```javascript
27
+ import { getDailyPalette, getPalette } from "daily-color";
28
+
29
+ const palette = getDailyPalette(); // or getDailyPalette(new Date("2024-11-09"))
30
+ palette.color; // the day's color, e.g. "#7ad2f9"
31
+ palette.contrast; // "#000000" or "#ffffff", whichever reads better on it
32
+ palette.complementary; // "#ffb086"
33
+ palette.splitComplementary; // ["#ffabac", "#ecbc6f"]
34
+ palette.analogous; // ["#5edbdf", "#a2c7ff"]
35
+ palette.triadic; // ["#fba8d1", "#cbcb74"]
36
+ palette.tetradic; // ["#e4aef3", "#ffb086", "#a1d691"]
37
+
38
+ getPalette("#3fa2c1"); // the same, for any color
39
+ ```
40
+
41
+ Black or white text, whichever is easier to read on a color:
42
+
43
+ ```javascript
44
+ import { contrastColor } from "daily-color";
45
+
46
+ contrastColor("#7ad2f9"); // "#000000"
47
+ contrastColor("#1935a4"); // "#ffffff"
48
+ ```
49
+
24
50
  Directly loading the bundled JavaScript, for static projects not using NPM:
25
51
 
26
52
  ```html
@@ -32,10 +58,42 @@ Directly loading the bundled JavaScript, for static projects not using NPM:
32
58
  </script>
33
59
  ```
34
60
 
61
+ Or as a plain script, which sets `window.DailyColor`. Plain scripts in `<head>` run before the page is drawn, so the color is there from the very first frame. Pin a version from jsDelivr so it never changes under you:
62
+
63
+ ```html
64
+ <script src="https://cdn.jsdelivr.net/npm/daily-color@3/dist/daily-color.umd.js"></script>
65
+ <script>
66
+ document.documentElement.style.setProperty("--day", DailyColor.getDailyColor());
67
+ </script>
68
+ ```
69
+
70
+ ### Building your own colors
71
+
72
+ The color tools behind the palette are there too, for making a whole theme from the day's color:
73
+
74
+ ```javascript
75
+ import { contrastRatio, getDailyColor, oklch, readableOn, toOklch } from "daily-color";
76
+
77
+ const { l, c, h } = toOklch(getDailyColor()); // lightness 0–1, chroma 0–0.37, hue 0–360°
78
+ const pale = oklch(0.97, 0.02, h); // a background faintly tinted with the day's hue
79
+ const link = readableOn(getDailyColor(), pale); // darker or lighter until it reads at 4.5:1
80
+ contrastRatio(link, pale); // 4.5 or more
81
+
82
+ readableOn(getDailyColor(), "#ffffff", 7); // ask for more contrast
83
+ readableOn({ l: 0.9, c: 0.25, h }, "#ffffff"); // keep chroma that only fits once it's darker
84
+ ```
85
+
86
+ `oklch()` brings the chroma down when a color doesn't fit in sRGB, so its lightness and hue stay true. `readableOn()` keeps the hue and chroma and only moves the lightness: darker on a light background, lighter on a dark one.
87
+
35
88
  Using the CLI:
36
89
 
37
90
  ```bash
38
- dailycolor
91
+ dailycolor # today's color
92
+ dailycolor complementary # the color opposite it
93
+ dailycolor triadic analogous # several, labeled
94
+ dailycolor all --date 2027-01-01 # everything, for another day
95
+ dailycolor --help # all the options
96
+ dailycolor --version
39
97
  ```
40
98
 
41
99
  Just want to see today's color?
package/bin/dailycolor.js CHANGED
@@ -1,5 +1,92 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { getDailyColor } from "../index.js";
3
+ import { readFileSync } from "node:fs";
4
4
 
5
- console.log(getDailyColor());
5
+ import { getDailyPalette } from "../index.js";
6
+
7
+ const HELP = `Usage: dailycolor [colors...] [--date YYYY-MM-DD]
8
+
9
+ Prints today's color as a hex code. Name other colors to print the ones that
10
+ go with it instead.
11
+
12
+ Colors:
13
+ color the day's color (the default)
14
+ contrast black or white, whichever reads better on it
15
+ complementary opposite on the color wheel
16
+ split-complementary either side of the complement
17
+ analogous next door on the color wheel
18
+ triadic a third of the way round each way
19
+ tetradic a square round the color wheel
20
+ all all of the above, labeled
21
+
22
+ Options:
23
+ -d, --date <date> another day, like 2027-01-01
24
+ -h, --help show this help
25
+ -v, --version show the version number
26
+
27
+ Examples:
28
+ dailycolor
29
+ dailycolor complementary
30
+ dailycolor all --date 2027-01-01`;
31
+
32
+ // "split-complementary" on the command line, splitComplementary in the palette
33
+ const NAMES = {
34
+ color: "color",
35
+ contrast: "contrast",
36
+ complementary: "complementary",
37
+ "split-complementary": "splitComplementary",
38
+ analogous: "analogous",
39
+ triadic: "triadic",
40
+ tetradic: "tetradic",
41
+ };
42
+
43
+ function fail(message) {
44
+ console.error(`dailycolor: ${message}\nRun "dailycolor --help" to see what it can do.`);
45
+ process.exit(1);
46
+ }
47
+
48
+ const args = process.argv.slice(2);
49
+ const wanted = [];
50
+ let date = new Date();
51
+
52
+ for (let i = 0; i < args.length; i++) {
53
+ const arg = args[i];
54
+ if (arg === "-h" || arg === "--help") {
55
+ console.log(HELP);
56
+ process.exit(0);
57
+ } else if (arg === "-v" || arg === "--version") {
58
+ const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
59
+ console.log(version);
60
+ process.exit(0);
61
+ } else if (arg === "-d" || arg === "--date" || arg.startsWith("--date=")) {
62
+ const value = arg.startsWith("--date=") ? arg.slice(7) : args[++i];
63
+ date = parseDate(value);
64
+ } else if (arg === "all") {
65
+ wanted.push(...Object.keys(NAMES));
66
+ } else if (NAMES[arg]) {
67
+ wanted.push(arg);
68
+ } else {
69
+ fail(`there's no color called "${arg}"`);
70
+ }
71
+ }
72
+
73
+ // A day where you are, not UTC midnight
74
+ function parseDate(value) {
75
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value || "");
76
+ const day = m && new Date(+m[1], +m[2] - 1, +m[3]);
77
+ if (!day || day.getMonth() !== +m[2] - 1) fail(`"${value ?? ""}" isn't a date like 2027-01-01`);
78
+ return day;
79
+ }
80
+
81
+ const palette = getDailyPalette(date);
82
+ const show = (name) => [palette[NAMES[name]]].flat().join(" ");
83
+
84
+ if (wanted.length === 0) {
85
+ console.log(palette.color);
86
+ } else if (wanted.length === 1) {
87
+ console.log(show(wanted[0]));
88
+ } else {
89
+ // Several colors get a label each, lined up
90
+ const width = Math.max(...wanted.map((name) => name.length));
91
+ for (const name of new Set(wanted)) console.log(`${name.padEnd(width)} ${show(name)}`);
92
+ }
@@ -0,0 +1 @@
1
+ function t(t){const{L:r,C:o,H:a}=f(u(t)),e=Math.max(o,.11),c=t=>s(r,e,(a+t)%360);return{color:t.toLowerCase(),contrast:n(t),complementary:c(180),splitComplementary:[c(150),c(210)],analogous:[c(330),c(30)],triadic:[c(120),c(240)],tetradic:[c(90),c(180),c(270)]}}function n(t){const n=c(t);return(n+.05)/.05>=1.05/(n+.05)?"#000000":"#ffffff"}function r(t,n){const r=c(t),o=c(n);return(Math.max(r,o)+.05)/(Math.min(r,o)+.05)}function o(t,o,c=4.5){const{l:u,c:f,h:i}="string"==typeof t?a(t):t,h="#000000"===n(o)?-1:1;for(let n=0;n<=200;n++){const a=u+h*n*.005;if(a<0||a>1)break;const s=0===n&&"string"==typeof t?t.toLowerCase():e(a,f,i);if(r(s,o)>=c)return s}return h<0?"#000000":"#ffffff"}function a(t){const{L:n,C:r,H:o}=f(u(t));return{l:n,c:r,h:o}}function e(t,n,r){return s(Math.min(1,Math.max(0,t)),Math.max(0,n),(r%360+360)%360)}function c(t){const[n,r,o]=u(t);return.2126*n+.7152*r+.0722*o}function u(t){const n=parseInt(t.replace("#",""),16);return[n>>16&255,n>>8&255,255&n].map(t=>(t/=255)<=.04045?t/12.92:((t+.055)/1.055)**2.4)}function f([t,n,r]){const o=Math.cbrt(.4122214708*t+.5363325363*n+.0514459929*r),a=Math.cbrt(.2119034982*t+.6806995451*n+.1073969566*r),e=Math.cbrt(.0883024619*t+.2817188376*n+.6299787005*r),c=1.9779984951*o-2.428592205*a+.4505937099*e,u=.0259040371*o+.7827717662*a-.808675766*e;return{L:.2104542553*o+.793617785*a-.0040720468*e,C:Math.hypot(c,u),H:(180*Math.atan2(u,c)/Math.PI+360)%360}}function i(t,n,r){const o=n*Math.cos(r*Math.PI/180),a=n*Math.sin(r*Math.PI/180),e=(t+.3963377774*o+.2158037573*a)**3,c=(t-.1055613458*o-.0638541728*a)**3,u=(t-.0894841775*o-1.291485548*a)**3;return[4.0767416621*e-3.3077115913*c+.2309699292*u,-1.2684380046*e+2.6097574011*c-.3413193965*u,-.0041960863*e-.7034186147*c+1.707614701*u]}function h(t){return t.every(t=>t>=-1e-4&&t<=1.0001)}function s(t,n,r){let o=i(t,n,r);if(!h(o)){let a=0,e=n;for(let n=0;n<20;n++){const n=(a+e)/2;h(i(t,n,r))?a=n:e=n}o=i(t,a,r)}return function(t){return"#"+t.map(t=>{const n=(t=Math.min(1,Math.max(0,t)))<=.0031308?12.92*t:1.055*t**(1/2.4)-.055;return Math.round(255*n).toString(16).padStart(2,"0")}).join("")}(o)}function M(t=new Date){const n=function(t){const n=t.getDate(),r=t.getMonth()+1,o=t.getFullYear(),a=`${n}${n*o*r}${o}${r}${n}${o}${r}${n}`;let e=0;for(let t=0;t<a.length;t++)e=(e<<5)-e+a.charCodeAt(t),e|=0;return Math.abs(e)}(t),r=n>>8&255,o=255&n;return`#${(n>>16&255).toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`}function l(n=new Date){return t(M(n))}export{n as contrastColor,r as contrastRatio,M as getDailyColor,l as getDailyPalette,t as getPalette,e as oklch,o as readableOn,a as toOklch};
@@ -0,0 +1 @@
1
+ !function(t,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.DailyColor=n():t.DailyColor=n()}(globalThis,()=>(()=>{"use strict";const t={d:(n,e)=>{for(var o in e)t.o(e,o)&&!t.o(n,o)&&Object.defineProperty(n,o,{enumerable:!0,get:e[o]})},o:(t,n)=>Object.prototype.hasOwnProperty.call(t,n),r:t=>{Object.defineProperties(t,{[Symbol.toStringTag]:{value:"Module"},__esModule:{value:!0}})}};let n={};t.r(n),t.d(n,{contrastColor:()=>r,contrastRatio:()=>a,getDailyColor:()=>d,getDailyPalette:()=>m,getPalette:()=>o,oklch:()=>f,readableOn:()=>c,toOklch:()=>i});const e=.11;function o(t){const{L:n,C:o,H:a}=s(l(t)),c=Math.max(o,e),i=t=>M(n,c,(a+t)%360);return{color:t.toLowerCase(),contrast:r(t),complementary:i(180),splitComplementary:[i(150),i(210)],analogous:[i(330),i(30)],triadic:[i(120),i(240)],tetradic:[i(90),i(180),i(270)]}}function r(t){const n=u(t);return(n+.05)/.05>=1.05/(n+.05)?"#000000":"#ffffff"}function a(t,n){const e=u(t),o=u(n);return(Math.max(e,o)+.05)/(Math.min(e,o)+.05)}function c(t,n,e=4.5){const{l:o,c,h:u}="string"==typeof t?i(t):t,l="#000000"===r(n)?-1:1;for(let r=0;r<=200;r++){const i=o+l*r*.005;if(i<0||i>1)break;const s=0===r&&"string"==typeof t?t.toLowerCase():f(i,c,u);if(a(s,n)>=e)return s}return l<0?"#000000":"#ffffff"}function i(t){const{L:n,C:e,H:o}=s(l(t));return{l:n,c:e,h:o}}function f(t,n,e){return M(Math.min(1,Math.max(0,t)),Math.max(0,n),(e%360+360)%360)}function u(t){const[n,e,o]=l(t);return.2126*n+.7152*e+.0722*o}function l(t){const n=parseInt(t.replace("#",""),16);return[n>>16&255,n>>8&255,255&n].map(t=>(t/=255)<=.04045?t/12.92:((t+.055)/1.055)**2.4)}function s([t,n,e]){const o=Math.cbrt(.4122214708*t+.5363325363*n+.0514459929*e),r=Math.cbrt(.2119034982*t+.6806995451*n+.1073969566*e),a=Math.cbrt(.0883024619*t+.2817188376*n+.6299787005*e),c=1.9779984951*o-2.428592205*r+.4505937099*a,i=.0259040371*o+.7827717662*r-.808675766*a;return{L:.2104542553*o+.793617785*r-.0040720468*a,C:Math.hypot(c,i),H:(180*Math.atan2(i,c)/Math.PI+360)%360}}function h(t,n,e){const o=n*Math.cos(e*Math.PI/180),r=n*Math.sin(e*Math.PI/180),a=(t+.3963377774*o+.2158037573*r)**3,c=(t-.1055613458*o-.0638541728*r)**3,i=(t-.0894841775*o-1.291485548*r)**3;return[4.0767416621*a-3.3077115913*c+.2309699292*i,-1.2684380046*a+2.6097574011*c-.3413193965*i,-.0041960863*a-.7034186147*c+1.707614701*i]}function p(t){return t.every(t=>t>=-1e-4&&t<=1.0001)}function M(t,n,e){let o=h(t,n,e);if(!p(o)){let r=0,a=n;for(let n=0;n<20;n++){const n=(r+a)/2;p(h(t,n,e))?r=n:a=n}o=h(t,r,e)}return function(t){return"#"+t.map(t=>{const n=(t=Math.min(1,Math.max(0,t)))<=.0031308?12.92*t:1.055*t**(1/2.4)-.055;return Math.round(255*n).toString(16).padStart(2,"0")}).join("")}(o)}function d(t=new Date){const n=function(t){const n=t.getDate(),e=t.getMonth()+1,o=t.getFullYear(),r=`${n}${n*o*e}${o}${e}${n}${o}${e}${n}`;let a=0;for(let t=0;t<r.length;t++)a=(a<<5)-a+r.charCodeAt(t),a|=0;return Math.abs(a)}(t),e=n>>8&255,o=255&n;return`#${(n>>16&255).toString(16).padStart(2,"0")}${e.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`}function m(t=new Date){return o(d(t))}return n})());
package/index.d.ts CHANGED
@@ -1 +1,43 @@
1
+ export interface Palette {
2
+ /** The color itself */
3
+ color: string;
4
+ /** Black or white, whichever is easier to read on the color */
5
+ contrast: string;
6
+ /** Opposite on the color wheel (180°) */
7
+ complementary: string;
8
+ /** Either side of the complement (150° and 210°) */
9
+ splitComplementary: [string, string];
10
+ /** Next door on the color wheel (-30° and +30°) */
11
+ analogous: [string, string];
12
+ /** A third of the way round each way (120° and 240°) */
13
+ triadic: [string, string];
14
+ /** A square: 90°, 180° and 270° */
15
+ tetradic: [string, string, string];
16
+ }
17
+
1
18
  export function getDailyColor(date?: Date): string;
19
+ export function getDailyPalette(date?: Date): Palette;
20
+ export function getPalette(hex: string): Palette;
21
+ export function contrastColor(hex: string): string;
22
+
23
+ /** The WCAG contrast ratio between two colors, from 1 to 21 */
24
+ export function contrastRatio(a: string, b: string): number;
25
+
26
+ export interface Oklch {
27
+ /** Lightness, 0 to 1 */
28
+ l: number;
29
+ /** Chroma (strength), 0 to about 0.37 */
30
+ c: number;
31
+ /** Hue, 0 to 360° */
32
+ h: number;
33
+ }
34
+
35
+ /** A hex color in OKLCH */
36
+ export function toOklch(hex: string): Oklch;
37
+ /** The hex code for an OKLCH color, with chroma brought down to fit in sRGB */
38
+ export function oklch(l: number, c: number, h: number): string;
39
+ /**
40
+ * The color made darker or lighter until it reads on the background (4.5:1 by
41
+ * default), keeping its hue and chroma. Black or white if nothing is enough.
42
+ */
43
+ export function readableOn(color: string | Oklch, background: string, ratio?: number): string;
package/index.js CHANGED
@@ -1,3 +1,7 @@
1
+ import { getPalette } from "./palette.js";
2
+
3
+ export { contrastColor, contrastRatio, getPalette, oklch, readableOn, toOklch } from "./palette.js";
4
+
1
5
  export function getDailyColor(date = new Date()) {
2
6
  const hash = getSimpleHash(date);
3
7
 
@@ -8,6 +12,14 @@ export function getDailyColor(date = new Date()) {
8
12
  return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
9
13
  }
10
14
 
15
+ /**
16
+ * The day's color and the colors that go with it.
17
+ * @param {Date} [date] Defaults to today
18
+ */
19
+ export function getDailyPalette(date = new Date()) {
20
+ return getPalette(getDailyColor(date));
21
+ }
22
+
11
23
  function getSimpleHash(date) {
12
24
  const day = date.getDate();
13
25
  const month = date.getMonth() + 1; // getMonth() is zero-based
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "daily-color",
3
- "version": "2.3.19",
3
+ "version": "3.0.0",
4
4
  "description": "Provides a unique hex code each day",
5
5
  "keywords": [
6
6
  "color",
@@ -16,8 +16,10 @@
16
16
  "license": "ISC",
17
17
  "author": "Drue Wilding",
18
18
  "files": [
19
+ "dist",
19
20
  "index.d.ts",
20
- "index.js"
21
+ "index.js",
22
+ "palette.js"
21
23
  ],
22
24
  "main": "index.js",
23
25
  "bin": {
@@ -34,7 +36,8 @@
34
36
  "lint": "eslint --fix",
35
37
  "lint:check": "eslint",
36
38
  "package:lint": "npx npm-package-json-lint .",
37
- "test": "node test/index.js",
39
+ "prepublishOnly": "npm run webpack",
40
+ "test": "node --test test/",
38
41
  "webpack": "npx webpack"
39
42
  },
40
43
  "devDependencies": {
package/palette.js ADDED
@@ -0,0 +1,161 @@
1
+ // Colors that go with a color: its complement, triads and so on.
2
+ //
3
+ // The hues are turned in OKLCH, which matches how we see color better than
4
+ // HSL does, so the partners keep the color's lightness and strength. When a
5
+ // turned color doesn't fit in sRGB, its chroma comes down until it does.
6
+ //
7
+ // Grayish colors have hardly any chroma (strength) to keep, so their partners
8
+ // get at least MIN_CHROMA, and a gray day still has some color to go with it.
9
+ // A gray's hue is only a tiny tint, but it's always the same for that gray.
10
+
11
+ const MIN_CHROMA = 0.11;
12
+
13
+ /**
14
+ * A palette of colors that go with `hex`.
15
+ * @param {string} hex A color like "#3fa2c1"
16
+ */
17
+ export function getPalette(hex) {
18
+ const { L, C, H } = linToOklch(hexToLin(hex));
19
+ const strength = Math.max(C, MIN_CHROMA);
20
+ const turn = (degrees) => fromOklch(L, strength, (H + degrees) % 360);
21
+
22
+ return {
23
+ color: hex.toLowerCase(),
24
+ contrast: contrastColor(hex),
25
+ complementary: turn(180),
26
+ splitComplementary: [turn(150), turn(210)],
27
+ analogous: [turn(330), turn(30)],
28
+ triadic: [turn(120), turn(240)],
29
+ tetradic: [turn(90), turn(180), turn(270)],
30
+ };
31
+ }
32
+
33
+ /** Black or white, whichever is easier to read on `hex` */
34
+ export function contrastColor(hex) {
35
+ const l = luminance(hex);
36
+ return (l + 0.05) / 0.05 >= 1.05 / (l + 0.05) ? "#000000" : "#ffffff";
37
+ }
38
+
39
+ /** The WCAG contrast ratio between two colors, from 1 to 21 */
40
+ export function contrastRatio(a, b) {
41
+ const x = luminance(a);
42
+ const y = luminance(b);
43
+ return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05);
44
+ }
45
+
46
+ /**
47
+ * `color` made readable on `background`: the same hue and chroma, made darker
48
+ * (on a light background) or lighter (on a dark one) until the contrast ratio
49
+ * is at least `ratio`. A color that's already readable comes back as it is.
50
+ * If no lightness is enough, you get black or white.
51
+ *
52
+ * `color` can be a hex code, or { l, c, h } to keep a chroma that wouldn't fit
53
+ * in sRGB at its starting lightness but might once it's darker or lighter.
54
+ * @param {string | {l: number, c: number, h: number}} color
55
+ * @param {string} background
56
+ * @param {number} [ratio] Defaults to 4.5, the WCAG AA level for text
57
+ */
58
+ export function readableOn(color, background, ratio = 4.5) {
59
+ const { l, c, h } = typeof color === "string" ? toOklch(color) : color;
60
+ const dir = contrastColor(background) === "#000000" ? -1 : 1;
61
+ for (let step = 0; step <= 200; step++) {
62
+ const L = l + dir * step * 0.005;
63
+ if (L < 0 || L > 1) break;
64
+ const candidate = step === 0 && typeof color === "string" ? color.toLowerCase() : oklch(L, c, h);
65
+ if (contrastRatio(candidate, background) >= ratio) return candidate;
66
+ }
67
+ return dir < 0 ? "#000000" : "#ffffff";
68
+ }
69
+
70
+ /**
71
+ * A hex color's lightness (0 to 1), chroma (0 to about 0.37) and hue (0 to
72
+ * 360°) in OKLCH
73
+ */
74
+ export function toOklch(hex) {
75
+ const { L, C, H } = linToOklch(hexToLin(hex));
76
+ return { l: L, c: C, h: H };
77
+ }
78
+
79
+ /**
80
+ * The hex code for an OKLCH color. If it doesn't fit in sRGB, its chroma comes
81
+ * down until it does, so the lightness and hue stay true.
82
+ */
83
+ export function oklch(l, c, h) {
84
+ return fromOklch(Math.min(1, Math.max(0, l)), Math.max(0, c), ((h % 360) + 360) % 360);
85
+ }
86
+
87
+ function luminance(hex) {
88
+ const [r, g, b] = hexToLin(hex);
89
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
90
+ }
91
+
92
+ // ── sRGB <-> OKLCH ──────────────────────────────────────────────────────────
93
+
94
+ function hexToLin(hex) {
95
+ const n = parseInt(hex.replace("#", ""), 16);
96
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255].map((v) => {
97
+ v /= 255;
98
+ return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
99
+ });
100
+ }
101
+
102
+ function linToHex(rgb) {
103
+ return (
104
+ "#" +
105
+ rgb
106
+ .map((v) => {
107
+ v = Math.min(1, Math.max(0, v));
108
+ const s = v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055;
109
+ return Math.round(s * 255)
110
+ .toString(16)
111
+ .padStart(2, "0");
112
+ })
113
+ .join("")
114
+ );
115
+ }
116
+
117
+ function linToOklch([r, g, b]) {
118
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
119
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
120
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
121
+ const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
122
+ const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
123
+ return {
124
+ L: 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
125
+ C: Math.hypot(A, B),
126
+ H: ((Math.atan2(B, A) * 180) / Math.PI + 360) % 360,
127
+ };
128
+ }
129
+
130
+ function oklchToLin(L, C, H) {
131
+ const a = C * Math.cos((H * Math.PI) / 180);
132
+ const b = C * Math.sin((H * Math.PI) / 180);
133
+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
134
+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
135
+ const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
136
+ return [
137
+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
138
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
139
+ -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
140
+ ];
141
+ }
142
+
143
+ function inGamut(rgb) {
144
+ return rgb.every((v) => v >= -1e-4 && v <= 1 + 1e-4);
145
+ }
146
+
147
+ // OKLCH -> hex, bringing chroma down until the color fits in sRGB
148
+ function fromOklch(L, C, H) {
149
+ let rgb = oklchToLin(L, C, H);
150
+ if (!inGamut(rgb)) {
151
+ let lo = 0;
152
+ let hi = C;
153
+ for (let i = 0; i < 20; i++) {
154
+ const mid = (lo + hi) / 2;
155
+ if (inGamut(oklchToLin(L, mid, H))) lo = mid;
156
+ else hi = mid;
157
+ }
158
+ rgb = oklchToLin(L, lo, H);
159
+ }
160
+ return linToHex(rgb);
161
+ }