Skip to content

Light, dark and less motion

The theme button on this site now just switches between light and dark, with a menu for following your system and for turning the animations off, and how reduced motion became a setting of the site and not only of your computer.

The button in the top right corner of this site used to step through three themes: light, then dark, then whatever your system uses. That's three clicks to get back where you started, and the third one often did nothing you could see, because "system" was already light or dark.

Yago's site does it better. A click switches between light and dark, and the rest is a right-click away. So I did the same, and added a setting I'd wanted for a while: turning the animations off, on this site, without changing anything on your computer.

What the button does now

  • A click switches between light and dark, starting from whatever's showing. Until you click, the site follows your system.
  • A right-click, or ↓ when the button has focus, opens a menu: Light, Dark, System, and Reduce motion.
  • Hovering over it says so, in a tooltip: "Toggle theme · right-click or ↓ for more".

The keyboard shortcut, T T, and the toggle in the ⌘K menu do the same as a click.

One click, two themes

Switching is the theme the page isn't showing, whatever made it show the one it is:

ts
/** * The other one of light and dark, from whatever's showing, even when that * came from the OS. Following the OS again is in the theme menu. */export function toggleTheme() {  setTheme(document.documentElement.classList.contains("dark") ? "light" : "dark")}

The site's theme is a dark class on <html>, so that's the only thing worth asking. If you've never clicked, it was set from your system before the page drew anything, by a few lines in the <head>:

ts
export const themeScript = `(() => {  let choice = "system"  try {    const stored = sessionStorage.getItem("theme")    if (stored === "light" || stored === "dark") choice = stored  } catch {}  const dark = choice === "system"    ? !matchMedia("(prefers-color-scheme: light)").matches    : choice === "dark"  document.documentElement.classList.toggle("dark", dark)  document.documentElement.dataset.themeChoice = choice})()`

The choice also goes on <html>, as data-theme-choice, so the button can show the right icon before React has loaded. All three icons are in the HTML, and CSS shows one:

tsx
<SunIcon className="hidden in-data-[theme-choice=light]:block" /><MoonIcon className="hidden in-data-[theme-choice=dark]:block" /><SunMoonIcon className="hidden in-data-[theme-choice=system]:block" />

The half sun means you're following your system. Going back to that is in the menu, as no number of clicks gets you there now.

The menu

The menu is shadcn's context menu, on Base UI. A context menu opens where you right-click, and on a phone, where you press and hold. Its trigger is the theme button itself:

bash
pnpm dlx shadcn@latest add context-menu
tsx
<ContextMenu>  <ContextMenuTrigger    render={<Button aria-label="Toggle light and dark" onClick={toggleTheme} />}  >    {icons}  </ContextMenuTrigger>  <ContextMenuContent className="w-40">    <ContextMenuGroup>      <ContextMenuLabel>Theme</ContextMenuLabel>      <ContextMenuRadioGroup value={choice} onValueChange={setTheme}>        <ContextMenuRadioItem value="light">          <SunIcon /> Light        </ContextMenuRadioItem>        <ContextMenuRadioItem value="dark">          <MoonIcon /> Dark        </ContextMenuRadioItem>        <ContextMenuRadioItem value="system">          <SunMoonIcon /> System        </ContextMenuRadioItem>      </ContextMenuRadioGroup>    </ContextMenuGroup>    <ContextMenuSeparator />    <ContextMenuCheckboxItem      checked={reducedMotion}      onCheckedChange={setReducedMotion}    >      Reduce motion    </ContextMenuCheckboxItem>  </ContextMenuContent></ContextMenu>

Radio items for the theme, as it's one of three, and a checkbox for motion, which is on or off. The menu ticks whichever is current.

Right-clicking from the keyboard

A menu you can only reach with a mouse is half a menu. Windows and Linux keyboards have a menu key, and Shift F10 does the same, but a Mac has neither.

Yago's site opens the menu with ↓ as well, which is what a menu button does anyway. The context menu has no way to be opened from code, but it opens wherever it's right-clicked. So ↓ right-clicks the button, just below its corner, and the menu drops down from there:

ts
function openMenu(event: KeyboardEvent<HTMLButtonElement>) {  if (event.key !== "ArrowDown") return  event.preventDefault()  const { left, bottom } = event.currentTarget.getBoundingClientRect()  event.currentTarget.dispatchEvent(    new MouseEvent("contextmenu", {      bubbles: true,      cancelable: true,      button: 2,      clientX: left,      clientY: bottom + 4,    })  )}

From there it's a normal menu: arrows to move, Enter to pick, Esc to close and go back to the button.

Nobody guesses a right-click, so the button says so. Its tooltip is shadcn's tooltip around the same button, with the arrow as a key:

tsx
<TooltipContent>  Toggle theme · right-click or <Kbd>↓</Kbd> for more</TooltipContent>

A screen reader gets the same in the button's label: "Toggle light and dark. Theme: system. Press down arrow for more options".

Reduce motion, on the site

Your computer can ask websites for less motion. On a Mac it's in Accessibility, Display, Reduce motion, and websites see it as the prefers-reduced-motion media query. This site has always listened: no typing headings, no cards fading in, numbers that don't count up, no snow.

But that's a setting for everything on your computer. You might want this one site to keep still, or to see the animations on a laptop where you've turned them off everywhere else. Now the menu can do either.

One attribute on <html>

Before, everything that moved asked the media query itself: CSS, a React hook, three canvas effects, the animated numbers. Now there's one answer, on <html>, set before the page draws anything, like the theme:

