Menhir

Color Scheme

The reader's choice of light, dark or system, saved in localStorage or a cookie and applied to <html>. It follows the system while the choice is system, and stays in step across tabs. A utility, not a component: the control is yours, and so is how each scheme looks. The toggle in this site's header is the example below. For a list of themes rather than light and dark, use Theme. The two write different attributes, data-color-scheme and data-theme, so a site can use both.

Entry points
menhir/color-scheme/local-storage, 1.2 kB
menhir/color-scheme/cookie, 1.4 kB

Example

Styling
ColorSchemeToggle.tsx
import {
  createColorScheme,
  nextColorScheme,
} from "menhir/color-scheme/local-storage";

import ColorSchemeIcon from "../ColorSchemeIcon";

/**
 * One button that cycles through the schemes. Its name says the current scheme
 * and what a click does; the icon shows the current scheme.
 */
export default function ColorSchemeToggle() {
  const colorScheme = createColorScheme();
  const next = () =>
    nextColorScheme(colorScheme.scheme(), colorScheme.system());

  return (
    <button
      type="button"
      aria-label={`Color scheme: ${colorScheme.scheme()}. Switch to ${next()}.`}
      title={`Color scheme: ${colorScheme.scheme()}`}
      class="inline-flex size-9 cursor-pointer items-center justify-center rounded-md text-stone-700 hover:bg-stone-200/60 hover:text-stone-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-stone-500 dark:text-stone-300 dark:hover:bg-stone-900 dark:hover:text-white"
      onClick={() => colorScheme.setScheme(next())}
    >
      <ColorSchemeIcon scheme={colorScheme.scheme()} />
    </button>
  );
}
ColorSchemeIcon.tsx
import { Match, Switch } from "solid-js";
import type { ColorScheme } from "menhir/color-scheme/local-storage";

/** A sun, a moon or a screen, for the light, dark and system schemes. */
export default function ColorSchemeIcon(props: { scheme: ColorScheme }) {
  return (
    <svg
      viewBox="0 0 24 24"
      width="20"
      height="20"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
    >
      <Switch>
        <Match when={props.scheme === "light"}>
          <circle cx="12" cy="12" r="4" />
          <path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4" />
        </Match>
        <Match when={props.scheme === "dark"}>
          <path d="M20 14.5A8 8 0 0 1 9.5 4 8 8 0 1 0 20 14.5Z" />
        </Match>
        <Match when={props.scheme === "system"}>
          <rect x="3" y="4" width="18" height="12" rx="2" />
          <path d="M8 20h8M12 16v4" />
        </Match>
      </Switch>
    </svg>
  );
}

Setup

Import from the entry point for where the choice is saved. Both export the same functions, so switching is a change of import. Use menhir/color-scheme/local-storage unless the server renders each page per request and should send the chosen scheme; then use menhir/color-scheme/cookie (see Server rendering).

Add the head script, so the saved look is applied before the page first paints, without a flash of the other one:

import { colorSchemeScript } from "menhir/color-scheme/local-storage";

// In the document's <head>, before the styles. As a child, the script would
// be HTML-escaped, so pass it as innerHTML.
<script innerHTML={colorSchemeScript()} />

Style the schemes from the attribute. With Tailwind CSS, point the dark: variant at it:

/* Tailwind's dark: variant, from the attribute instead of the system. */
@custom-variant dark (&:where([data-color-scheme="dark"], [data-color-scheme="dark"] *));

/* Native controls and scrollbars follow the scheme too. */
:root[data-color-scheme="dark"] {
  color-scheme: dark;
}

With plain CSS:

:root {
  color-scheme: light;
}
:root[data-color-scheme="dark"] {
  color-scheme: dark;
}
/* Then pick colours with light-dark(), or under [data-color-scheme="dark"]. */

Then call createColorScheme() in the component that changes the scheme, as the example does. The server cannot see localStorage, so the state starts as system and catches up once the page settles; the head script has already applied the right look by then.

Server rendering

From menhir/color-scheme/cookie, the choice is saved in a cookie that the browser sends with every request, so the server can render it. createColorScheme reads the cookie itself, from getRequestEvent() on the server, so its state is right from the first render. Put the attribute on <html> with colorSchemeFromCookie:

