---
title: "State API"
description: "Every interactive component declares its UI states by name and exposes them per element - el.api.setState('open') / el.api.getState() - for agents, tests, and code."
slug: "state-api"
---

import { DocPage, PageHeader, SkillPanel, Example, ExampleLabel, ExampleHint, ExampleCode, SourceFiles, SourceNote, StatesSection, CodeBlock, Demo, DemoCode, ChangelogEntries, ArchBody, StatsClaim, StatsCards, PageOverlay, DocText, DocLink, H2, SkillField, SkillText, SkillRow, SkillGrid, Variant, ApiPill, Dim, CodeWindow, CodeCard, TableCard, DeclaredStatesTable } from "../../lib/components/index";

<DocPage meta={meta}>

<PageHeader slug="state-api" title="State API" introStyle="max-width:38rem;">
  Interactive components don't just look stateful - they <em>declare</em> their states. Every component that ships a <code>.js</code> file exposes its states by name, so agents, tests, and your own code can drive and observe any documented state without knowing the implementation.
</PageHeader>

<H2>The contract</H2>

<p class="text-sm text-muted-foreground mb-5"> Each component instance binds a tiny API directly on the element. State lives <em>on the element</em> (never in module scope), so twenty components on one page can each hold a different state: </p>

<CodeWindow lang="javascript" title="the shape - any JS component" mb="2.5rem" code={"// the element - df$ selects it (get(0) = the node itself)\nconst el = df$('#confirm').get(0);\n\n// set a declared state by name - throws on unknown names\nel.api.setState('open', { /* optional config */ });\n\n// read it back - always reflects the real UI\nel.api.getState(); // returns { name: 'open', config: { ... }, model: { ... } }\n\n// the markup of a state - the authored HTML, 1:1, with that state applied\nel.api.render();                                  // the current state\nel.api.render({ ...el.api.getState(), name: 'default' }); // any declared state"} />

<p class="text-sm text-muted-foreground mb-5"> Four guarantees, verified by <DocLink href="https://github.com/kyr0/defuss-shadcn/blob/main/scripts/verify.ts" target="_blank">the build's verifier</DocLink> for every component: </p>

<div class="grid grid-cols-auto gap-4 mb-10">
  <div style="border:1px solid var(--border);border-radius:var(--radius-xl);padding:1.25rem;">
    <p class="text-sm font-medium mb-2" style="margin-top:0;">Declared, not implied</p>
    <p class="text-sm text-muted-foreground" style="margin-bottom:0;"> Each component lists its states as names (<code>const dialogStates = ['default', 'open']</code>) - <code>default</code> first. Unknown names throw with the supported list. </p>
  </div>
  <div style="border:1px solid var(--border);border-radius:var(--radius-xl);padding:1.25rem;">
    <p class="text-sm font-medium mb-2" style="margin-top:0;">Honest reads</p>
    <p class="text-sm text-muted-foreground" style="margin-bottom:0;"> <code>getState()</code> reflects what the user sees: pressing Escape on an open dialog returns <code>default</code>, not the stale last <code>setState</code> value. </p>
  </div>
  <div style="border:1px solid var(--border);border-radius:var(--radius-xl);padding:1.25rem;">
    <p class="text-sm font-medium mb-2" style="margin-top:0;">Reproducible markup</p>
    <p class="text-sm text-muted-foreground" style="margin-bottom:0;"> <code>render(state)</code> rebuilds the component's HTML from state: its model is the authored markup byte for byte, and for every state it equals what <code>setState()</code> produces on the live element. Every component with JavaScript has it, and its e2e test proves both. </p>
  </div>
  <div style="border:1px solid var(--border);border-radius:var(--radius-xl);padding:1.25rem;">
    <p class="text-sm font-medium mb-2" style="margin-top:0;">Documented visually</p>
    <p class="text-sm text-muted-foreground" style="margin-bottom:0;"> Every state is a named entry in the component's skill (<code>## States</code>), a section on its doc page and an e2e assertion, and <code>bun run screenshots</code> renders it in light and dark mode. </p>
  </div>
