# Theming

The user picks the theme, the mode and the variant; the app offers the choice, remembers it, and never overrides it.

API [Theme](/ui/storybook/?path=/docs/ui-foundations-theme--docs) [ThemeMenu](/ui/storybook/?path=/docs/ui-thememenu--docs) [ThemeEditor](/ui/storybook/?path=/docs/ui-themeeditor--docs) [Terminal](/ui/storybook/?path=/docs/ui-foundations-terminal--docs)

**Put a `ThemeMenu` where the user can reach it from any screen, and let the store do the rest.** The theme is the user's: they pick it for their eyes, their room and their screen, and an app that fixes one, or quietly bends one, takes that away.

```tsx
import { Button } from "@orz/ui/components/button";
import { InfoPopover } from "@orz/ui/components/info-popover";
import { Label } from "@orz/ui/components/label";
import { Separator } from "@orz/ui/components/separator";
import { ThemeEditor } from "@orz/ui/components/theme-editor";
import { ThemeMenu } from "@orz/ui/components/theme-menu";
import { useTerminalTheme, useTheme } from "@orz/ui/theme";
import { PaletteIcon } from "lucide-react";
import { useState } from "react";

const TEST_LOG: [string, string?][][] = [
  [["✓", "text-ansi-green"], [" test/retry.test.ts (4 tests)"]],
  [["✓", "text-ansi-green"], [" test/fetch-task.test.ts (9 tests)"]],
  [
    ["×", "text-ansi-red"],
    [" test/flaky.test.ts (1 test | "],
    ["1 failed", "text-ansi-red"],
    [")"],
  ],
  [
    ["Tests ", "text-ansi-bright-black"],
    ["1 failed", "text-ansi-red"],
    [" | "],
    ["16 passed", "text-ansi-green"],
    [" (17)"],
  ],
];

type Editing = { id: string | undefined; slot: "ui" | "terminal" } | null;

export function AppearanceSettings() {
  const { theme, colorScheme, variant, amoled } = useTheme();
  const terminal = useTerminalTheme();
  const [editing, setEditing] = useState<Editing>(null);
  const customize = (id: string | undefined, slot: "ui" | "terminal") =>
    setEditing({ id, slot });
  return (
    <div className="grid">
      <div className="flex items-center justify-between gap-4 py-3">
        <div className="flex items-center gap-1">
          <Label htmlFor="appearance-theme">Theme</Label>
          <InfoPopover label="About theme">
            Shared with the menu in this site's top bar: a pick repaints the
            whole page.
          </InfoPopover>
        </div>
        <ThemeMenu
          onCustomize={customize}
          trigger={({ Icon, label }) => (
            <Button
              id="appearance-theme"
              variant="outline"
              aria-label={`${label}: ${theme.label}`}
              className="max-w-48"
            >
              <Icon />
              <span className="truncate">
                {theme.label}
                {variant !== "default" && `, ${variant}`}
                {amoled && ", AMOLED"}
              </span>
              <span className="sr-only">, {colorScheme}</span>
            </Button>
          )}
        />
      </div>
      <Separator purpose="row" />
      <div className="grid gap-3 py-3">
        <div className="flex items-center justify-between gap-4">
          <div className="flex items-center gap-1">
            <Label htmlFor="appearance-terminal-theme">Terminal theme</Label>
            <InfoPopover label="About terminal theme">
              For logs and recordings, such as a pull request's test output.
            </InfoPopover>
          </div>
          <ThemeMenu
            slot="terminal"
            onCustomize={customize}
            trigger={({ Icon, label }) => (
              <Button
                id="appearance-terminal-theme"
                variant="outline"
                aria-label={`${label}: ${terminal.following ? "follows the theme" : terminal.theme.label}`}
                className="max-w-48"
              >
                <Icon />
                <span className="truncate">
                  {terminal.following
                    ? "Follows the theme"
                    : terminal.theme.label}
                </span>
              </Button>
            )}
          />
        </div>
        <pre className="overflow-x-auto rounded-lg bg-terminal-background p-3 font-mono text-terminal-foreground text-ui-sm leading-5">
          {TEST_LOG.map((line) => (
            <div key={line.map(([text]) => text).join("")}>
              {line.map(([text, color]) => (
                <span key={text} className={color}>
                  {text}
                </span>
              ))}
            </div>
          ))}
        </pre>
      </div>
      <Separator purpose="row" />
      <div className="flex items-center justify-between gap-4 py-3">
        <Label htmlFor="appearance-custom-themes">Custom themes</Label>
        <Button
          id="appearance-custom-themes"
          variant="outline"
          onClick={() => customize(undefined, "ui")}
        >
          <PaletteIcon />
          Edit…
        </Button>
      </div>
      <ThemeEditor
        open={editing !== null}
        themeId={editing?.id}
        kind={editing?.slot}
        onOpenChange={(open) => {
          if (!open) setEditing(null);
        }}
      />
    </div>
  );
}
```

