Command palette

@yasinsensoy/web

Web · APIs and utilities

Theme

Manages the app's theme: stores the user preference, follows the system preference, syncs across tabs and applies the theme to the <html> element.

26 exports

Live example

Preview

background
foreground
card
card-foreground
popover
popover-foreground
primary
primary-foreground
secondary
secondary-foreground
muted
muted-foreground
accent
accent-foreground
destructive
destructive-foreground
success
success-foreground
warning
warning-foreground
Badge

Code

import { ThemeProvider } from "@yasinsensoy/web";

/* globals.css */
[data-theme="markam"] {
  --ui-radius: 0.625rem;
}

// layout.tsx
<ThemeProvider themes={["light", "dark", "markam"]} transition={{ type: "ripple", duration: 900 }}>

Events

  1. Events appear here when you interact with the preview.

Import

import {
  ThemeProvider,
  ThemeView,
  createColorScale,
  createTheme,
  checkContrast,
  themeToCss,
  themeToStyle,
  useTheme,
  getThemeScript,
} from "@yasinsensoy/web";

ThemeProvider

componentClient component

Manages the app's theme: stores the user preference, follows the system preference, syncs across tabs and applies the theme to the <html> element.

It also prevents the wrong theme from flashing on first page load: it adds a small inline script to the server output that applies the theme before the content. You do not need to add anything to <head>. The script is removed from the DOM after hydration; when rendered from scratch on the client it is not added at all (React does not run such scripts and warns). For apps without server output use getThemeScript.

Place it inside <body> in the root layout, outermost around the content. Add suppressHydrationWarning to <html>, because the script changes that element's attributes before React takes over. Use the useTheme hook to change the theme.

Nesting: If a section or page wants a different theme, wrap it in a ThemeProvider too. Since the theme is applied to <html>, the innermost mounted provider wins; when it unmounts (e.g. on leaving the page) the outer one's theme comes back automatically. Dialogs and notifications get the right theme too. useTheme reads the nearest provider.

  • Pinning a page to one theme: pass forcedTheme; the preference is neither read nor written.
  • Giving a section its own preference (e.g. an admin panel): pass a different storageKey. With the same key the user's choice is shared across sections; a choice not in the section's themes list falls back to defaultTheme.
ThemeProvider({ children, disableTransitionOnChange, transition, nonce, ...options }: ThemeProviderProps): JSX.Element

Examples

// app/layout.tsx
import { ThemeProvider } from "@yasinsensoy/web";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <body>
        <ThemeProvider themes={["light", "dark", "ocean"]} darkThemes={["dark", "ocean"]}>
          {children}
        </ThemeProvider>
      </body>
    </html>
  );
}

// app/dashboard/layout.tsx — the panel's own themes and preference
<ThemeProvider themes={["light", "corporate"]} storageKey="panel-theme">{children}</ThemeProvider>

// app/presentation/page.tsx — always dark
<ThemeProvider forcedTheme="dark">…</ThemeProvider>

ThemeView

componentClient component

Shows theme-dependent content (theme picker label, selected button, sun/moon icon) correctly on first page load too, with no server/client difference (hydration mismatch) or flashing.

The server cannot know the user's preference, so useTheme returns undefined on the first render and a label using it directly first shows the wrong theme name and then changes. ThemeView instead renders the content once per theme on the first render and hides, via CSS, the ones not matching the theme the inline script wrote to <html>. After hydration only the current theme's content remains; that copy is not recreated and keeps its state.

Content is wrapped in a <span> with display: contents; it does not affect layout. Do not use it where a <span> is not allowed, such as a table row.

ThemeView({ children, resolved }: ThemeViewProps): JSX.Element[]

Examples

"use client";
import { Select, ThemeView, useTheme } from "@yasinsensoy/web";

const labels: Record<string, string> = { light: "Light", dark: "Dark", system: "System" };

export function ThemePicker() {
  const { themes, setTheme } = useTheme();
  return (
    <ThemeView>
      {(theme) => (
        <Select
          aria-label="Theme"
          value={theme}
          onValueChange={(name) => name && setTheme(name)}
          items={themes.map((name) => ({ value: name, label: labels[name] ?? name }))}
        />
      )}
    </ThemeView>
  );
}

