Menhir

Theme

The reader's choice of theme, out of the themes you list, saved in localStorage or a cookie and applied to <html>. It stays in step across tabs. A utility, not a component: the control is yours, and so is how each theme looks. A theme is just a theme, light or dark; for the reader's light, dark or system choice, use Color Scheme.

Entry points
menhir/theme/local-storage, 1.0 kB
menhir/theme/cookie, 1.2 kB

Example

Styling

Styled from the attribute on <html>.

ThemePicker.tsx
import { For } from "solid-js";
import { createTheme } from "menhir/theme/local-storage";

import { themeOptions } from "../themes";

/** A native select of the themes, above a preview drawn in the chosen one. */
export default function ThemePicker() {
  const theme = createTheme(themeOptions);

  return (
    <div class="grid justify-items-start gap-3">
      <label class="text-sm">
        Theme{" "}
        <select
          class="rounded-md border border-stone-300 bg-transparent px-2 py-1 dark:border-stone-700"
          value={theme.theme()}
          onChange={(event) =>
            theme.setTheme(
              event.currentTarget.value as (typeof themeOptions.themes)[number],
            )
          }
        >
          <For each={themeOptions.themes}>
            {(name) => <option value={name}>{name}</option>}
          </For>
        </select>
      </label>
      {/* Paper by default; in-[…] styles the other themes from the
          attribute on <html>. */}
      <p class="rounded-lg bg-amber-50 p-4 text-amber-950 in-[[data-theme=forest]]:bg-emerald-900 in-[[data-theme=forest]]:text-emerald-50 in-[[data-theme=slate]]:bg-slate-800 in-[[data-theme=slate]]:text-slate-100">
        Styled from the attribute on &lt;html&gt;.
      </p>
    </div>
  );
}
themes.ts
/** The example's themes: give createTheme and themeScript the same options. */
export const themeOptions = {
  themes: ["paper", "slate", "forest"],
  defaultTheme: "paper",
} as const;

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/theme/local-storage unless the server renders each page per request and should send the chosen theme; then use menhir/theme/cookie (see Server rendering).

List the themes, add the head script so the saved theme is applied before the page first paints, and call createTheme in the component that changes it:

import { createTheme, themeScript } from "menhir/theme/local-storage";

// Every theme the reader can choose, and the one shown until they do.
// Give createTheme and themeScript the same options.
export const themeOptions = {
  themes: ["paper", "slate", "forest"],
  defaultTheme: "paper",
} as const;

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

// In the component that changes the theme:
const theme = createTheme(themeOptions);
theme.setTheme("slate");

Style each theme from the attribute. Each theme can say whether it is light or dark with color-scheme, so native controls and scrollbars match it:

:root[data-theme="paper"] {
  color-scheme: light;
  --background: #fbf7ee;
  --text: #3d2e1f;
}
:root[data-theme="slate"] {
  color-scheme: dark;
  --background: #1e293b;
  --text: #f1f5f9;
}

The server cannot see localStorage, so the state starts as the default theme and catches up once the page settles; the head script has already applied the saved theme by then. A saved name that is no longer in themes reads as the default.

Offer the themes in a <select>, a radio group or a menu, as the example does. With attribute: "class", every theme name is a class Menhir owns on <html>: changing the theme removes all of them before adding one.

Server rendering

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

import { getRequestEvent } from "@solidjs/web";
import { themeFromCookie, themeScript } from "menhir/theme/cookie";

// The server's document. Pass the options given to createTheme.
const theme = themeFromCookie(
  getRequestEvent()?.request.headers.get("cookie"),
  themeOptions,
);

<html lang="en" data-theme={theme}>
  <head>
    <script innerHTML={themeScript(themeOptions)} />
  </head>
  ...
</html>

The page has to be rendered for each request: a prerendered page has no cookie to read, so it shows the default and disagrees with the saved theme when it hydrates. Cookies have no event for changes made in other tabs, so another tab picks up a theme when it is shown again.

Content Security Policy