The Settings demo's Appearance rows, on the site's own theme store. A pick in **Theme** repaints the whole page, this text included; its mode row sets Auto, Light or Dark, and a theme's ▾ opens its variants under it, the picked theme's open already. **Terminal theme** repaints only the test output under it, from the pull request demo's failing run, unless it is left to follow. **Edit…**, or **Custom themes…** in either menu, opens the `ThemeEditor`, which repaints the page with the draft as you edit it.

## What the user chooses

| Choice         | Values                                                                                                                                                                | Where                                                                                            |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| Style          | The [styles](/ui/guidelines/foundations/styles/index.md) the app offers; there is no choice when it offers one                                                        | `ThemeMenu`'s Style row                                                                          |
| Theme          | The themes the app passes the store, such as [`@orz/themes`' built-ins](#the-built-in-themes)                                                                         | `ThemeMenu`                                                                                      |
| Mode           | Auto (follows the system), Light, Dark; one-palette themes have one. Use AMOLED draws the dark side in true black, wherever the mode shows it, Auto's nights included | `ThemeMenu`'s mode row, Use AMOLED behind its ▾                                                  |
| Variant        | Per theme, such as Tessera's accents or [Catppuccin's flavours](#the-built-in-themes)                                                                                 | Under its theme in `ThemeMenu`, once the row's ▾ opens them; the picked theme's are open already |
| Terminal theme | Any theme, a terminal-only one, or following the UI                                                                                                                   | `ThemeMenu slot="terminal"`                                                                      |
| Custom themes  | A theme based on another with overrides, or made from scratch                                                                                                         | `ThemeEditor`                                                                                    |

The store saves the pick under the app's `storageKey`, follows the system's light and dark when the mode is Auto, and follows a pick made in another tab.

## The built-in themes

`@orz/themes` ships these, each a module of its own; `builtinThemes` lists them all. A side with a name of its own shows it, and the variants a side adds follow it. Style is the [style](/ui/guidelines/foundations/styles/index.md) a theme is drawn for.

| Theme            | Import                                 | Style   | Light                                                           | Dark                                                                    |
| ---------------- | -------------------------------------- | ------- | --------------------------------------------------------------- | ----------------------------------------------------------------------- |
| Tessera          | `defaultTheme` (`default`)             | Default | ✓; Blue, Indigo, Violet, Teal, Green, Amber, Vermilion, Crimson | ✓; Blue, Indigo, Violet, Teal, Green, Amber, Vermilion, Crimson         |
| Warm Ink         | `warmInk` (`warm-ink`)                 | Default | ✓                                                               | ✓                                                                       |
| Kabushiki        | `kabushiki`                            | Default | ✓; Ai, Enji, Tokiwa, Kaki, Edomurasaki                          | ✓; Ai, Enji, Tokiwa, Kaki, Edomurasaki                                  |
| Picotera         | `picotera`                             | Default | Pico                                                            | Tera                                                                    |
| Solarized        | `solarized`                            | Default | ✓                                                               | ✓                                                                       |
| Visual Studio    | `vs`                                   | Default | ✓                                                               | ✓                                                                       |
| GitHub           | `github`                               | Default | ✓                                                               | ✓                                                                       |
| Catppuccin       | `catppuccin`                           | Default | Latte; Mocha (Gray), Frappé (Gray), Macchiato (Gray)            | Mocha; Frappé, Macchiato, Mocha (Gray), Frappé (Gray), Macchiato (Gray) |
| Gruvbox          | `gruvbox`                              | Default | ✓                                                               | ✓                                                                       |
| Prohibitorum     | `prohibitorum`                         | Default | ✓; Nord, Sand, Matcha, Sakura, Lavender, Lagoon, Citrus         | ✓; Nord, Sand, Matcha, Sakura, Lavender, Lagoon, Citrus                 |
| Dracula          | `dracula`                              | Default |                                                                 | ✓                                                                       |
| Nord             | `nord`                                 | Default |                                                                 | ✓                                                                       |
| Tokyo Night      | `tokyoNight` (`tokyo-night`)           | Default |                                                                 | ✓                                                                       |
| One Dark         | `oneDark` (`one-dark`)                 | Default |                                                                 | ✓                                                                       |
| Monokai          | `monokai`                              | Default |                                                                 | ✓                                                                       |
| Afterglow        | `afterglow`                            | Default |                                                                 | ✓                                                                       |
| Windows Standard | `windowsStandard` (`windows-standard`) | Raymond | ✓                                                               |                                                                         |

Every dark side can be shown in AMOLED, which makes the background true black.

## Setting it up

[Start](/ui/start/index.md#theme) creates the store. Three things make it feel native:

- **Pass the themes you offer.** `createThemeStore({ themes })` takes the list, so the bundle carries only those; the first is the default for a new user.
- **Paint before the first frame.** `themePaintGuardScript({ storageKey })` in an inline `<script>` in `<head>` paints the saved theme before the bundle loads, so a reload in a dark theme never flashes white.
- **Give a terminal its own slot** with `terminalThemes` when the app shows terminal output, so someone who likes a light UI can keep a dark terminal.

## Themes belong to styles

A theme lists the styles it is drawn for, as the table above has them, and the menu shows only the active style's themes. A custom theme belongs to the styles of the theme it starts from, and one made from scratch to the style it was made under. [Styles](/ui/guidelines/foundations/styles/index.md) says what a style draws, and how an app offers more than one.

## What the app does not do

**Do**

Draw every colour from a token, and read `useTheme()` or `useTerminalTheme()` when a script needs the colours, such as a canvas or xterm.js. Both re-render when the pick changes.

**Don't**

Style by theme id with `[data-theme="dracula"]`, or read a colour from CSS once and keep it. The first breaks in every theme you did not test; the second keeps the old colour after a switch.

Both bars are drawn on a canvas, the way a chart or xterm.js draws. Pick another theme or terminal theme above: the first redraws in it, and the second keeps the colours it read when the page loaded.

- **No fixed theme for a screen.** A dark-only editor or a light-only print view takes the choice away in the place the user spends the most time.
- **No `dark:` for colour.** A token already flips with the mode. Keep `dark:` for what a token cannot say, such as swapping a screenshot for its dark twin, and know that it sees only light and dark, not which theme.
- **No brand override of the palette.** The store's rule has plain `:root` specificity, so a later stylesheet can retune a token for every theme. Do that only to fix a token, and check it in every theme the app offers, because it now applies to all of them.

## A part of the page in a look of its own

**A part that shows a look other than the user's, a theme's preview, a window in a tour or a wall of demos each in a theme, gets a theme store of its own, on a wrapper element.** `createThemeStore({ root, themes, styles, persistPref: false })` paints that element alone, and everything inside it is drawn in the store's theme and style whatever the page wears: its tokens, its `dark:` classes and its style's look, and a window nested inside takes its own store's in turn. The wrapper is drawn as the page is, its background, text and font from its own theme, and a menu or a dialog opened inside it wears its look too, though it opens over the whole page. Build the box inside the wrapper, from a `Pane` or a `Frame`: classes on the wrapper itself answer to the page around it.

Keep the user's own look on everything they work in. A look of its own is for showing a look, not for choosing one on the user's behalf.

**Do**

Wrap the part in an element, give that element its own store and a `ThemeProvider` over it, and set the look with the store's `setPref`.

**Don't**

Put `.dark`, `data-style` or a palette's tokens on an element by hand. Its tokens, its `dark:` classes and the menus opened from it then each follow a different look.

## A surface on someone else's page

A widget or an extension that draws inside another site's page imports `@orz/ui/theme.css` rather than `styles.css`, so it brings the tokens without restyling the host, and creates its store with `root` set to its own element: the store then paints that element alone, two stores on one page never repaint each other, and the host's own `.dark` stops at the widget's edge.

## On each platform

- **Pointer.** The menu sits in the top bar, at the trailing edge, as on this site.
- **Touch.** Auto is the default mode, so a phone that switches to dark at sunset takes the app with it. Use AMOLED makes the dark background true black, which an OLED phone shows by turning those pixels off.

## In the demos

- [Gallery](/ui/demos/gallery/index.md): Pick a theme from the ThemeMenu tile or the top bar's: every tile repaints from the one store, and none carries a colour of its own.
- [Settings](/ui/demos/settings/index.md): Appearance picks the theme and the terminal theme from the same menus as this site's top bar, and Edit… opens the theme editor.
