---
title: PreferenceController
description: 'One value from a fixed list, written as an attribute on an element, saved across visits and kept in step across tabs.'
order: 25
---

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

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

# PreferenceController

<p class="docs-lede">
	One value from a fixed list, written as an attribute on an element, saved across visits and kept in step across
	tabs.
</p>

Reach for it for a saved choice that lives as an attribute on the page: density, a layout, a mode. For light, dark and system, use [ColorSchemeController](/docs/controllers/color-scheme), which is built on it.

## Import

```ts
import {
	PreferenceController,
	createPreferenceController,
	type PreferenceChange,
	type PreferenceChangeReason,
	type PreferenceSetOptions,
} from '@ecopages/radiant-ui/controllers';
```

## Try it

Choose a density. The box shows the attribute the controller wrote on it, and the choice is saved: reload the page and it comes back. Open the page in a second tab and choose there, and this one follows.

<PrimitiveExample name="preference">
	<div data-box>data-density="comfortable"</div>
	<button type="button" value="compact">Compact</button>
	<button type="button" value="comfortable">Comfortable</button>
	<button type="button" value="spacious">Spacious</button>
</PrimitiveExample>

```html
<div data-example="preference">
	<div data-box>data-density="comfortable"</div>
	<button type="button" value="compact">Compact</button>
	<button type="button" value="comfortable">Comfortable</button>
	<button type="button" value="spacious">Spacious</button>
</div>
```

```ts
import { PreferenceController } from '@ecopages/radiant-ui/controllers';

const DENSITIES = ['compact', 'comfortable', 'spacious'] as const;

export function mount(root: HTMLElement): () => void {
	const box = root.querySelector<HTMLElement>('[data-box]')!;
	const buttons = [...root.querySelectorAll('button')];

	const density = new PreferenceController({
		values: DENSITIES,
		defaultValue: 'comfortable',
		storageKey: 'radiant-ui-docs:example-density',
		attribute: 'data-density',
		getTarget: () => box,
		onApply: (value) => {
			box.textContent = `data-density="${value}"`;
			for (const button of buttons) {
				button.setAttribute('aria-pressed', String(button.value === value));
			}
		},
	});
	density.attach();

	const listeners = new AbortController();
	for (const button of buttons) {
		button.addEventListener(
			'click',
			() => {
				const value = DENSITIES.find((candidate) => candidate === button.value);
				if (value) {
					density.set(value);
				}
			},
			{ signal: listeners.signal },
		);
	}
	return () => {
		listeners.abort();
		density.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).

## Config

| Option         | Description                                                                                                                                                                 |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `values`       | Every value the preference can take. A saved value outside the list is replaced by `defaultValue`.                                                                          |
| `defaultValue` | The value when nothing is saved, or what is saved is not in `values`.                                                                                                       |
| `storageKey`   | The `localStorage` key the value is saved under.                                                                                                                            |
| `attribute`    | The attribute the value is written to on the target, such as `data-density`.                                                                                               |
| `getTarget`    | The element that carries the attribute, resolved on every `attach()`. Default `document.documentElement`.                                                                   |
| `onChange`     | Called with a pending change, `{ value, previous, reason }`, before it is applied, from `set()`, from another tab's save and from another controller on the page. Return `false` to keep the current value.     |
| `onApply`      | Called with the value and the target after the attribute is written, on `attach()` and after every accepted change.                                                         |

`reason` is `user` (the default of `set()`), `restore` (a value restored from somewhere other than storage, such as a shared link), `storage` (another tab saved a new value) or `page` (another controller on this page wrote a new value to the same target and attribute).

## Methods

| Method                           | Description                                                                                                                                                                                                           |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `get()`                          | The current value; `defaultValue` before `attach()`.                                                                                                                                                                  |
| `set(value, { reason?, save? })` | Offers the change to `onChange`, then writes the attribute and saves the value. `save: false` applies it for this page only. Returns whether the value changed: `false` when it is the current one, when `onChange` returned `false` or when the controller is not attached. |

## Behavior

- `attach()` reads the saved value and writes the attribute, so it agrees with a boot script that wrote the attribute before the page loaded.
- A save in another tab arrives through the `storage` event and goes through `onChange` with `reason: 'storage'`, without saving again. Clearing storage in another tab brings back `defaultValue`.
- Two controllers on one page with the same target and attribute, such as a toggle in the header and another in a drawer, stay in step: when one writes a value from the list, the other adopts it through `onChange` with `reason: 'page'`, without saving. A value outside the list written to the attribute is ignored.
- A saved value that is not in `values`, such as one an older version of the site wrote, gives `defaultValue`.
- Blocked storage (a private window, a disabled setting) is not an error: the value is kept in memory for this page and not saved.

## Lifecycle

`attach()` resolves the target, reads the saved value, writes the attribute and starts listening for other tabs; attaching again changes nothing. `destroy()` stops listening and leaves the attribute and the saved value in place, because they belong to the document: a toggle that disconnects does not reset the page. `set()` before `attach()` or after `destroy()` does nothing.

With a host, `createPreferenceController(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 writes one attribute and sets no ARIA. The control that changes the value is yours: give it a name and show the current choice, with `aria-pressed` on toggle buttons as the example does, `aria-checked` on radios, or the selected option of a select. A change made in another tab arrives through `onChange` and `onApply`, so update that state there too.

## Protected hooks

None. Change behavior through the config callbacks.
