@k8ordo/color-scheme 1.4.4 → 2.3.1

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
@@ -5,7 +5,7 @@ light, dark, or nothing, which follows the default (the system unless told
5
5
  otherwise) — lives in localStorage through `@k8ordo/state`; one rule resolves
6
6
  it against `prefers-color-scheme`; the result is the `dark` class on `<html>`,
7
7
  put there by an inline script before the first paint and kept there after
8
- hydration. One provider does all of that; a hook reads it. `@k8ordo/ui`'s
8
+ hydration. A script in `<head>` and a provider do that; a hook reads it. `@k8ordo/ui`'s
9
9
  tokens read the class; Tailwind's `dark:` does too once the stylesheet declares
10
10
  `@custom-variant dark (&:where(.dark, .dark *));` — `@k8ordo/ui/tailwind.css`
11
11
  already does.
@@ -31,7 +31,7 @@ pnpm add @k8ordo/color-scheme @k8ordo/state zod
31
31
 
32
32
  | Package | Version | Required | Needed for |
33
33
  | --------------- | ------- | -------- | ------------------------------------------ |
34
- | `@k8ordo/state` | ^1.4.4 | yes | where the preference lives (localStorage) |
34
+ | `@k8ordo/state` | ^2.3.1 | yes | where the preference lives (localStorage) |
35
35
  | `react` | ≥19.3.0 | yes | the provider and the hook |
36
36
  | `zod` | ^4.6.6 | yes | the one-field schema `@k8ordo/state` reads |
37
37
  | `typescript` | ≥7.0.0 | optional | the shipped type declarations |
@@ -41,16 +41,20 @@ pnpm add @k8ordo/color-scheme @k8ordo/state zod
41
41
 
42
42
  ## Quick Start
43
43
 
44
- The provider goes in the root layout, inside `<body>`, around everything. It
45
- renders the inline script itself, so nothing goes in `<head>`:
44
+ The script goes in the root layout's `<head>`, and the provider inside
45
+ `<body>`, around everything. `@k8ordo/framework` writes the script ahead of
46
+ every stylesheet, which it has to be for the first paint to be right:
46
47
 
47
48
  ```tsx
48
49
  // src/routes/layout.tsx — a Server Component
49
- import { ColorSchemeProvider } from '@k8ordo/color-scheme';
50
+ import { ColorSchemeProvider, ColorSchemeScript } from '@k8ordo/color-scheme';
50
51
 
51
52
  export default function RootLayout({ children }) {
52
53
  return (
53
54
  <html suppressHydrationWarning>
55
+ <head>
56
+ <ColorSchemeScript />
57
+ </head>
54
58
  <body>
55
59
  <ColorSchemeProvider>{children}</ColorSchemeProvider>
56
60
  </body>
@@ -82,8 +86,16 @@ export function SchemeSwitcher() {
82
86
  `scheme` is what is on screen; `preference` is what the visitor asked for
83
87
  (`'system'` when nothing is stored); `setPreference('system')` stores none, so
84
88
  the provider's default applies again. That default is the system unless told
85
- otherwise: `<ColorSchemeProvider defaultPreference="dark">` starts every
86
- visitor dark until they choose.
89
+ otherwise: `defaultPreference="dark"` on both `<ColorSchemeScript>` and
90
+ `<ColorSchemeProvider>` starts every visitor dark until they choose.
91
+
92
+ The browser's own UI — the address bar, the status bar — follows the same
93
+ scheme once the script is given the colours: it writes the
94
+ `<meta name="theme-color">` itself, and the provider keeps them in step.
95
+
96
+ ```tsx
97
+ <ColorSchemeScript themeColor={{ light: '#ffffff', dark: '#18181b' }} />
98
+ ```
87
99
 
88
100
  ## AI Agent Documentation
89
101
 
@@ -96,8 +108,9 @@ Point your agent at them once by pasting this into your project's `CLAUDE.md` /
96
108
  ```markdown
97
109
  Use `@k8ordo/color-scheme` for light and dark mode. Before touching the
98
110
  colour scheme, read `node_modules/@k8ordo/color-scheme/docs/GUIDE.md`. One
99
- `<ColorSchemeProvider>` wraps everything inside the root layout's `<body>`,
100
- with `suppressHydrationWarning` on `<html>`; components read and change the
111
+ `<ColorSchemeScript />` goes in the root layout's `<head>` and one
112
+ `<ColorSchemeProvider>` wraps everything inside its `<body>`, with
113
+ `suppressHydrationWarning` on `<html>`; components read and change the
101
114
  scheme through `useColorScheme()`. Never toggle the `dark` class, query
102
115
  `prefers-color-scheme` for the scheme, or write the stored preference
103
116
  yourself — the provider owns all three, and `setPreference` is the one way in.
package/dist/index.d.mts CHANGED
@@ -1,3 +1,4 @@
1
- import { ColorScheme, ColorSchemePreference, colorSchemeScriptHash, colorSchemeState } from "./scheme.mjs";
1
+ import { ColorScheme, ColorSchemePreference, ColorSchemeScriptOptions, colorSchemeScriptHash, colorSchemeState } from "./scheme.mjs";
2
2
  import { ColorSchemeProvider, ColorSchemeProviderProps, UseColorScheme, useColorScheme } from "./provider.mjs";