</div>

<H2>Try it</H2>

<p class="text-sm text-muted-foreground mb-5"> The buttons below call <code>api.setState()</code> and print what <code>api.getState()</code> reads back. Closing the dialog with Escape or the backdrop flips the observed state to <code>default</code> on its own - the read always matches the UI. </p>

```html example label="Drive the dialog by name" schema="none" height="24" hint="The same API keyboard users, tests and agents use: the buttons call api.setState() and print what api.getState() reads back. Close the dialog with Escape, the backdrop or its button - the named state follows the UI, so the badge flips back to default on its own."
<div class="flex flex-wrap items-center gap-2">
  <button class="btn" type="button" id="sa-open">api.setState('open')</button>
  <button class="btn" data-variant="outline" type="button" id="sa-default">api.setState('default')</button>
  <output class="badge" data-variant="secondary" id="sa-out" aria-live="polite">default</output>
</div>
<dialog id="sa-dialog" class="dialog" aria-labelledby="sa-title">
  <div class="dialog-content">
    <div class="dialog-header">
      <h2 class="dialog-title" id="sa-title">Named state</h2>
      <p class="dialog-description"
        >Opened via api.setState('open') - close it and watch the badge flip back to default.</p
      >
    </div>
    <div class="dialog-footer">
      <button class="btn" data-variant="outline" data-dialog-close>Close</button>
    </div>
  </div>
</dialog>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    // df$ selects; dialog.js has bound dialog.api on the element
    const dialog = df$('#sa-dialog').get(0);
    const show = () => df$('#sa-out').text(dialog.api.getState().name);
    df$('#sa-open').on('click', () => {
      dialog.api.setState('open');
      show();
    });
    df$('#sa-default').on('click', () => {
      dialog.api.setState('default');
      show();
    });
    // Escape / backdrop / close button: the state follows the dialog
    df$(dialog).on('close', () => queueMicrotask(show));
  });
</script>
```

<H2>The state is a store</H2>

<p class="text-sm text-muted-foreground mb-5"> Behind <code>el.api</code> every component keeps its state in a <a class="link" href="https://www.npmjs.com/package/defuss-store">defuss-store</a> store, exposed as <code>el.store</code> - a tiny synchronous observable holding <code>\{ name, config \}</code>. Subscribe to react to <em>any</em> change, including the ones a user makes without <code>setState</code> (a click, Escape, a native close); write it to drive the component exactly like <code>setState</code> does. The big-data components keep their whole query there - a <a class="link" href="data-grid.html">Data Grid</a>'s sort, filters, locked columns and selection are <code>el.store.value.config</code>. </p>

```html example label="Subscribe and write" schema="none" height="22" hint="The log subscribes to the toggle's store: press the toggle with the mouse or the keyboard - every change arrives, though nothing called setState. The second button writes the store directly; the toggle applies it like setState."
<div class="flex flex-col gap-3" style="max-width: 28rem">
  <div class="flex flex-wrap items-center gap-2">
    <button class="toggle" type="button" aria-pressed="false" id="sa-toggle">Bold</button>
    <button class="btn" data-variant="outline" data-size="sm" type="button" id="sa-write"
      >el.store.set({ name: 'pressed' })</button
    >
  </div>
  <pre
    class="text-xs m-0"
    id="sa-log"
    style="padding: 0.75rem; border-radius: var(--radius-md); background: var(--muted); min-height: 4rem"
  ></pre>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const toggle = df$('#sa-toggle').get(0);
    const log = df$('#sa-log').get(0);
    // every change - by click, keyboard or code - reaches the subscriber
    toggle.store.subscribe((state) => {
      log.textContent = JSON.stringify(state) + '\n' + log.textContent;
    });
    df$('#sa-write').on('click', () => toggle.store.set({ name: 'pressed', config: {} }));
  });
</script>
```