ts
// <html> always says which motion the page uses, "reduce" or "full", so CSS// needs no media query: a saved choice wins, otherwise the OS setting.// Without JavaScript there's no attribute, and the page stays stillexport const motionScript = `(() => {  let reduce = matchMedia("(prefers-reduced-motion: reduce)").matches  try {    const stored = sessionStorage.getItem("motion")    if (stored === "reduce" || stored === "full") reduce = stored === "reduce"  } catch {}  document.documentElement.dataset.motion = reduce ? "reduce" : "full"})()`

Ticking the box in the menu changes the attribute, and remembers the choice. If the new setting is the same as your system's, it forgets it instead, so the site follows your system again:

ts
export function setReducedMotion(reduce: boolean) {  document.documentElement.dataset.motion = reduce ? "reduce" : "full"  try {    if (reduce === systemReduces()) sessionStorage.removeItem("motion")    else sessionStorage.setItem("motion", reduce ? "reduce" : "full")  } catch {    // Storage is unavailable; the choice lasts until the page reloads  }  window.dispatchEvent(new Event("motionchange"))}

Both settings are kept in session storage, not local storage. They last while you're browsing the site, and a new visit starts from your system again. Your system settings are the better long-term answer, and the site shouldn't quietly overrule them next month.

CSS

Tailwind's motion-safe: and motion-reduce: are media queries. In Tailwind 4, a custom variant with the same name replaces the built-in one, so they now read the attribute instead:

css
@custom-variant motion-safe {  &:where([data-motion="full"], [data-motion="full"] *) {    @slot;  }}@custom-variant motion-reduce {  &:where(:root:not([data-motion="full"]), :root:not([data-motion="full"]) *) {    @slot;  }}

Every motion-reduce:animate-none in the components carried on working without a change. motion-reduce is "anything but full", so a page without the attribute, because JavaScript didn't run, keeps still.

The CSS I wrote by hand had media queries too. Each became the attribute, using nesting:

css
html {  /* Before: @media (prefers-reduced-motion: no-preference) */  &[data-motion="full"] {    scroll-behavior: smooth;  }}
.reading-progress {  display: none;
  [data-motion="full"] & {    /* The scroll-driven progress bar */  }}

The theme change's diagonal wipe and the page cross-fades are view transitions. They're drawn on <html>, so their selectors go on html itself:

css
html[data-motion="full"][data-theme-transition]::view-transition-new(root) {  mask: url("./theme-reveal-mask.svg") top left / 0 no-repeat;  animation: theme-reveal 1.5s both;}

JavaScript

The React hook that components used to ask the media query now asks the attribute, and listens for the menu as well as the system:

ts
export const useReducedMotion = (): boolean =>  useSyncExternalStore(subscribeToMotion, getReducedMotion, () => false)
ts
export function getReducedMotion() {  return document.documentElement.dataset.motion !== "full"}
export function subscribeToMotion(callback: () => void) {  const query = matchMedia("(prefers-reduced-motion: reduce)")  // Without a choice of their own, the page follows the OS as it changes  const onSystemChange = () => {    if (hasChoice()) return    document.documentElement.dataset.motion = query.matches ? "reduce" : "full"    callback()  }  query.addEventListener("change", onSystemChange)  window.addEventListener("motionchange", callback)  return () => {    query.removeEventListener("change", onSystemChange)    window.removeEventListener("motionchange", callback)  }}

The snow, glitch and fire effects are canvas components from a registry, and each keeps a MediaQueryList around: it reads matches, and listens for change. Rather than rewrite them, they get something shaped the same:

ts
export function reducedMotionQuery() {  const unsubscribes = new Map<() => void, () => void>()  return {    get matches() {      return getReducedMotion()    },    addEventListener(_type: "change", listener: () => void) {      unsubscribes.set(listener, subscribeToMotion(listener))    },    removeEventListener(_type: "change", listener: () => void) {      unsubscribes.get(listener)?.()      unsubscribes.delete(listener)    },  }}
ts
// Before: window.matchMedia("(prefers-reduced-motion: reduce)")const motionQuery = reducedMotionQuery()

One line changed in each, and the snow stops falling when you tick the box.

Motion, which draws my signature, has its own useReducedMotion, and that only knows about the system. The signature and the typing headline use the site's hook instead.

The map was stuck in the dark

Testing all this found a bug on Stats. The flight map from the last post stayed dark after switching to light.

The map component works out the theme from a class on <html>: dark is dark, and light is light. This site only ever has dark, or nothing. So after a switch to light the map saw no theme at all, and kept the one it had. It takes the theme as a prop as well, so it gets the site's instead:

tsx
const siteTheme = (): "light" | "dark" =>  document.documentElement.classList.contains("dark") ? "dark" : "light"
const theme = useSyncExternalStore(subscribeToDark, siteTheme, () => "dark" as const)
<Map theme={theme} />

subscribeToDark watches the class with a MutationObserver, so the map changes the moment the page does.

What I learnt

  • Two states make a better button than three. The third one is better as a choice in a menu than as a click that seems to do nothing.
  • Say when there's more. A right-click menu nobody knows about isn't there. A tooltip fixed that.
  • One source of truth for motion. An attribute on <html> meant CSS, React and canvas code all agree, and none of them needed to know where the setting came from.
  • Make the fallback the safe one. Without JavaScript, nothing moves.
  • Shape-compatible beats rewritten. Something that looks like a MediaQueryList changed one line in each canvas effect, not their logic.