# State & changes

Every stateful component can be controlled or uncontrolled. Pass `value` (or `checked`, `pressed`, `open`) to own the state yourself, or a `defaultValue` and let the component keep it. Either way the matching callback — `onValueChange`, `onCheckedChange`, `onOpenChange` — tells you about each change. `onChange` stays the native DOM event.

```tsx
const [tab, setTab] = useState("account");

<Tabs value={tab} onValueChange={setTab}>…</Tabs>   // controlled
<Tabs defaultValue="account">…</Tabs>                // uncontrolled
```

## Why it changed

Each callback gets a second argument, `details`: `{ reason, event, cancel(), isCanceled }`. The `reason` is a string union specific to the component — Tabs reports `"trigger-press"` or `"keyboard"`, Dialog reports `"close-button"`, `"escape-key"`, `"outside-press"` or `"programmatic"` — so a handler can treat a click differently from a key press, or keep programmatic changes out of analytics. `event` is the DOM event behind the change, when there is one. Each component's reasons are listed in its API table, typed as `ChangeDetails<Reason>`.

```tsx
<Select
  label="Plan"
  onValueChange={(plan, { reason }) => {
    // reason: "item-press" | "keyboard" | "typeahead"
    track("plan_changed", { plan, via: reason });
  }}
>
  …
</Select>
```

It's purely additive: a callback that takes one argument never sees it.

## Cancelling a change

The component calls your callback *before* it updates anything. Call `details.cancel()` and it keeps its current state and skips side effects such as closing a menu.

```tsx
import { DropdownMenu, MenuItem } from "@kernelui-lib/react";

<DropdownMenu
  render={<Button>Edit</Button>}
  onOpenChange={(open, details) => {
    // Keep the menu open while someone works through it with the keyboard.
    if (!open && details.reason === "item-keyboard") details.cancel();
  }}
>
  <MenuItem onSelect={bold}>Bold</MenuItem>
  <MenuItem onSelect={italic}>Italic</MenuItem>
</DropdownMenu>
```

A controlled component is already yours to keep: not updating your state leaves the old value in place, and `cancel()` just says so — check `details.isCanceled` if one handler both cancels and sets state.

```tsx
<Dialog
  open={open}
  title="Edit profile"
  onOpenChange={(next, details) => {
    // A stray click on the backdrop shouldn't throw away unsaved edits.
    if (dirty && details.reason === "outside-press") {
      details.cancel();
      return;
    }
    setOpen(next);
  }}
>
  …
</Dialog>
```

Where the platform owns the change, cancelling does the closest honest thing. A native `popover` 's light-dismiss can't be refused, so a cancelled Popover or DropdownMenu close re-shows the panel before the next paint, without replaying its entrance. A cancelled Sheet drag-dismiss springs back to where it rested. A TagInput removal is reported once the chip's exit transition has played, so cancelling it brings the chip back; a paste or typed separator that adds several tags is one change, in both packages.

## Web Components

The custom elements carry the same reasons in `detail.reason`, with one rule for every value control, the platform's `beforeinput` / `input` pairing: a cancelable `beforevaluechange` fires first, with the proposed value, and `event.preventDefault()` on it vetoes the change. Otherwise the element commits, then fires `valuechange` with the same detail, and `change` too where it has one, so a handler can read the element's own state. Dialog and CommandPalette ask with a cancelable `cancel` (the native dialog's own name for "about to close"); Popover, DropdownMenu and Accordion items with `beforetoggle`.

```html
<kernel-tabs default-value="account">…</kernel-tabs>
<kernel-switch>Wi-Fi</kernel-switch>
<script type="module">
  const tabs = document.querySelector("kernel-tabs");
  // Before the tab changes: veto it.
  tabs.addEventListener("beforevaluechange", (event) => {
    const { value, reason } = event.detail;   // reason: "trigger-press" | "keyboard" | …
    if (value === "billing" && !confirmLeave()) event.preventDefault();
  });
  // After it changed (same detail, not cancelable).
  tabs.addEventListener("valuechange", (event) => track(event.detail.value));

  const wifi = document.querySelector("kernel-switch");
  wifi.addEventListener("beforevaluechange", (event) => {
    if (!event.detail.checked && !confirmDisconnect()) event.preventDefault();
  });
  // After the flip: the element already shows the new state.
  wifi.addEventListener("change", () => save(wifi.hasAttribute("checked")));
</script>
```

## Filtering

Combobox and CommandPalette filter with a ranked fuzzy match: the characters you type have to appear in order, not together, and results that match at the start, at word starts, or in one unbroken run rise to the top. Case and accents are ignored, and the matched characters are underlined. Both take a `filter` prop to replace it, and the matcher is exported for your own lists.

```tsx
import { fuzzyFilter, fuzzyScore } from "@kernelui-lib/react";

fuzzyScore("nwfl", "New file");
// → { score: 16.5, ranges: [[0, 1], [2, 3], [4, 5], [6, 7]] }

fuzzyFilter(commands, query, (command) => [command.label, ...command.keywords]);
// → matches only, best first, each with { item, score, ranges, field }
```