3
- export { type ColorScheme, type ColorSchemePreference, ColorSchemeProvider, type ColorSchemeProviderProps, type UseColorScheme, colorSchemeScriptHash, colorSchemeState, useColorScheme };
3
+ import { ColorSchemeScript, ColorSchemeScriptProps } from "./script.mjs";
4
+ export { type ColorScheme, type ColorSchemePreference, ColorSchemeProvider, type ColorSchemeProviderProps, ColorSchemeScript, type ColorSchemeScriptOptions, type ColorSchemeScriptProps, type UseColorScheme, colorSchemeScriptHash, colorSchemeState, useColorScheme };
package/dist/index.mjs CHANGED
@@ -1,3 +1,4 @@
1
1
  import { colorSchemeScriptHash, colorSchemeState } from "./scheme.mjs";
2
2
  import { ColorSchemeProvider, useColorScheme } from "./provider.mjs";
3
- export { ColorSchemeProvider, colorSchemeScriptHash, colorSchemeState, useColorScheme };
3
+ import { ColorSchemeScript } from "./script.mjs";
4
+ export { ColorSchemeProvider, ColorSchemeScript, colorSchemeScriptHash, colorSchemeState, useColorScheme };
@@ -18,24 +18,19 @@ export type ColorSchemeProviderProps = {
18
18
  /**
19
19
  * What applies while the visitor has chosen nothing. `'system'` follows
20
20
  * `prefers-color-scheme`; a scheme starts every visitor there until they
21
- * choose.
21
+ * choose. Give `ColorSchemeScript` the same.
22
22
  */
23
23
  readonly defaultPreference?: ColorSchemePreference;
24
- /**
25
- * The nonce the page's `Content-Security-Policy` lets inline scripts run
26
- * with, put on the inline script — under `@k8ordo/framework`'s server mode,
27
- * `nonce()` from `@k8ordo/framework/server`. A policy that allows the script by its hash
28
- * instead names `colorSchemeScriptHash()`.
29
- */
30
- readonly nonce?: string;
31
24
  readonly children: ReactNode;
32
25
  };
33
26
  /**
34
- * The one place the scheme is decided and written. Goes in the root
35
- * layout, inside `<body>`, around everything: it renders the inline script
36
- * that puts the class on `<html>` before the first paint, keeps the class
37
- * in step afterwards, and hands `useColorScheme` what it reads.
27
+ * The one place the scheme is decided and written after the first paint.
28
+ * Goes in the root layout, inside `<body>`, around everything: it keeps the
29
+ * class on `<html>` — and the theme-color `<meta>` `ColorSchemeScript`
30
+ * wrote, when it was given the colours — in step with the stored preference
31
+ * and the system, and hands `useColorScheme` what it reads. What the page
32
+ * shows before the first paint is `ColorSchemeScript`'s, in `<head>`.
38
33
  */
39
- export declare function ColorSchemeProvider({ defaultPreference, nonce, children }: ColorSchemeProviderProps): ReactNode;
34
+ export declare function ColorSchemeProvider({ defaultPreference, children }: ColorSchemeProviderProps): ReactNode;
40
35
  /** The visitor's colour scheme and a way to change it, from the provider above. */
41
36
  export declare function useColorScheme(): UseColorScheme;
package/dist/provider.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  "use client";
2
- import { DARK_CLASS, DARK_QUERY, colorSchemeState, resolve, scriptFor } from "./scheme.mjs";
2
+ import { DARK_CLASS, DARK_QUERY, THEME_COLOR_ATTRIBUTE, colorSchemeState, pinnedScheme, resolve, themeColorMedia } from "./scheme.mjs";
3
3
  import { useAppState } from "@k8ordo/state";
4
4
  import { createContext, use, useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
5
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
+ import { jsx } from "react/jsx-runtime";
6
6
  // src/provider.tsx
7
7
  const ColorSchemeContext = createContext(null);
8
8
  const subscribeSystem = (onChange) => {
@@ -17,20 +17,30 @@ const serverSystemDark = () => false;
17
17
  const subscribeNever = () => () => {};
18
18
  const useReadsStore = () => useSyncExternalStore(subscribeNever, () => true, () => false);
19
19
  /**
20
- * The one place the scheme is decided and written. Goes in the root
21
- * layout, inside `<body>`, around everything: it renders the inline script
22
- * that puts the class on `<html>` before the first paint, keeps the class
23
- * in step afterwards, and hands `useColorScheme` what it reads.
20
+ * The one place the scheme is decided and written after the first paint.
21
+ * Goes in the root layout, inside `<body>`, around everything: it keeps the
22
+ * class on `<html>` — and the theme-color `<meta>` `ColorSchemeScript`
23
+ * wrote, when it was given the colours — in step with the stored preference
24
+ * and the system, and hands `useColorScheme` what it reads. What the page
25
+ * shows before the first paint is `ColorSchemeScript`'s, in `<head>`.
24
26
  */
25
- function ColorSchemeProvider({ defaultPreference = "system", nonce, children }) {
27
+ function ColorSchemeProvider({ defaultPreference = "system", children }) {
26
28
  const [{ preference }, update] = useAppState(colorSchemeState);
27
29
  const systemDark = useSyncExternalStore(subscribeSystem, readSystemDark, serverSystemDark);
28
30
  const scheme = resolve(preference, defaultPreference, systemDark);
31
+ const pinned = pinnedScheme(preference, defaultPreference);
29
32
  const readsStore = useReadsStore();
30
33
  useEffect(() => {
31
34
  if (!readsStore) return;
32
35
  document.documentElement.classList.toggle(DARK_CLASS, scheme === "dark");
33
36
  }, [readsStore, scheme]);
37
+ useEffect(() => {
38
+ if (!readsStore) return;
39
+ for (const each of ["light", "dark"]) {
40
+ const meta = document.querySelector(`meta[${THEME_COLOR_ATTRIBUTE}="${each}"]`);
41
+ if (meta !== null) meta.media = themeColorMedia(each, pinned);
42
+ }
43
+ }, [readsStore, pinned]);
34
44
  const setPreference = useCallback((next) => {
35
45
  update({ preference: next === "system" ? void 0 : next });
36
46
  }, [update]);
@@ -43,13 +53,10 @@ function ColorSchemeProvider({ defaultPreference = "system", nonce, children })
43
53
  preference,
44
54
  setPreference
45
55
  ]);
46
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("script", {
47
- nonce,
48
- children: scriptFor(defaultPreference)
49
- }), /* @__PURE__ */ jsx(ColorSchemeContext, {
56
+ return /* @__PURE__ */ jsx(ColorSchemeContext, {
50
57
  value,
51
58
  children
52
- })] });
59
+ });
53
60
  }