// Icon based on the applied theme
<ThemeView resolved>{(theme) => <Icon icon={theme === "dark" ? "moon" : "sun"} />}</ThemeView>

50–950 shade scale of a color (equal perceptual steps in OKLCH). The color itself is placed on the step closest to its lightness; the other steps are derived from there. Chroma is clipped to fit in sRGB.

createColorScale(color: string): ColorScale

Examples

const blue = createColorScale("#2563eb");
blue[100]; // "oklch(0.936 0.032 264.1)"

createTheme

function

Generates all color tokens of the light and dark themes from a single primary color: grays such as background, card, border and muted text are slightly tinted toward the primary; the text color on filled colors is chosen by contrast; for the dark theme colors are lightened enough to stay readable. The result also includes a WCAG contrast check of important pairs.

Pure function; runs on the server. Convert the output to CSS with themeToCss or pass it to a container as style.

createTheme(options: CreateThemeOptions): GeneratedTheme

Examples

const theme = createTheme({ primary: "#2563eb", neutralTint: 0.4, radius: 0.5 });
const css = themeToCss(theme, { name: "brand" });
theme.contrast.filter((c) => !c.pass); // weak pairs

WCAG contrast of important text/background pairs in theme tokens. At least 4.5 is required for text pairs and at least 3 for the primary against the background. Can also be used to check tokens you wrote by hand (values are oklch() or strings parseColor understands).

checkContrast(tokens: ThemeTokens, scheme: "light" | "dark"): ContrastCheck[]

themeToCss

function

Converts a createTheme result into text to paste into the project's CSS file.

themeToCss(theme: GeneratedTheme, options?: ThemeToCssOptions): string

Examples

themeToCss(theme);                    // :root { … }  .dark { … }
themeToCss(theme, { name: "brand" }); // [data-theme="brand"] { … } [data-theme="brand-dark"] { … }

themeToStyle

function

Converts theme tokens into variables for a container's style prop; to draw part of the page (e.g. a preview) with that theme.

themeToStyle(tokens: ThemeTokens, radius?: string): Record<string, string>

Examples

`<div style={themeToStyle(theme.light, theme.radius)}>…</div>`

useTheme

function

Reads and changes the current theme. Must be used inside ThemeProvider.

theme and resolvedTheme return undefined on the server and during the first hydration, because the user preference is only known in the browser. Render UI that displays the selected theme (theme picker label, pressed button, sun/moon icon) with ThemeView; then the right theme shows on first page load too, with no server/client mismatch.

useTheme(): ThemeContextValue

Examples

"use client";
import { useTheme } from "@yasinsensoy/web";

export function ThemeToggle() {
  const { resolvedTheme, setTheme } = useTheme();
  return (
    <button onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}>
      Toggle theme
    </button>
  );
}

Returns the source of the inline script that applies the theme before the page paints.

ThemeProvider adds this script to the server output itself; apps rendered on the server such as Next.js do not need this function. Use it only in apps without server output (e.g. a Vite single-page app) to put the text in a <script> tag in index.html.

getThemeScript(config?: ThemeConfig): string

ThemeConfig

interface

Theme configuration. ThemeProvider uses these options both for its own state and for the anti-flicker script it embeds in the page.

