@k8ordo/color-scheme

API

Everything @k8ordo/color-scheme exports: the components, the hook, values and types.

On this page

ColorSchemeScript

Import from @k8ordo/color-scheme

The inline script that puts dark on <html> before the first paint, and writes the theme-color <meta> when given themeColor. It goes in the root layout’s <head>.

ts
ColorSchemeScript(props: ColorSchemeScriptProps): ReactNode

Parameters

defaultPreferenceColorSchemePreference = 'system'
What applies to a visitor who has chosen nothing, at the first paint. Pass the same value as the provider’s defaultPreference.
themeColor{ light: string; dark: string } | undefined
The light and dark colors for the browser’s own UI, such as the address bar. Given them, the script writes theme-color <meta> that match the scheme on screen. Render no theme-color <meta> of your own.
noncestring | undefined
The nonce to put on the script. In @k8ordo/framework’s server mode, pass nonce(). Leave it out when the script is allowed by hash.

Caveats

  • It is exported from a 'use client' module, so a root layout that is a Server Component can render it directly. The script's text is written into the HTML only, never into the payload.
  • It has to come before every stylesheet. @k8ordo/framework moves the inline scripts written in <head> ahead of the stylesheets.
layout.tsx
export default function RootLayout({
  children,
}: {
  children: ReactNode;
}) {
  return (
    <html lang="en" suppressHydrationWarning>
      <head>
        <ColorSchemeScript />
      </head>
      <body>
        <ColorSchemeProvider>{children}</ColorSchemeProvider>
      </body>
    </html>
  );
}

ColorSchemeProvider

Import from @k8ordo/color-scheme

The provider that wraps the whole page. It goes in the root layout, inside <body>. After hydration it updates dark on <html> whenever the stored choice or the OS setting changes, and the theme-color <meta> the script wrote along with it.

ts
ColorSchemeProvider(props: ColorSchemeProviderProps): ReactNode

Parameters

defaultPreferenceColorSchemePreference = 'system'
What applies to a visitor who has chosen nothing. 'system' follows the OS setting. 'light' or 'dark' keeps every visitor on that scheme until they choose. Give ColorSchemeScript the same value.
childrenReactNode
The whole page.

Caveats

  • It is exported from a 'use client' module, so a root layout that is a Server Component can render it directly.
  • Put suppressHydrationWarning on <html>. The class the script adds is not in the server HTML, and React reports it as a mismatch in development.
  • Put exactly one in the application. With two, each writes the class, and they can disagree.
layout.tsx
export default function RootLayout({
  children,
}: {
  children: ReactNode;
}) {
  return (
    <html lang="en" suppressHydrationWarning>
      <head>
        <ColorSchemeScript />
      </head>
      <body>
        <ColorSchemeProvider>{children}</ColorSchemeProvider>
      </body>
    </html>
  );
}

useColorScheme

Import from @k8ordo/color-scheme

Returns the scheme on screen, the visitor’s choice, and a function that changes it. Use it in a Client Component.

ts
useColorScheme(): UseColorScheme

Returns

UseColorScheme — An object holding scheme, preference and setPreference.

Fields

scheme'light' | 'dark'
What is on screen. It is decided by the visitor’s choice, then the provider’s default, then the OS setting.
preference'light' | 'dark' | 'system'
What the visitor chose. 'system' while nothing is chosen.
setPreference(preference: ColorSchemePreference) => void
Stores a choice. 'system' clears the stored choice, so the provider’s default applies again.

Caveats

  • Called outside the provider, it throws an error starting with useColorScheme needs <ColorSchemeProvider> above it. It does not return the default.
  • It only reads what the provider decided. It never changes the class on <html> or localStorage.
  • In the server render and the hydration render it returns the value decided from the default, which is 'light' for a 'system' default. The stored choice and the OS setting are reflected from the render after that.
scheme-toggle.tsx
const { scheme, setPreference } = useColorScheme();

<button
  onClick={() => {
    setPreference(scheme === 'dark' ? 'light' : 'dark');
  }}
  type="button"
>
  Toggle
</button>

A toggle and a three-way choice are built in the Switch guide.

colorSchemeState

