ColorSchemeController
Saves the choice of system, light or dark and applies it: color-scheme, a class or attribute, and the system scheme while system is chosen.
Reach for it for a light, dark and system switch. Radiant UI's theme colors switch on color-scheme, so setting it is all a scheme needs; see Theming. It is a PreferenceController with the values system, light and dark.
Import
import {
ColorSchemeController,
createColorSchemeController,
type ColorSchemeControllerConfig,
type ColorSchemeState,
} from '@ecopages/radiant-ui/controllers';Try it
This example applies the scheme to the box, not the page, so it leaves the docs theme alone. Choose Dark or Light and the box and its buttons switch colors; System follows your system setting, whatever this page shows. The choice is saved under its own key: reload and it comes back, and a second tab of this page follows a choice made in the first.
Chose system
<div data-example="color-scheme">
<div data-box>
<button type="button" value="system">System</button>
<button type="button" value="light">Light</button>
<button type="button" value="dark">Dark</button>
</div>
<p data-status>Chose system</p>
</div>import { ColorSchemeController } from '@ecopages/radiant-ui/controllers';
import { COLOR_SCHEME_PREFERENCES } from '@ecopages/radiant-ui/helpers';
export function mount(root: HTMLElement): () => void {
const box = root.querySelector<HTMLElement>('[data-box]')!;
const status = root.querySelector('[data-status]')!;
const buttons = [...box.querySelectorAll('button')];
const scheme = new ColorSchemeController({
storageKey: 'radiant-ui-docs:example-color-scheme',
getTarget: () => box,
apply: (resolved) => {
const { value } = scheme.get();
for (const button of buttons) {
button.setAttribute('aria-pressed', String(button.value === value));
}
status.textContent = `Chose ${value}, showing ${resolved}`;
},
});
scheme.attach();
const listeners = new AbortController();
for (const button of buttons) {
button.addEventListener(
'click',
() => {
const value = COLOR_SCHEME_PREFERENCES.find((preference) => preference === button.value);
if (value) {
scheme.set(value);
}
},
{ signal: listeners.signal },
);
}
return () => {
listeners.abort();
scheme.destroy();
};
}mount runs once for each example element on the page, and the function it returns undoes it; see how the examples run.
For the whole page
A site switch targets <html>, the default, and pairs the controller with colorSchemeBootScript inline in <head>, with the same options, so the saved scheme applies before first paint and before any module loads:
import { createColorSchemeController } from '@ecopages/radiant-ui/controllers';
import { colorSchemeBootScript } from '@ecopages/radiant-ui/helpers';
const options = { storageKey: 'theme', attribute: 'data-theme' } as const;
// the <head> of every page, as a blocking inline script
const bootScript = colorSchemeBootScript(options);
// the toggle, a RadiantElement subclass with a `value`
private readonly scheme = createColorSchemeController(this, {
...options,
onChange: ({ value }) => {
this.value = value;
},
});
protected override onConnected(): void {
this.value = this.scheme.get().value;
}This docs site does exactly that: its theme toggle in the header is a ColorSchemeController with attribute: 'data-theme', which Tailwind's dark variant selects on.
Config
| Option | Description |
|---|---|
storageKey | The localStorage key of the saved preference. Default rui-color-scheme. |
preferenceAttribute | The attribute that carries the preference (system, light or dark). Default data-color-scheme. |
classes | The class names toggled for the resolved scheme, { dark, light }. Default dark and light; false writes none. |
attribute | An attribute set to the resolved scheme (light or dark), such as data-theme. None by default. |
getTarget | The element the scheme is written to, resolved on every attach(). Default document.documentElement. |
apply | (resolved, target): applies a marker of the site's own, after color-scheme, classes and attribute are written. Called on attach(), after every accepted change, and when the system scheme changes while system is chosen. |
onChange | Called with a pending change of the preference, { value, previous, reason }, before it is applied, from set() and from another tab's save. Return false to keep the current one. |
Methods
| Method | Description |
|---|---|
get() | { value, system, resolved }: the saved choice, the scheme the system asks for, and the scheme that wins. value is system before attach(). |
set(value, { reason?, save? }) | Offers the change to onChange, then applies and saves it; save: false applies it for this page only. Returns whether the choice changed. Does nothing before attach(). |
Behavior
- Applying a choice sets
color-schemeon the target,light darkforsystemso the page follows the system with no script, otherwiselightordark. It then toggles the classes, setsattributeand callsapplywith the resolved scheme. - While
systemis chosen, a change ofprefers-color-schemeupdates the classes, the attribute andapply. - A choice saved in another tab arrives through
onChangewithreason: 'storage'and is applied. A saved value other thansystem,lightordark, and blocked storage, givesystem. - A shared link's override, such as
?mode=dark, shows for the visit withset(value, { reason: 'restore', save: false }); the boot script reads it with itsqueryKeyoption. ReturnfalsefromonChangeforreason: 'storage'while the override shows, if another tab must not replace it.
Lifecycle
attach() listens for prefers-color-scheme changes, reads the saved choice and applies it; attaching again changes nothing. destroy() stops listening and leaves the scheme, the markers and the saved value in place. With a host, createColorSchemeController(host, config) does the same on connect and disconnect; see bindController.
Accessibility: what the controller does and what you must provide
The controller applies the scheme and sets no ARIA. The switch is yours: a cycle button such as RuiCycleToggle, toggle buttons with aria-pressed as in the example, or a radio group, with a name and the current choice shown. color-scheme also gives form controls and scrollbars the matching browser look.
Protected hooks
None. Change behavior through classes, attribute, apply and onChange.