NameTypeDefaultDescription
themes?readonly string[]["light", "dark"]Available theme names. "system" is not listed here; it is enabled separately with enableSystem.
darkThemes?readonly string[]["dark"]Themes with a dark color scheme. While one of them is active, the dark class is added to <html> and color-scheme: dark is applied.
defaultTheme?string"system"` (`"light"` if `enableSystem` is off)Theme used when there is no stored preference.
enableSystem?booleantrueEnables the "system" option. When selected, the OS light/dark preference is followed and the theme updates instantly when it changes.
storageKey?string"ui-theme"Key under which the user preference is stored in localStorage.
forcedTheme?stringWhen given, the user preference is ignored and this theme is always applied. Useful for pinning certain pages to a single theme.

Names of the color tokens in the createTheme output (--ui-<name>).

type ThemeTokenName = "background" | "foreground" | "card" | "card-foreground" | "popover" | "popover-foreground" | "primary" | "primary-foreground" | "secondary" | "secondary-foreground" | "muted" | "muted-foreground" | "accent" | "accent-foreground" | "destructive" | "destructive-foreground" | "success" | "success-foreground" | "warning" | "warning-foreground" | "border" | "input" | "ring"

Token values of a color scheme (light or dark); oklch() strings.

type ThemeTokens = Record<ThemeTokenName, string>

Steps of the shade scale (same names as Tailwind).

type PaletteStep = 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 950

50–950 shade scale of a color; oklch() strings.

type ColorScale = Record<PaletteStep, string>

createTheme options.

NameTypeDefaultDescription
primarystringPrimary (brand) color; a hex, rgb, hsl or oklch string CSS understands. Used as is in the light theme; lightened enough to stay readable in the dark theme (see primaryDark).
primaryDark?stringPrimary color in the dark theme. Derived from primary when omitted.
neutralTint?number0.3How much the grays (background, border, muted text) are tinted toward the primary color: 0 is pure gray, 1 clearly tinted.
neutralHue?numberHue of the grays (oklch degrees, 0–360). Defaults to the primary color's hue; 285 (the library default) when the primary is gray.
accent?"neutral" | "primary""neutral"Hover and selected item background (accent) color. - "neutral": gray (the library default). - "primary": a very light (dark in the dark theme) shade of the primary.
destructive?stringDanger color (delete, error). Defaults to the library's red.
success?stringSuccess color. Defaults to the library's green.
warning?stringWarning color. Defaults to the library's yellow.
radius?number | string0.625Corner radius (--ui-radius): a number is rem (0.5), a string is written as is ("8px").

ContrastCheck

interface

WCAG contrast result of a text/background pair.

NameTypeDescription
scheme"light" | "dark"Which theme: light or dark.
foregroundThemeTokenNameText token.
backgroundThemeTokenNameBackground token.
rationumberContrast ratio (1–21).
minnumberMinimum required ratio: 4.5 for text (WCAG AA), 3 for the primary color against the background (non-text element such as a button border).
passbooleanratio >= min.

Result of createTheme.

NameTypeDescription
lightThemeTokensLight theme tokens.
darkThemeTokensDark theme tokens.
radiusstring--ui-radius value.
scaleColorScale50–950 shade scale of the primary color.
contrastContrastCheck[]Contrast check of important text/background pairs, for both themes.

themeToCss options.

NameTypeDefaultDescription
name?stringTheme name. When given, [data-theme="name"] (light) and [data-theme="name-dark"] (dark) blocks are written; add them to ThemeProvider's themes and darkThemes lists. When omitted, the default light and dark themes are overridden (:root and .dark).
scale?booleanfalseAlso write the primary color's shade scale (--ui-primary-50 … --ui-primary-950) and register it with Tailwind (for classes like bg-primary-100).

Extra options for ThemeContextValue.setTheme.

NameTypeDescription
transition?ThemeTransitionAnimation for this change; overrides the provider's transition.
origin?ThemeTransitionOriginOrigin of spreading animations (an element, a click event or a coordinate). Defaults to the last clicked spot, or the focused element if there is none; you rarely need to pass it.

Return value of the useTheme hook.

NameTypeDescription
themestring | undefinedThe selected theme; may be "system". Returns undefined on the server and during the first hydration because the user preference is not known yet (returns forcedTheme if set). Use ThemeView for UI that displays this value; otherwise the wrong theme shows first on page load.
resolvedThemestring | undefinedThe theme actually applied. If "system" is selected it resolves to "light" or "dark". Returns undefined on the server and during the first hydration.
systemTheme"light" | "dark" | undefinedThe OS preference: "light", "dark", or undefined on the server.
themesreadonly string[]Selectable themes. If enableSystem is on, "system" is included at the end.
forcedThemestring | undefinedName of the forced theme, if any.
setTheme(theme: string | ((current: string) => string), options?: SetThemeOptions) => voidChanges the theme and stores the preference. Other open tabs of the same site update instantly. If the provider has a transition, the change is animated, starting from the clicked element.

Props of the ThemeProvider component.

NameTypeDefaultDescription
children?ReactNodeApp content that uses the theme.
disableTransitionOnChange?booleantrueTemporarily disables CSS transitions while the theme changes.
transition?ThemeTransition"none"Animation played when the user changes the theme (useTheme setTheme). Pass a type name ("ripple") or settings with duration and easing ({ type: "ripple", duration: 900 }). - "ripple": like a water drop, spreads in a wave from the clicked element. - "circle": spreads from the clicked element as a sharp circle. - "fade": slow, soft transition. - "wipe": comes down from the top like a curtain. - "blur": changes by blurring. Uses the browser's View Transitions API (smoothness details: ThemeTransitionType). If the chosen theme does not change the appearance (e.g. from dark to "system" that is currently dark), no animation plays. In unsupported browsers and for users who prefer reduced motion the theme changes instantly. A theme changed by the system preference or another tab is applied without animation.
nonce?stringIf you use a Content Security Policy (CSP), the nonce for the inline anti-flicker script and the inline style added for ThemeView.
themes?readonly string[]["light", "dark"]Available theme names. "system" is not listed here; it is enabled separately with enableSystem.
darkThemes?readonly string[]["dark"]Themes with a dark color scheme. While one of them is active, the dark class is added to <html> and color-scheme: dark is applied.
defaultTheme?string"system"` (`"light"` if `enableSystem` is off)Theme used when there is no stored preference.
enableSystem?booleantrueEnables the "system" option. When selected, the OS light/dark preference is followed and the theme updates instantly when it changes.
storageKey?string"ui-theme"Key under which the user preference is stored in localStorage.
forcedTheme?stringWhen given, the user preference is ignored and this theme is always applied. Useful for pinning certain pages to a single theme.

