---
title: ColorSchemeController
description: '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.'
order: 26
---

import { PrimitiveExample } from '@/components/primitive-example';

export const config = {
	dependencies: {
		components: [PrimitiveExample],
		scripts: ['./color-scheme.script.ts'],
	},
};

# ColorSchemeController

<p class="docs-lede">
	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.
</p>

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](/docs/getting-started/theming#dark-mode). It is a [PreferenceController](/docs/controllers/preference) with the values `system`, `light` and `dark`.

## Import

```ts
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.

<PrimitiveExample name="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>
</PrimitiveExample>

```html
<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>
```

```ts
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](/docs/controllers/overview#how-the-examples-run).

## For the whole page

A site switch targets `<html>`, the default, and pairs the controller with [`colorSchemeBootScript`](/docs/helpers/color-scheme) inline in `<head>`, with the same options, so the saved scheme applies before first paint and before any module loads:

```ts
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-scheme` on the target, `light dark` for `system` so the page follows the system with no script, otherwise `light` or `dark`. It then toggles the classes, sets `attribute` and calls `apply` with the resolved scheme.
- While `system` is chosen, a change of `prefers-color-scheme` updates the classes, the attribute and `apply`.
- A choice saved in another tab arrives through `onChange` with `reason: 'storage'` and is applied. A saved value other than `system`, `light` or `dark`, and blocked storage, give `system`.
- A shared link's override, such as `?mode=dark`, shows for the visit with `set(value, { reason: 'restore', save: false })`; the boot script reads it with its `queryKey` option. Return `false` from `onChange` for `reason: '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](/docs/controllers/bind-controller).

## 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](/docs/actions/cycle-toggle), 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`.
