# Primitives

> Element directives that handle roles, keyboard, focus and announcements.

Framework: Lit (`@stepperize/lit`), Stepperize v9.
Source: https://stepperize.com/docs/v9/lit/guides/primitives

The controller carries a set of element directives, bound to your steps. Each
one goes on an element of your own template and takes care of the parts that
are easy to get wrong: roles, ids, keyboard navigation, focus and
announcements. The markup, the tag names and the styles stay yours.

For a simple flow, your own buttons and `stepper.match` are enough.

## Basic structure

```ts
import { html, LitElement } from "lit";
import { checkout } from "./checkout";

class CheckoutSteps extends LitElement {
  stepper = checkout.controller(this, { linear: true, onFinish: placeOrder });

  render() {
    const s = this.stepper;

    return html`
      <div ${s.root()}>
        <ol ${s.list()}>
          ${s.steps.map(
            (step) => html`
              <li ${s.item(step.id)}>
                <button ${s.trigger(step.id)}>
                  <span ${s.indicator(step.id)}></span>
                  ${step.title}
                </button>
              </li>
            `,
          )}
        </ol>

        <div ${s.content("shipping")}><shipping-form></shipping-form></div>
        <div ${s.content("payment")}><payment-form></payment-form></div>
        <div ${s.content("review")}><order-review></order-review></div>

        <button ${s.prev()}>Back</button>
        <button ${s.next()}>Continue</button>
      </div>
    `;
  }
}
```