54
61
  /** The visitor's colour scheme and a way to change it, from the provider above. */
55
62
  function useColorScheme() {
package/dist/scheme.d.mts CHANGED
@@ -19,29 +19,65 @@ export declare const colorSchemeState: import("@k8ordo/state").LocalState<z.ZodM
19
19
  }>>;
20
20
  }, z.core.$strip>>;
21
21
  /** The media query the system answers through. */
22
- export declare const DARK_QUERY = "(prefers-color-scheme: dark)";
22
+ export declare const DARK_QUERY: string;
23
23
  /**
24
24
  * The class `@k8ordo/ui` reads on `<html>` (and Tailwind's `dark:` under a
25
25
  * class-based `@custom-variant dark`).
26
26
  */
27
27
  export declare const DARK_CLASS = "dark";
28
28
  /**
29
- * The one rule: what the visitor chose wins, then what the provider was
30
- * told to start from, and `system` — the default's default — asks the
31
- * system.
29
+ * The attribute that marks the theme-color `<meta>` the inline script
30
+ * writes, naming the scheme its colour is for.
31
+ */
32
+ export declare const THEME_COLOR_ATTRIBUTE = "data-color-scheme";
33
+ /**
34
+ * The scheme the system has no say in: what the visitor chose, else the
35
+ * default the provider was told to start from — `undefined` while that
36
+ * default is `system`, the default's default, and the visitor never chose.
32
37
  */
38
+ export declare const pinnedScheme: (preference: ColorScheme | undefined, defaultPreference: ColorSchemePreference) => ColorScheme | undefined;
39
+ /** The one rule: the pinned scheme wins, and nothing pinned asks the system. */
33
40
  export declare const resolve: (preference: ColorScheme | undefined, defaultPreference: ColorSchemePreference, systemDark: boolean) => ColorScheme;
34
41
  /**
35
- * The inline script the provider renders before its children: the rule
36
- * above, run before the first paint. The schema does not run there, so the
37
- * stored value is checked by hand and anything else reads as nothing
38
- * chosen — the same salvage the store applies.
42
+ * The `media` of the theme-color `<meta>` for `scheme`. While nothing is
43
+ * pinned it is that scheme's `prefers-color-scheme`, so the browser follows
44
+ * the system on its own, as it changes; once a scheme is pinned, the pinned
45
+ * one applies everywhere and the other nowhere.
46
+ */
47
+ export declare const themeColorMedia: (scheme: ColorScheme, pinned: ColorScheme | undefined) => string;
48
+ /**
49
+ * What the inline script carries — the props `ColorSchemeScript` takes, its
50
+ * nonce aside — and so what its hash depends on.
51
+ */
52
+ export type ColorSchemeScriptOptions = {
53
+ /**
54
+ * The `defaultPreference` the provider is given. The script applies it
55
+ * before the first paint to a visitor who has chosen nothing, so the two
56
+ * have to say the same.
57
+ */
58
+ readonly defaultPreference?: ColorSchemePreference;
59
+ /**
60
+ * The colour the browser paints its own UI in — the address bar, the
61
+ * status bar — for each scheme; the page's background, usually. The
62
+ * script writes it as `<meta name="theme-color">`, one for each scheme,
63
+ * and the provider keeps them in step with the scheme on screen.
64
+ */
65
+ readonly themeColor?: {
66
+ readonly light: string;
67
+ readonly dark: string;
68
+ };
69
+ };
70
+ /**
71
+ * The inline script `ColorSchemeScript` renders: the rule above, run before
72
+ * the first paint. The schema does not run there, so the stored value is
73
+ * checked by hand and anything else reads as nothing chosen — the same
74
+ * salvage the store applies.
39
75
  */
40
- export declare const scriptFor: (defaultPreference: ColorSchemePreference) => string;
76
+ export declare const scriptFor: ({ defaultPreference, themeColor }?: ColorSchemeScriptOptions) => string;
41
77
  /**
42
78
  * The inline script's hash as a CSP source, `'sha256-…'`, for a policy that
43
79
  * allows it by what it is rather than by a nonce — the static mode's `csp`
44
- * option, or a header that names no nonce. Give it the default the provider
45
- * is given: the script carries it.
80
+ * option, or a header that names no nonce. Give it what `ColorSchemeScript`
81
+ * is given, its nonce aside: the script carries it.
46
82
  */