import { getRequestEvent } from "@solidjs/web";
import {
  colorSchemeFromCookie,
  colorSchemeScript,
  createColorScheme,
} from "menhir/color-scheme/cookie";

// The server's document. The cookie names a fixed scheme, or none for system.
const scheme = colorSchemeFromCookie(
  getRequestEvent()?.request.headers.get("cookie"),
);

<html lang="en" data-color-scheme={scheme === "system" ? undefined : scheme}>
  <head>
    {/* Still needed: the server cannot see the system's preference. */}
    <script innerHTML={colorSchemeScript()} />
  </head>
  ...
</html>

// In the component that changes the scheme:
const colorScheme = createColorScheme();

The page has to be rendered for each request: a prerendered page has no cookie to read, so it shows system and disagrees with the saved choice when it hydrates. Keep the head script. While the choice is system the server cannot know the look, since the system's preference never reaches it; with a fixed scheme the script applies what the server already rendered. Cookies have no event for changes made in other tabs, so another tab picks up a choice when it is shown again.

Content Security Policy

A policy without 'unsafe-inline' blocks the head script until it is allowed, by a nonce or by its hash. colorSchemeScript returns the script's source and the element is yours, so neither needs an option. The script itself only reads the saved choice and sets the attribute, which a policy does not restrict.

A server that renders each page can put its nonce on the element:

// nonce: the one the server made for this response. It goes in the header,
// Content-Security-Policy: script-src 'nonce-<nonce>', and to Solid's own
// scripts through the nonce option of renderToStream or renderToString.
<script nonce={nonce} innerHTML={colorSchemeScript()} />

A prerendered page has no nonce, so allow the script by the hash of its source:

import { createHash } from "node:crypto";
import { colorSchemeScript } from "menhir/color-scheme/local-storage";

// In the build or the server's setup, with the options the page uses.
const hash = createHash("sha256").update(colorSchemeScript()).digest("base64");
// Content-Security-Policy: script-src 'sha256-<hash>'

Compute the hash rather than pasting it: the source depends on the entry point and the options, and may change with any Menhir release. Loading the script from a file instead would let the page paint before it runs, which is the flash it is there to prevent.

Cycling order

A single button has to step through three schemes that share two looks, so one click in every round changes nothing on screen. nextColorScheme puts that click last: from system it goes to the look the system is not showing, so the first click always does something visible.

System prefersOrder
LightSystem → Dark → Light → System
DarkSystem → Light → Dark → System

The button's name says the current scheme and what a click does, such as "Color scheme: system. Switch to dark.", and its icon shows the current scheme.

API reference

FunctionTypeDescription
createColorScheme(options?) => ColorSchemeStateThe choice, saved and applied to <html>, following the system while it is system. Call it in a component; it returns the state below.
colorSchemeScript(options?) => stringThe source of the head script that applies the choice before the first paint. Give it the same options as createColorScheme.
colorSchemeFromCookie(cookieHeader, options?) => ColorSchemeFrom menhir/color-scheme/cookie only: the scheme saved in a request's Cookie header.
nextColorScheme(scheme, system) => ColorSchemeThe scheme a single cycling toggle moves to next (see Cycling order).
resolveColorScheme(scheme, system) => ResolvedColorSchemeThe look of a scheme: system replaced by the system's look.

Options

Taken by createColorScheme and colorSchemeScript. Pass both the same options.

OptionTypeDescription
storageKeystringThe localStorage key, or the cookie name, the choice is saved under. Default "color-scheme".
attribute"class" | `data-${string}`Where the look goes on <html>: a data attribute set to light or dark, default "data-color-scheme", or "class" for a light or dark class, which Menhir then owns on <html>.

State

What createColorScheme returns.

FieldTypeDescription
scheme() => ColorSchemeThe reader's choice: "light", "dark" or "system". System until the page has settled; from menhir/color-scheme/cookie, the saved choice from the first render.
system() => ResolvedColorSchemeThe look the system prefers, "light" or "dark". Light until the page has settled.
resolved() => ResolvedColorSchemeThe look on screen: scheme, with system replaced by system().
setScheme(scheme: ColorScheme) => voidSaves a choice and applies it, in every instance in the tab and in other tabs (with a cookie, once they are shown again). Choosing system removes the saved value. Call it from an event handler.