The live demo runs in the browser. Its source ([mount/lit.ts](https://github.com/damianricobelli/stepperize/blob/main/apps/docs/src/components/framework-demos/mount/lit.ts)):

```ts
import { defineStepper } from "@stepperize/lit";
import { html, LitElement } from "lit";

const demo = defineStepper([
	{ id: "account", title: "Account", description: "Who you are" },
	{ id: "plan", title: "Plan", description: "What you need" },
	{ id: "done", title: "Done", description: "All set" },
]);

const TAG = "stepperize-lit-demo";

class LitDemo extends LitElement {
	stepper = demo.controller(this);

	// Light DOM, so the page's utility classes style it like the other demos.
	protected createRenderRoot() {
		return this;
	}

	render() {
		const s = this.stepper;
		const stepper = s.value;
		const panel = "rounded-md bg-fd-muted p-3";
		return html`
			<div ${s.root()} data-demo="lit" class="not-prose my-4 flex flex-col gap-4 rounded-lg border p-4 text-sm">
				<ol ${s.list()} class="flex gap-2">
					${s.steps.map(
						(step, index) => html`
							<li ${s.item(step.id)} class="flex-1">
								<button
									${s.trigger(step.id)}
									class="flex w-full items-center gap-2 rounded-md border px-3 py-2 text-left data-[state=current]:border-fd-primary data-[state=current]:bg-fd-accent"
								>
									<span
										${s.indicator(step.id)}
										class="flex size-6 shrink-0 items-center justify-center rounded-full border text-xs data-[state=complete]:bg-fd-primary data-[state=complete]:text-fd-primary-foreground"
										>${index + 1}</span
									>
									<span class="flex flex-col">
										<span class="font-medium">${step.title}</span>
										<span class="text-xs text-fd-muted-foreground">${step.description}</span>
									</span>
								</button>
							</li>
						`,
					)}
				</ol>
				<div ${s.content("account")} class=${panel}>Create your account.</div>
				<div ${s.content("plan")} class=${panel}>Pick the plan that fits.</div>
				<div ${s.content("done")} class=${panel}>
					${stepper.isFinished ? "Finished. Thanks!" : "Press Finish to complete the flow."}
				</div>
				<div class="flex items-center gap-2">
					<button ${s.prev()} class="rounded-md border px-3 py-1 disabled:opacity-40">Back</button>
					<button ${s.next()} class="rounded-md border px-3 py-1 aria-disabled:opacity-40">
						${stepper.isLast ? "Finish" : "Continue"}
					</button>
					<span data-step class="ml-auto text-xs text-fd-muted-foreground">
						Step ${stepper.index + 1} of ${stepper.steps.length}
					</span>
				</div>
			</div>
		`;
	}
}

export function mount(el: HTMLElement) {
	if (!customElements.get(TAG)) customElements.define(TAG, LitDemo);
	const element = document.createElement(TAG);
	el.appendChild(element);
	return () => element.remove();
}
```

## How the pieces connect

1. `root()` marks the element that contains the stepper. Every other part must
   be inside it, in your template or in a [child component](#parts-in-a-child-component)'s;
   clicks and keys are handled there.
2. `list()` marks the list of steps and gives it arrow-key navigation.
3. `item(id)` is one step.
4. `trigger(id)` goes to that step when pressed.
5. `indicator(id)` is a decorative mark, hidden from assistive technology.
6. `content(id)` is the panel of a step: `hidden` unless its step is current.
7. `prev()` and `next()` call `prev()` and `next()` on the flow.

Step ids are typed: `s.content("shiping")` does not compile.

A directive is written inside the opening tag, next to the attributes. It adds
to what you wrote: `class`, `style`, your own attributes and your own
`@click` stay. See [Your attributes](#your-attributes) for the ones a directive
also sets.

## Why directives and not custom elements

A `<stepper-trigger>` element would put its button in a shadow root of its own.
`aria-controls` and `aria-labelledby` cannot point across shadow roots, so a
tab could not name its panel, and your styles could not reach the button.
Directives leave every element in your template, in one root, and keep step ids
typed by your definition.

They work the same in shadow DOM and in light DOM (`createRenderRoot()`
returning `this`).

## Three patterns, chosen for you

| The flow | What is rendered |
| --- | --- |
| Not `linear`, with triggers | A `tablist`: triggers are tabs with roving focus and arrow keys, panels are `tabpanel`s. |
| `linear` | An ordered list of buttons with `aria-current="step"`. Steps that cannot be reached yet are disabled. |
| No triggers | Panels are `group`s named by the step's `title`. |

On every step change the new step is announced to screen readers by its
`title`, and if the focused element was hidden or removed, focus moves to the
new panel instead of being lost.

## Styling

Nothing is styled. Every element has a `data-component` and the state it shows:

| Attribute | On | Values |
| --- | --- | --- |
| `data-state` | item, trigger, indicator | `pending`, `current`, `complete` |
| `data-invalid` | item, trigger, indicator | Present after a failed validation. |
| `data-disabled` | item, trigger, prev, next | Present when it cannot be used. |
| `data-pending` | root, prev, next | Present while an async check or `onFinish` runs. |
| `data-finished` | root | Present once the flow has finished. |
| `data-orientation` | root, list | `horizontal`, `vertical` |

```ts
static styles = css`
  [data-component="stepper-trigger"][data-state="current"] { font-weight: 600; }
  [data-component="stepper-indicator"][data-state="complete"] { background: green; }
`;
```

## Reading a step's state

`s.at(id)` returns what an item knows about its step, for your own markup:

```ts
${s.steps.map((step, index) => {
  const item = s.at(step.id);
  return html`<li ${s.item(step.id)}>
    <button ${s.trigger(step.id)}>${item.state === "complete" ? "✓" : index + 1} ${step.title}</button>
  </li>`;
})}
```

## Handling the move yourself

Your own `@click` runs first. Call `preventDefault()` in it to take over, for
example to pass form values:

```ts
html`<button
  ${s.next()}
  @click=${(event: Event) => {
    event.preventDefault();
    s.value.next(this.values);
  }}
>
  Continue
</button>`;
```

## Your attributes

A directive never removes an attribute it did not set. Where you and the
directive both set one:

| Attribute | On | Who wins |
| --- | --- | --- |
| `role`, `aria-label`, `aria-labelledby`, `tabindex` | root, list, item, content, indicator | **Yours.** A name you give replaces the stepper's, both ways of naming included. |
| `type` | any `<button>` | **Yours.** Otherwise `type="button"`. |
| `disabled`, `hidden` | any part | **Both.** Yours adds to the stepper's: disabled if either says so. `aria-disabled` and `data-disabled` follow. |
| ARIA and `id` | trigger, prev, next, and the `id` of content | **The stepper's.** They are what make the tabs, the keyboard and focus work. |
| `data-*` the stepper sets | any part | **The stepper's**, and yours comes back when it stops setting one. |

```ts
html`
  <div ${s.root()} aria-label="Checkout">…</div>
  <section ${s.content("payment")} aria-labelledby="payment-heading">
    <h3 id="payment-heading">Pay</h3>
  </section>
`;
```

To disable a button on top of the flow, prefer the option:
`s.next({ disabled: this.saving })`. A `?disabled=${…}` binding works too, with
one gap: when it turns on while the stepper has already disabled the button
(Back on the first step), the stepper cannot see it, and enables the button when
the flow moves on.

Trigger and panel ids are the stepper's: the tabs, `aria-controls`, the panel's
name and the focus hand-off are tied by them. Select a panel by
`[data-step="payment"]` instead of an id of your own.

## Parts in a child component

The parts can be rendered by another element, in its own shadow root: pass it
the controller as a property.

```ts
import type { StepperPrimitives } from "@stepperize/lit";

class CheckoutSteps extends LitElement {
  stepper = checkout.controller(this);

  render() {
    const s = this.stepper;
    return html`
      <div ${s.root()}>
        <ol ${s.list()}>…</ol>
        <div ${s.content("shipping")}>…</div>
        <checkout-nav .stepper=${s}></checkout-nav>
      </div>
    `;
  }
}

class CheckoutNav extends LitElement {
  static properties = { stepper: { attribute: false } };
  declare stepper: StepperPrimitives<typeof checkout.steps>;

  render() {
    return html`<button ${this.stepper.prev()}>Back</button><button ${this.stepper.next()}>Continue</button>`;
  }
}
```

Parts that arrive later, from a child component, `until` or anything else, are
painted as soon as their template is in place. Clicks reach the root and keys
reach the list from inside the child's shadow root.

Ids do not cross shadow roots, so two things need one root: a trigger and the
panel it controls name each other by id, and focus moves to the new panel by
id. Render the panels, and the triggers of a flow shown as tabs, in the same
shadow root as `root()`. In development a trigger or panel in another root is
reported as [SZ004](https://stepperize.com/docs/v9/core/errors#sz004). Everything else can be in a
child's shadow root: the list and its items, indicators, Back and Continue,
and the triggers of a linear flow whose steps have a `title`.

## Ending the stepper

`this.stepper.destroy()` ends the controller and stops its directives:
see [Ending a flow](https://stepperize.com/docs/v9/lit/guides/shared-state#ending-a-flow).

## Panels in or out of the template

`content(id)` hides its element while the step is not current, so the fields
inside keep their state. To drop a panel from the DOM instead, leave it out of
the template:

```ts
${s.value.current.id === "review" ? html`<div ${s.content("review")}>…</div>` : nothing}
```

With [server rendering](https://stepperize.com/docs/v9/lit/guides/ssr), either way needs a binding
or a condition so the server HTML only shows the current panel.

See the [primitives reference](https://stepperize.com/docs/v9/lit/api/primitives) for every option.