47
- export declare const colorSchemeScriptHash: (defaultPreference?: ColorSchemePreference) => Promise<string>;
83
+ export declare const colorSchemeScriptHash: (options?: ColorSchemeScriptOptions) => Promise<string>;
package/dist/scheme.mjs CHANGED
@@ -8,36 +8,60 @@ import * as z from "zod/mini";
8
8
  * their first visit.
9
9
  */
10
10
  const colorSchemeState = defineLocalState("color-scheme", z.object({ preference: z.optional(z.enum(["light", "dark"])) }));
11
+ const systemQuery = (scheme) => `(prefers-color-scheme: ${scheme})`;
11
12
  /** The media query the system answers through. */
12
- const DARK_QUERY = "(prefers-color-scheme: dark)";
13
+ const DARK_QUERY = systemQuery("dark");
13
14
  /**
14
15
  * The class `@k8ordo/ui` reads on `<html>` (and Tailwind's `dark:` under a
15
16
  * class-based `@custom-variant dark`).
16
17
  */
17
18
  const DARK_CLASS = "dark";
18
19
  /**
19
- * The one rule: what the visitor chose wins, then what the provider was
20
- * told to start from, and `system` — the default's default — asks the
21
- * system.
20
+ * The attribute that marks the theme-color `<meta>` the inline script
21
+ * writes, naming the scheme its colour is for.
22
22
  */
23
- const resolve = (preference, defaultPreference, systemDark) => {
24
- return preference ?? (defaultPreference === "system" ? void 0 : defaultPreference) ?? (systemDark ? "dark" : "light");
23
+ const THEME_COLOR_ATTRIBUTE = "data-color-scheme";
24
+ /**
25
+ * The scheme the system has no say in: what the visitor chose, else the
26
+ * default the provider was told to start from — `undefined` while that
27
+ * default is `system`, the default's default, and the visitor never chose.
28
+ */
29
+ const pinnedScheme = (preference, defaultPreference) => preference ?? (defaultPreference === "system" ? void 0 : defaultPreference);
30
+ /** The one rule: the pinned scheme wins, and nothing pinned asks the system. */
31
+ const resolve = (preference, defaultPreference, systemDark) => pinnedScheme(preference, defaultPreference) ?? (systemDark ? "dark" : "light");
32
+ /**
33
+ * The `media` of the theme-color `<meta>` for `scheme`. While nothing is
34
+ * pinned it is that scheme's `prefers-color-scheme`, so the browser follows
35
+ * the system on its own, as it changes; once a scheme is pinned, the pinned
36
+ * one applies everywhere and the other nowhere.
37
+ */
38
+ const themeColorMedia = (scheme, pinned) => {
39
+ if (pinned === void 0) return systemQuery(scheme);
40
+ return pinned === scheme ? "all" : "not all";
25
41
  };
26
42
  /**
27
- * The inline script the provider renders before its children: the rule
28
- * above, run before the first paint. The schema does not run there, so the
29
- * stored value is checked by hand and anything else reads as nothing
30
- * chosen — the same salvage the store applies.
43
+ * The inline script `ColorSchemeScript` renders: the rule above, run before
44
+ * the first paint. The schema does not run there, so the stored value is
45
+ * checked by hand and anything else reads as nothing chosen — the same
46
+ * salvage the store applies.
31
47
  */
32
- const scriptFor = (defaultPreference) => `(()=>{const s=${colorSchemeState.inlineRead()};const v=s&&s.preference;const p=v==="dark"||v==="light"?v:${JSON.stringify(defaultPreference)};if(p==="dark"||(p!=="light"&&matchMedia(${JSON.stringify(DARK_QUERY)}).matches))document.documentElement.classList.add(${JSON.stringify(DARK_CLASS)})})()`;
48
+ const scriptFor = ({ defaultPreference = "system", themeColor } = {}) => {
49
+ const scheme = `const s=${colorSchemeState.inlineRead()};const v=s&&s.preference;const p=v==="dark"||v==="light"?v:${JSON.stringify(defaultPreference)};if(p==="dark"||(p!=="light"&&matchMedia(${JSON.stringify(DARK_QUERY)}).matches))document.documentElement.classList.add(${JSON.stringify(DARK_CLASS)})`;
50
+ if (themeColor === void 0) return `(()=>{${scheme}})()`;
51
+ return `(()=>{${scheme};for(const[k,c,q]of ${JSON.stringify(["light", "dark"].map((each) => [
52
+ each,
53
+ themeColor[each],
54
+ systemQuery(each)
55
+ ]))}){const m=document.createElement("meta");m.name="theme-color";m.content=c;m.setAttribute(${JSON.stringify(THEME_COLOR_ATTRIBUTE)},k);m.media=p==="system"?q:p===k?"all":"not all";document.head.append(m)}})()`;
56
+ };
33
57
  /**
34
58
  * The inline script's hash as a CSP source, `'sha256-…'`, for a policy that
35
59
  * allows it by what it is rather than by a nonce — the static mode's `csp`
36
- * option, or a header that names no nonce. Give it the default the provider
37
- * is given: the script carries it.
60
+ * option, or a header that names no nonce. Give it what `ColorSchemeScript`
61
+ * is given, its nonce aside: the script carries it.
38
62
  */
39
- const colorSchemeScriptHash = async (defaultPreference = "system") => {
40
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(scriptFor(defaultPreference)));
63
+ const colorSchemeScriptHash = async (options = {}) => {
64
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(scriptFor(options)));
41
65
  return `'sha256-${btoa(String.fromCodePoint(...new Uint8Array(digest)))}'`;
42
66
  };
