sdxc

Type to search, or start from one of these:

[ @sdxc/ui/mixins ]

themeToggle

Switches a theme switch control's page-wide scheme.

import { themeToggle } from "@sdxc/ui/mixins";

Usage

Turns a theme switch control into the source of a page-wide color-scheme change, switching <html> and persisting the mode to a cookie together, every time, so <html>'s class list stays the only source of truth.

Signature

themeToggle(options?: ThemeToggle.Options): MixinDescriptor<HTMLElement>

Returns a mixin descriptor for a theme switch control's mix prop.

Parameters

ParameterTypeDescription
options?ThemeToggle.OptionsCookie name to persist the mode under; see ThemeToggle.Options. Optional — when a call site omits it (themeToggle()), the runtime passes its trailing current-props argument in its place, so that value is reset back to an empty options object.

Examples

<div id="theme-switch" mix={[themeToggle()]}>
	<button commandfor="theme-switch" command="--ui-theme-light">{t("theme.light")}</button>
	<button commandfor="theme-switch" command="--ui-theme-dark">{t("theme.dark")}</button>
	<button commandfor="theme-switch" command="--ui-theme-system">{t("theme.system")}</button>
</div>
// A form-native radio group, still fully functional as a plain form
// submission when JavaScript never runs.
<fieldset mix={[themeToggle()]}>
	<legend>{t("theme.label")}</legend>
	<label><input type="radio" name="theme" value="light" defaultChecked /> {t("theme.light")}</label>
	<label><input type="radio" name="theme" value="dark" /> {t("theme.dark")}</label>
	<label><input type="radio" name="theme" value="system" /> {t("theme.system")}</label>
</fieldset>

The events, constants and types its module publishes, each imported from @sdxc/ui/mixins too.

Event

ThemeChangeEvent

Dispatched on a theme switch control by themeToggle right after a switch, carrying the new mode so a consumer can resync another instance or update <meta name="theme-color"> without reading <html>'s class list.

new ThemeChangeEvent(mode: ThemeToggle.Mode)
PropertyTypeDescription
modereadonly ThemeToggle.ModeThe mode themeToggle just switched <html> to.
Interface

ThemeToggle.Options

Configuration accepted by themeToggle.

MemberTypeDescription
cookieName?stringCookie name the active mode persists under. Defaults to "ui:theme" — override only if the consuming app's server reads the cookie back under a different name.
Type

ThemeToggle.Mode

A color scheme themeToggle can switch <html> to: "light" removes .dark/.system for the light palette, "dark" adds .dark, and "system" adds .system to follow prefers-color-scheme.

type ThemeToggle.Mode = "light" | "dark" | "system"

Written by Sergio Xalambrí. Follow @sergiodxa for new packages, or sponsor the work.