A policy without 'unsafe-inline' blocks the head script until it is allowed. A server that renders each page can put its nonce on the element:

// nonce: the one the server made for this response, as in
// Content-Security-Policy: script-src 'nonce-<nonce>'
<script nonce={nonce} innerHTML={themeScript(themeOptions)} />

A prerendered page can allow the SHA-256 hash of what themeScript returns instead, as Color Scheme shows. Compute the hash in the build: it changes when the options do, such as the list of themes.

With Color Scheme

Most sites have either a light, dark or system choice or a list of themes. A site with both runs the two side by side: each has its own attribute and storage key, so each theme can have a light and a dark look.

// data-color-scheme="dark" and data-theme="nord" on <html>.
const colorScheme = createColorScheme();
const theme = createTheme(themeOptions);
:root[data-theme="nord"] {
  --background: #eceff4;
}
:root[data-theme="nord"][data-color-scheme="dark"] {
  --background: #2e3440;
}

Following the system

To follow the system with a theme for each look, such as paper while the system is light and slate while it is dark, add a theme for that choice and style it with a media query. Unlike With Color Scheme, the reader makes one choice: System sits in the same list as the fixed themes.

export const themeOptions = {
  themes: ["system", "paper", "slate", "forest"],
  defaultTheme: "system",
} as const;
:root[data-theme="paper"],
:root[data-theme="system"] {
  color-scheme: light;
  --background: #fbf7ee;
  --text: #3d2e1f;
}
:root[data-theme="slate"] {
  color-scheme: dark;
  --background: #1e293b;
  --text: #f1f5f9;
}
@media (prefers-color-scheme: dark) {
  :root[data-theme="system"] {
    color-scheme: dark;
    --background: #1e293b;
    --text: #f1f5f9;
  }
}

The browser switches looks when the system does, and the head script has put system on <html> before the first paint, so the page never shows the wrong one. The server sends system as it is, so cookie storage needs nothing more.

The dark look's values are written twice, for slate and in the media query. With Tailwind CSS, a custom variant can hold the pair instead, so each class is written once and Tailwind writes both rules:

/* slate: applies under slate, and under system while the system is dark,
   as in class="bg-amber-50 slate:bg-slate-800". */
@custom-variant slate {
  &:where([data-theme="slate"], [data-theme="slate"] *) {
    @slot;
  }
  @media (prefers-color-scheme: dark) {
    &:where([data-theme="system"], [data-theme="system"] *) {
      @slot;
    }
  }
}

theme() returns system, not the look on screen; a component that needs the look reads matchMedia("(prefers-color-scheme: dark)"). The pair is the app's: the reader cannot choose which theme shows while the system is light and which while it is dark.

API reference

FunctionTypeDescription
createTheme(options) => ThemeStateThe reader's theme, saved and applied to <html>. Call it in a component; it returns the state below.
themeScript(options) => stringThe source of the head script that applies the theme before the first paint. Give it the same options as createTheme.
themeFromCookie(cookieHeader, options) => ThemeFrom menhir/theme/cookie only: the theme saved in a request's Cookie header, or the default.

Options

Taken by createTheme, themeScript and themeFromCookie. Pass them all the same options.

OptionTypeDescription
themesreadonly string[]Every theme the reader can choose. Names use letters, digits, - and _. Their union is the type of a theme.
defaultThemestringOne of themes: the theme shown until the reader chooses. Choosing it removes the saved value.
storageKeystringThe localStorage key, or the cookie name, the choice is saved under. Default "theme".
attribute"class" | `data-${string}`Where the theme goes on <html>: a data attribute set to its name, default "data-theme", or "class" for a class named after it.

State

What createTheme returns. Theme is the union of the names in themes.

FieldTypeDescription
theme() => ThemeThe reader's theme. The default until the page has settled; from menhir/theme/cookie, the saved theme from the first render.
setTheme(theme: Theme) => voidSaves a theme and applies it, in every instance in the tab and in other tabs (with a cookie, once they are shown again). Choosing the default removes the saved value. Call it from an event handler.