43
- export { DARK_CLASS, DARK_QUERY, colorSchemeScriptHash, colorSchemeState, resolve, scriptFor };
67
+ export { DARK_CLASS, DARK_QUERY, THEME_COLOR_ATTRIBUTE, colorSchemeScriptHash, colorSchemeState, pinnedScheme, resolve, scriptFor, themeColorMedia };
@@ -0,0 +1,19 @@
1
+ import { ColorSchemeScriptOptions } from "./scheme.mjs";
2
+ import { ReactNode } from "react";
3
+ export type ColorSchemeScriptProps = ColorSchemeScriptOptions & {
4
+ /**
5
+ * The nonce the page's `Content-Security-Policy` lets inline scripts run
6
+ * with — under `@k8ordo/framework`'s server mode, `nonce()` from
7
+ * `@k8ordo/framework/server`. A policy that allows the script by its hash
8
+ * instead names `colorSchemeScriptHash()`.
9
+ */
10
+ readonly nonce?: string;
11
+ };
12
+ /**
13
+ * The inline script that puts the class on `<html>` before the first paint,
14
+ * and the theme-color `<meta>` in `<head>` when it is given the colours.
15
+ * Goes in the root layout's `<head>`, which `@k8ordo/framework` writes ahead
16
+ * of every stylesheet: a script after a stylesheet waits for it to load, and
17
+ * the browser may paint the page in the meantime.
18
+ */
19
+ export declare function ColorSchemeScript({ nonce, ...options }: ColorSchemeScriptProps): ReactNode;
@@ -0,0 +1,17 @@
1
+ import { scriptFor } from "./scheme.mjs";
2
+ import { jsx } from "react/jsx-runtime";
3
+ // src/script.tsx
4
+ /**
5
+ * The inline script that puts the class on `<html>` before the first paint,
6
+ * and the theme-color `<meta>` in `<head>` when it is given the colours.
7
+ * Goes in the root layout's `<head>`, which `@k8ordo/framework` writes ahead
8
+ * of every stylesheet: a script after a stylesheet waits for it to load, and
9
+ * the browser may paint the page in the meantime.
10
+ */
11
+ function ColorSchemeScript({ nonce, ...options }) {
12
+ return /* @__PURE__ */ jsx("script", {
13
+ ...nonce === void 0 ? {} : { nonce },
14
+ children: scriptFor(options)
15
+ });
16
+ }
17
+ export { ColorSchemeScript };
package/docs/GUIDE.md CHANGED
@@ -8,9 +8,12 @@ the first in localStorage (through `@k8ordo/state`), reads the second from
8
8
  `prefers-color-scheme`, and resolves both into the third — the `dark` class
9
9
  on `<html>`, which `@k8ordo/ui`'s tokens read, and Tailwind's `dark:` too
10
10
  once the stylesheet declares `@custom-variant dark (&:where(.dark, .dark *));`
11
- (`@k8ordo/ui/tailwind.css` already does). One provider does all of it: it
12
- renders the inline script that puts the class there before the first paint,
13
- keeps it right after hydration, and hands a hook what it reads.
11
+ (`@k8ordo/ui/tailwind.css` already does). Two pieces do it:
12
+ `<ColorSchemeScript>`, an inline script in `<head>`, puts the class there
13
+ before the first paint, and `<ColorSchemeProvider>` keeps it right after
14
+ hydration and hands a hook what it reads. Given the application's colours,
15
+ the two keep the browser's own UI — `<meta name="theme-color">` — on the
16
+ same scheme.
14
17
 
15
18
  Like every k8ordo package it assumes React 19 and Server Components, uses
16
19
  only what has reached Baseline newly available, and ships no polyfills or
@@ -19,8 +22,10 @@ legacy fallbacks.
19
22
  ## What it does not own
20
23
 
21
24
  - **The colours.** Which colour `dark` means is the stylesheet's business —
22
- `@k8ordo/ui`'s tokens, or any other that reads the class. So is the CSS
23
- `color-scheme` property (form controls, scrollbars): this package never
25
+ `@k8ordo/ui`'s tokens, or any other that reads the class — and the
26
+ browser's own UI is painted in colours the application gives (see "The
27
+ browser's own UI"). The CSS `color-scheme` property (form controls,
28
+ scrollbars) is the stylesheet's too: this package never
24
29
  sets it; `@k8ordo/ui`'s stylesheet does, next to its tokens (`light`, and
25
30
  `dark` under `.dark`), and a stylesheet of your own declares it beside its
26
31
  colours. Declare it by the class, not as `light dark`: that lets the
@@ -43,26 +48,29 @@ legacy fallbacks.
43
48
  ## The shape of it
44
49
 
45
50
  ```
46
- routes/layout.tsx <body><ColorSchemeProvider>{children}</ColorSchemeProvider></body>
47
- │ renders <script> first → class on <html> before the first paint
48
- │ reads the store + the system → keeps the class in step
51
+ routes/layout.tsx <head><ColorSchemeScript /></head>
52
+ │ runs before the stylesheets → class on <html> (+ theme-color <meta>) before the first paint
53
+ <body><ColorSchemeProvider>{children}</ColorSchemeProvider></body>
54
+ │ reads the store + the system → keeps the class (+ the <meta>) in step
49
55
  components useColorScheme() → { scheme, preference, setPreference }
50
56
  ```