Props of the ThemeView component.

NameTypeDefaultDescription
children(theme: string) => ReactNodeContent to render per theme. Receives the selected (or, with resolved, the applied) theme name.
resolved?booleanfalseWhen true, the theme actually applied is given instead of the selected one: "light" or "dark" while "system" is selected. Use it for appearance-dependent content such as a sun/moon icon.

Animations that can play on theme change.

  • "none": changes instantly.
  • "fade": the new theme slowly appears (soft transition).
  • "ripple": water drop; a drop in the new theme's color falls on the clicked spot and the new theme spreads from there as a single circle. The circle's edge is a rippling water edge; a bright wave crest moves ahead of it and calms as it spreads.
  • "circle": spreads from the clicked element as a sharp-edged circle without rings; the lightest spreading animation.
  • "wipe": the new theme comes down from the top like a curtain.
  • "blur": the old theme blurs while the new one appears over it.

Smoothness: fade and blur only use opacity and filters, so they run on the GPU and at full speed on 120 Hz screens too. ripple, circle and wipe reveal part of the screen by clipping; current Chromium-based browsers also run this clipping on the GPU. In browsers that cannot, the page is repainted every frame and may stay at 60 fps on 120 Hz screens. For the most reliable smoothness use fade.

If the chosen theme does not change the appearance (e.g. switching from dark to "system" that is currently dark), no animation plays.

type ThemeTransitionType = "none" | "fade" | "ripple" | "circle" | "wipe" | "blur"

Detailed settings of a theme transition.

NameTypeDefaultDescription
typeThemeTransitionTypeAnimation type.
duration?numberfade` 500, `ripple` 900 (including the drop's fall), `circle` 550, `wipe` 600, `blur` 500Duration (milliseconds).
easing?stringA soft curve chosen per type.CSS easing curve.

A theme transition: just a type name or detailed settings.

type ThemeTransition = ThemeTransitionType | ThemeTransitionOptions

Origin of spreading animations (ripple, circle): an element (starts from its center), a mouse/touch event or a screen coordinate.

type ThemeTransitionOrigin = Element | { clientX: number; clientY: number; } | { x: number; y: number; }