implement
API

API

Every export of @implementjs/mode-watcher, in one place.

createModeManager

Creates the ModeManager that owns the mode. mode, userPrefersMode, systemPrefersMode, and theme are readables; setMode, toggleMode, resetMode, and setTheme change them. Usually created at module scope so any code can flip the mode. Nothing reaches the DOM until a mounted ModeWatcher starts it.

PropTypeDefaultDescription
defaultMode"dark" | "light" | "system""system"The mode to use until the visitor picks one.
defaultThemestring""The data-theme value to use until one is set. Empty means no attribute.
darkClassNamesstring[]["dark"]Classes put on the html element in dark mode.
lightClassNamesstring[][]Classes put on the html element in light mode.
themeColors{ dark: string; light: string }Keeps meta[name=theme-color] in step with the mode.
modeStorageKeystring"implement-mode"localStorage key holding the picked mode.
themeStorageKeystring"implement-theme"localStorage key holding the theme.
disableTransitionsbooleantrueSuppresses CSS transitions while the mode swaps, so colors don't smear.
trackbooleantrueWhether to follow prefers-color-scheme as it changes. False keeps the first reading.

ModeWatcher

Mounted once at the root. Renders a blocking script into the head so the stored mode lands on the html element before the first paint, then applies the manager's mode — classes, color-scheme, data-theme, and the theme-color meta — for as long as it stays mounted. Takes every createModeManager option, applying them to the manager it is given or to the one it makes.

PropTypeDefaultDescription
managerModeManagerA manager from createModeManager(). Omitted, the component creates a private one.
injectScriptbooleantrueWhether to add the blocking script. False when it is injected elsewhere with createInitialModeExpression.
noncestringnonce for the injected script, for pages under a Content Security Policy.
Data attributeValue
[class]darkClassNames or lightClassNames, on the html element
[style]color-scheme: dark | light, on the html element
[data-theme]The current theme, when it is not empty

createInitialModeExpression

Returns the source of the blocking script ModeWatcher injects, for inlining into an index.html or injecting from a server hook. Takes defaultMode, defaultTheme, darkClassNames, lightClassNames, themeColors, modeStorageKey, and themeStorageKey — pass the same values the manager has, or the page corrects itself after it loads.