51
57
 
52
58
  ## Setup
53
59
 
54
- The provider goes in the root layout — a Server Component — inside `<body>`
55
- and around everything, so the script it renders comes before anything the
56
- page paints:
60
+ Both go in the root layout — a Server Component: the script in `<head>`,
61
+ and the provider inside `<body>`, around everything:
57
62
 
58
63
  ```tsx
59
64
  // src/routes/layout.tsx
60
- import { ColorSchemeProvider } from '@k8ordo/color-scheme';
65
+ import { ColorSchemeProvider, ColorSchemeScript } from '@k8ordo/color-scheme';
61
66
  import type { ReactNode } from 'react';
62
67
 
63
68
  export default function RootLayout({ children }: { children: ReactNode }) {
64
69
  return (
65
70
  <html lang="en" suppressHydrationWarning>
71
+ <head>
72
+ <ColorSchemeScript />
73
+ </head>
66
74
  <body>
67
75
  <ColorSchemeProvider>{children}</ColorSchemeProvider>
68
76
  </body>
@@ -74,40 +82,90 @@ export default function RootLayout({ children }: { children: ReactNode }) {
74
82
  `suppressHydrationWarning` on `<html>`, because the script adds a class the
75
83
  server did not render — that difference is the point, not a mistake.
76
84
 
85
+ The script has to come before every stylesheet in the HTML as sent. A
86
+ script after a stylesheet waits for it to load, and the browser may paint
87
+ the page in the meantime — light, for a visitor who gets dark. React writes
88
+ the stylesheets it hoists into `<head>` ahead of what the layout put there,
89
+ and `@k8ordo/framework` moves the inline scripts of the `<head>` back in
90
+ front of them, so under the framework the layout above is all it takes.
91
+ Without the framework, check the HTML your server sends: the script has to
92
+ come before the first `<link rel="stylesheet">` and `<style>`.
93
+
77
94
  Nothing else is required: the first paint is right, and a visitor who
78
95
  never chooses follows the system, in either direction, for as long as the
79
- page is open. To start every visitor somewhere other than the system, say
80
- so once: `<ColorSchemeProvider defaultPreference="dark">`.
96
+ page is open. To start every visitor somewhere other than the system, give
97
+ both the same default: `<ColorSchemeScript defaultPreference="dark" />` and
98
+ `<ColorSchemeProvider defaultPreference="dark">`. The script applies it
99
+ before the first paint and the provider after hydration; told different
100
+ defaults, a visitor who never chose sees the scheme change as the page
101
+ hydrates.
102
+
103
+ ### The browser's own UI
104
+
105
+ The address bar and the status bar are painted in the colour of
106
+ `<meta name="theme-color">`. A pair of them under
107
+ `media="(prefers-color-scheme: …)"` follows the system, not the visitor:
108
+ with the system on light and dark chosen, the browser's UI stays light
109
+ around a dark page. Give `ColorSchemeScript` the colours instead — the
110
+ page's background in each scheme, usually — and write no theme-color
111
+ `<meta>` of your own:
112
+
113
+ ```tsx
114
+ <ColorSchemeScript themeColor={{ light: '#ffffff', dark: '#18181b' }} />
115
+ ```
116
+
117
+ The script writes one `<meta name="theme-color">` for each scheme, at the
118
+ same moment it puts the class on. While the scheme is the system's — the
119
+ visitor chose nothing and the default is `'system'` — each sits under its
120
+ own `prefers-color-scheme`, so the browser follows the system by itself, as
121
+ it changes. Once something pins the scheme — a choice, or a default of
122
+ `'light'` or `'dark'` — that scheme's colour applies whatever the system
123
+ says. The provider keeps the two in step after hydration
124
+ (`setPreference('system')` hands them back to the system) and takes no
125
+ colours of its own: it changes their `media`, never their `content`.
126
+
127
+ The script writes them, rather than the page, because React writes every
128
+ `<meta>` it renders after the stylesheets, where the script, which runs
129
+ ahead of them, cannot reach. A theme-color `<meta>` of the page's own comes
130
+ after the script's and never applies, so leave it out. Without the script —
131
+ blocked by a policy, or never rendered — there is no theme colour at all.
81
132
 
82
133
  ### Under a Content-Security-Policy
83
134
 
84
- The script is inline, so a policy that restricts scripts has to allow it,
85
- by nonce or by hash. Blocked, it costs the first paint and nothing else: the
86
- provider's effect still writes the class after hydration, but until then
87
- `<html>` has no `dark` class and the page is painted light, so a visitor who
88
- gets dark — by choice or by a `'dark'` default — sees the flash the script
89
- exists to prevent. Do not reach for `'unsafe-inline'`, which allows
90
- every inline script that reaches the page; name this one.
135
+ `ColorSchemeScript` is an inline script, so a policy that restricts scripts
136
+ has to allow it, by nonce or by hash. Blocked, it costs the first paint and
137
+ the theme colour: the provider's effect still writes the class after
138
+ hydration, but until then `<html>` has no `dark` class and the page is
139
+ painted light, so a visitor who gets dark — by choice or by a `'dark'`
140
+ default — sees the flash the script exists to prevent; and the theme-color
141
+ `<meta>` are never written. Do not reach for `'unsafe-inline'`,
142
+ which allows every inline script that reaches the page; name this one.
91
143
 
92
144
  `nonce` puts the answer's nonce on it — in `@k8ordo/framework`'s server
93
145
  mode, `nonce()` from `@k8ordo/framework/server`, which the render may read
94
146
  (signing a script is not writing the response):
95
147
 
96
148
  ```tsx