<p class="text-sm text-muted-foreground mb-5"> The same primitive is the system's only way into Web Storage: <code>df$.store.persisted(key, initial)</code> returns a store whose value lives in <code>localStorage</code> (or <code>sessionStorage</code>) - validated, versioned, kept in memory when the browser blocks storage (<code>df$.store.available()</code> says which), and in step with every other store for that key on the page. Components use it for <code>data-save</code> (border layout, data grid, data tree), the theme switcher and the cookie consent; this site keeps every remembered choice (dark mode, theme, sidebar) that way. </p>

<CodeWindow lang="javascript" title="df$.store" mb="2.5rem" code={"// an observable value\nconst count = df$.store.create(0);\nconst off = count.subscribe((n) => console.log('count', n));\ncount.set(1);                       // logs: count 1\n\n// a value kept in localStorage - validated against the initial shape,\n// in memory when storage is blocked\nconst prefs = df$.store.persisted('my-app:prefs', { compact: false });\nprefs.set('compact', true);         // a path write; stored at once\nprefs.subscribe((p) => df$('html').toggleClass('compact', p.compact));\n\n// a component's state, from outside\nconst grid = df$('#orders').get(0);\ngrid.store.subscribe(({ config }) => console.log(config.sorters, config.selected));"} />

<H2>Discovering the states</H2>

<p class="text-sm text-muted-foreground mb-5"> Three places name the same list. The skill frontmatter is the machine-readable source - <code>dist/SKILL.md</code> indexes it, and every component's doc page shows the states with a live demo: </p>

<CodeWindow lang="markdown" title="dialog/component-skill.md" mb="1.5rem" code={"---\nname: Dialog\ntype: MOL\n...\nsupportedStates: default, open\n---\n\n## States\n- `default` - closed (authored initial state)\n- `open` - shown modally via showModal()\n\n```js\ndf$('#confirm').get(0).api.setState('open');\n```"} />

<p class="text-sm text-muted-foreground mb-5"> The component scripts also register their states and a registry-level API on <code>globalThis.df$</code> - useful when you have no element handle yet: </p>

<CodeWindow lang="javascript" title="registry globals (set by each component .js)" mb="2.5rem" code={"df$.shadcn.dialogStates;  // ['default', 'open']\n\n// registry form - element passed explicitly, same contract as el.api\nconst { dialogApi } = df$.shadcn;\nconst confirm = df$('#confirm').get(0);\ndialogApi.setState(confirm, 'open');\ndialogApi.getState(confirm);\n// returns { name: 'open', config: {} }"} />

<H2>States across components</H2>

<p class="text-sm text-muted-foreground mb-5"> Every multi-state component, with its declared state names (from each skill's <code>supportedStates</code>). Components with no <code>.js</code> file are pure HTML/CSS - their only state is <code>default</code>, and their variants are markup attributes (<DocLink href="data-attribute-api.html">Data Attribute API</DocLink>), not runtime states. </p>

<TableCard title="declared states per JS component" mb="2.5rem">
  <DeclaredStatesTable />
</TableCard>

<H2>Why it exists</H2>

<p class="text-sm text-muted-foreground mb-5"> The <DocLink href="architecture.html">VAE page</DocLink> describes the proof loop: every declared state of every component must be visually verifiable - <code>scripts/create-screenshots.ts</code> captures one per color scheme through <code>api.setState()</code> when a change needs a look - and asserted by an e2e test. That is only possible because the states are named, uniform, and callable from plain JavaScript, no matter what the component does internally. Your agents get the same handle: <a class="link" href="component-skills.html">the skills</a> name the states, the API drives them. </p>

<p class="text-sm text-muted-foreground mb-8"> See also: <DocLink href="anatomy.html">Anatomy of a Component</DocLink> (where the <code>.js</code> layer sits), <DocLink href="data-attribute-api.html">Data Attribute API</DocLink> (markup configuration, as opposed to runtime state). </p>


</DocPage>