Import from @k8ordo/color-scheme

The @k8ordo/state defineLocalState definition that says where the preference is stored. It is saved in localStorage under k8ordo-state:color-scheme, as an object with one field, preference.

ts
const colorSchemeState = defineLocalState(
  'color-scheme',
  z.object({ preference: z.optional(z.enum(['light', 'dark'])) }),
);

Fields

kind'local'
The kind of place the state is stored in. 'local', for localStorage.
key'color-scheme'
Its name within @k8ordo/state. There is one store per name.
schemaZodMiniObject
The schema the definition was given.
storageKey'k8ordo-state:color-scheme'
The localStorage key: k8ordo-state: followed by key.
inlineRead() => string
Returns a JavaScript expression for an inline script. It evaluates to the stored object, or to null when the value cannot be read.

Caveats

  • useAppState(colorSchemeState) reads the stored preference without the hook. Its value is 'light' | 'dark' | undefined, not the resolved scheme.
  • Change the choice through setPreference. A direct localStorage.setItem in the same tab is not reflected until a reload.
  • Do not define another defineLocalState('color-scheme', …). Stores are shared by name, so both definitions would read and write the same stored value.
stored-preference.tsx
const [{ preference }] = useAppState(colorSchemeState);
// 'light' | 'dark' | undefined

colorSchemeScriptHash

Import from @k8ordo/color-scheme

Resolves to the SHA-256 of ColorSchemeScript’s inline script as a CSP source, 'sha256-…'. Put it in a policy that allows the script without a nonce.

ts
colorSchemeScriptHash(
  options?: ColorSchemeScriptOptions,
): Promise<string>

Parameters

options.defaultPreferenceColorSchemePreference = 'system'
The defaultPreference ColorSchemeScript is given. The default is written into the script, so the hash depends on it.
options.themeColor{ light: string; dark: string } | undefined
The themeColor ColorSchemeScript is given. The colors are written into the script too, so the hash depends on them. The order of the keys does not.

Returns

Promise<string> — A CSP source such as 'sha256-…', quotes included.

Caveats

  • Call it where the policy is written, every time, instead of copying its value. The script text belongs to the installed version, and an update may change it.
  • Where every response can carry a nonce, the hash is not needed.
vite.config.ts
framework({
  mode: 'static',
  csp: {
    'script-src': ["'self'", await colorSchemeScriptHash()],
  },
});

Building the policy is covered in the CSP guide.

ColorScheme

Import from @k8ordo/color-scheme

A scheme that can be on screen. The type of scheme.

ts
type ColorScheme = 'light' | 'dark';

ColorSchemePreference

Import from @k8ordo/color-scheme

A scheme, or 'system'. As a visitor’s choice, 'system' means nothing chosen, so the provider’s default applies. As that default, it follows the OS setting.

ts
type ColorSchemePreference = ColorScheme | 'system';

ColorSchemeProviderProps

Import from @k8ordo/color-scheme

The props of ColorSchemeProvider. Use it for a component of your own that wraps the provider.

ts
type ColorSchemeProviderProps = {
  readonly defaultPreference?: ColorSchemePreference;
  readonly children: ReactNode;
};

ColorSchemeScriptOptions

Import from @k8ordo/color-scheme

The props of ColorSchemeScript that are written into the script. The type of colorSchemeScriptHash()’s argument.

ts
type ColorSchemeScriptOptions = {
  readonly defaultPreference?: ColorSchemePreference;
  readonly themeColor?: {
    readonly light: string;
    readonly dark: string;
  };
};

ColorSchemeScriptProps

Import from @k8ordo/color-scheme

The props of ColorSchemeScript. Use it for a component of your own that wraps the script.

ts
type ColorSchemeScriptProps = ColorSchemeScriptOptions & {
  readonly nonce?: string;
};

UseColorScheme

Import from @k8ordo/color-scheme

What useColorScheme() returns. Use it for a component that receives the hook’s value as props.

ts
type UseColorScheme = {
  readonly scheme: ColorScheme;
  readonly preference: ColorSchemePreference;
  readonly setPreference: (preference: ColorSchemePreference) => void;
};
k8ordo

React libraries that use Baseline features without holding back.