97
- <ColorSchemeProvider nonce={nonce()}>{children}</ColorSchemeProvider>
149
+ <ColorSchemeScript nonce={nonce()} />
98
150
  ```
99
151
 
100
- `colorSchemeScriptHash(defaultPreference?)` resolves to its hash as a CSP
101
- source, `'sha256-…'`, for a policy that allows it by what it is — the
102
- `csp` option of its static mode, whose files cannot carry a nonce, or a
103
- header that names none. Pass it the `defaultPreference` the provider is
104
- given: the script carries it, so the hash depends on it.
152
+ `colorSchemeScriptHash(options?)` resolves to its hash as a CSP source,
153
+ `'sha256-…'`, for a policy that allows it by what it is — the `csp` option
154
+ of its static mode, whose files cannot carry a nonce, or a header that names
155
+ none. Pass it what the script is given, its nonce aside —
156
+ `{ defaultPreference, themeColor }`: the script carries both, so the hash
157
+ depends on them. Keep them in one module the layout and the config both
158
+ import, and the two cannot drift apart:
105
159
 
106
160
  ```ts
107
161
  // vite.config.ts
162
+ import { themeColor } from './src/lib/theme-color';
163
+
108
164
  framework({
109
165
  mode: 'static',
110
- csp: { 'script-src': ["'self'", await colorSchemeScriptHash()] },
166
+ csp: {
167
+ 'script-src': ["'self'", await colorSchemeScriptHash({ themeColor })],
168
+ },
111
169
  });
112
170
  ```
113
171
 
@@ -188,9 +246,16 @@ every visitor who never chose.
188
246
  ## What it guarantees
189
247
 
190
248
  - **No flash.** The script runs before the first paint and reads the same
191
- row the provider writes; a dark page loads dark. It is an inline script,
192
- so a Content-Security-Policy that restricts scripts has to allow it (see
193
- "Under a Content-Security-Policy").
249
+ row the provider writes; a dark page loads dark. That holds while the
250
+ script comes before every stylesheet in the HTML as sent, which
251
+ `@k8ordo/framework` ensures for a script in the root layout's `<head>`
252
+ (see "Setup"). It is an inline script, so a Content-Security-Policy that
253
+ restricts scripts has to allow it (see "Under a Content-Security-Policy").
254
+ - **The browser's UI agrees.** Given `themeColor`, the theme-color
255
+ `<meta>` are written with the class and show the scheme on screen: the
256
+ pinned scheme's colour once a choice or a default pins it, the system's
257
+ while nothing does. The hydration render leaves them as the script wrote
258
+ them, as it does the class.
194
259
  - **Nothing chosen follows the default, and a `'system'` default follows
195
260
  the system.** A visitor who never chose is never pinned to what the
196
261
  system said on their first visit, and a row that is not a JSON object, or
@@ -219,8 +284,9 @@ every visitor who never chose.
219
284
 
220
285
  Under a browser, `localStorage.clear()`, remove the class from
221
286
  `document.documentElement`, and `resetStateRegistry()` from `@k8ordo/state`
222
- between tests; render the hook under `<ColorSchemeProvider>` (a `wrapper`).
223
- A client-only mount does not run the script the provider renders: React
224
- never executes an inline `<script>` it creates in the browser (in
225
- development it logs an error saying so), so the class a test sees is the
226
- one the provider's effect wrote.
287
+ between tests; render the hook under `<ColorSchemeProvider>` (a `wrapper`),
288
+ and leave `ColorSchemeScript` out: React never executes an inline
289
+ `<script>` it creates in the browser (in development it logs an error
290
+ saying so), so the class a test sees is the one the provider's effect
291
+ wrote. Without the script there is no theme-color `<meta>` either, and the
292
+ provider writes none.
package/docs/llms.txt CHANGED
@@ -5,10 +5,12 @@
5
5
  > told otherwise) — lives in localStorage through `@k8ordo/state`; one rule
6
6
  > resolves it against `prefers-color-scheme`; the result is the `dark` class
7
7
  > on `<html>` (what `@k8ordo/ui` reads, and Tailwind's `dark:` with a
8
- > class-based `@custom-variant dark`). `<ColorSchemeProvider>` in the root
9
- > layout renders the inline script that puts the class on before the first
10
- > paint and keeps it in step afterwards; `useColorScheme()` reads it. The
11
- > server renders the default (`light` when that default is `'system'`).
8
+ > class-based `@custom-variant dark`). `<ColorSchemeScript>` in the root
9
+ > layout's `<head>` is the inline script that puts the class on before the
10
+ > first paint, and `<ColorSchemeProvider>` in its `<body>` keeps it in step
11
+ > afterwards; `useColorScheme()` reads it. Given the application's colours,
12
+ > the two keep `<meta name="theme-color">` on the same scheme. The server
13
+ > renders the default (`light` when that default is `'system'`).
12
14
  >
13
15
  > Like every k8ordo package it assumes React 19 and Server Components, uses
14
16
  > only what has reached Baseline newly available, and ships no polyfills or
@@ -21,28 +23,41 @@ When installed via npm, these docs live under `node_modules/@k8ordo/color-scheme
21
23
  - [Design Guide](GUIDE.md): what the package owns and does not (the class,
22
24
  not the colours or the `color-scheme` property; the rule, not the storage;
23
25
  no contrast preference — `prefers-contrast` and `forced-colors` are the
24
- OS's, which `@k8ordo/ui` follows in either scheme), placing the provider
25
- in the root layout, allowing its inline script under a
26
- Content-Security-Policy (by nonce or by hash, and what a blocked script
27
- costs), reading and changing the preference with the hook, the stored row
28
- and reading it without the hook, what it guarantees, and testing.
26
+ OS's, which `@k8ordo/ui` follows in either scheme), placing the script in
27
+ the root layout's `<head>` (ahead of every stylesheet, which
28
+ `@k8ordo/framework` ensures) and the provider in its `<body>`, the
29
+ browser's own UI (the theme-color `<meta>` the script writes from the
30
+ colours it is given), allowing
31
+ the inline script under a Content-Security-Policy (by nonce or by hash,
32
+ and what a blocked script costs), reading and changing the preference
33
+ with the hook, the stored row and reading it without the hook, what it
34
+ guarantees, and testing.
29
35
 
30
36
  ## Entry point
31
37
 
32
- - `@k8ordo/color-scheme` — `<ColorSchemeProvider defaultPreference? nonce?>`
33
- (client; goes inside `<body>` around everything) renders the inline
34
- `<script>` that puts `dark` on `<html>` before the first paint from the
35
- stored preference, the default (`'system'` unless told otherwise), or the
36
- system, and keeps the class in step; `nonce` signs that script for a
38
+ - `@k8ordo/color-scheme` —
39
+ `<ColorSchemeScript defaultPreference? themeColor? nonce?>` (goes in the
40
+ root layout's `<head>`, ahead of every stylesheet, which
41
+ `@k8ordo/framework` ensures) is the inline `<script>` that puts `dark` on
42
+ `<html>` before the first paint from the stored preference, the default
43
+ (`'system'` unless told otherwise), or the system; `themeColor`
44
+ (`{ light, dark }`) makes it write a `<meta name="theme-color">` per
45
+ scheme, the pinned scheme's applying once a choice or a default pins one
46
+ and each under its own `prefers-color-scheme` otherwise (write no
47
+ theme-color `<meta>` of your own); `nonce` signs it for a
37
48
  Content-Security-Policy (in `@k8ordo/framework`'s server mode, `nonce()`
38
49
  from `@k8ordo/framework/server`).
39
- `colorSchemeScriptHash(defaultPreference?)` resolves to the script's hash
40
- as a CSP source (`'sha256-…'`), for a policy that allows it by hash —
41
- the `csp` option of `@k8ordo/framework`'s static mode. `useColorScheme()` returns
42
- `{ scheme, preference, setPreference }`: `scheme` is `'light' | 'dark'`
50
+ `<ColorSchemeProvider defaultPreference?>` (client; goes inside `<body>`
51
+ around everything) keeps the class and the theme-color `<meta>` in step
52
+ after hydration; give it the same `defaultPreference` as the script.
53
+ `colorSchemeScriptHash({ defaultPreference?, themeColor? }?)` resolves to
54
+ the script's hash as a CSP source (`'sha256-…'`), for a policy that
55
+ allows it by hash — the `csp` option of `@k8ordo/framework`'s static
56
+ mode; pass what the script is given, its nonce aside. `useColorScheme()`
57
+ returns `{ scheme, preference, setPreference }`: `scheme` is `'light' | 'dark'`
43
58
  on screen, `preference` is `'light' | 'dark' | 'system'`, and
44
59
  `setPreference('system')` clears the stored preference, so the default
45
60
  applies again. `colorSchemeState` is the `@k8ordo/state` local definition
46
61
  itself (`k8ordo-state:color-scheme`).
47
62
  Types: `ColorScheme`, `ColorSchemePreference`, `ColorSchemeProviderProps`,
48
- `UseColorScheme`.
63
+ `ColorSchemeScriptOptions`, `ColorSchemeScriptProps`, `UseColorScheme`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@k8ordo/color-scheme",
3
- "version": "1.4.4",
3
+ "version": "2.3.1",
4
4
  "description": "The colour-scheme axis of an application, owned: the visitor's light / dark / system preference, kept in localStorage, resolved against the system, put on <html> before the first paint and kept there.",
5
5
  "keywords": [
6
6
  "color-scheme",
@@ -39,7 +39,7 @@
39
39
  },
40
40
  "devDependencies": {
41
41
  "@arethetypeswrong/cli": "0.18.5",
42
- "@k8ordo/state": "^1.4.4",
42
+ "@k8ordo/state": "^2.3.1",
43
43
  "@types/react": "19.3.0",
44
44
  "@types/react-dom": "19.3.0",
45
45
  "@vitejs/plugin-react": "6.1.2",
@@ -55,7 +55,7 @@
55
55
  "zod": "4.6.7"
56
56
  },
57
57
  "peerDependencies": {
58
- "@k8ordo/state": "^1.4.4",
58
+ "@k8ordo/state": "^2.3.1",
59
59
  "@types/react": ">=19.3.0",
60
60
  "react": ">=19.3.0",
61
61
  "typescript": ">=7.0.0",