# Dialog stack

> Native modal for a short multi-step flow; finished steps peek behind the current one. All steps list in order without script.

- Kind: ui · Category: Overlays · Interactivity: script
- Install: `npx shadcn@latest add @haze/dialog-stack`
- File: `src/components/haze/ui/dialog-stack.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/button, @haze/utils
- Docs page: https://hazeui.com/ui/dialog-stack

## Use when
- A two to four step flow such as invite, choose a role, review, where the user should see progress behind the panel
- A short setup wizard that must not leave the current page
- Steps that share one trigger and one outcome, with Back and Next between them

## Avoid when
- A single decision or short form needs only dialog.
- A long flow with many fields deserves its own page; use stepper for in-page progress.
- Side-anchored detail panels fit drawer better than a centered modal.

## Alternatives
- [dialog](https://hazeui.com/ui/dialog.md)
- [drawer](https://hazeui.com/ui/drawer.md)
- [stepper](https://hazeui.com/ui/stepper.md)
- [alert-dialog](https://hazeui.com/ui/alert-dialog.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique on the page. Buttons target it with commandfor="<id>"; step ids derive from it. |
| steps | `{ title: string; description: string; body?: string }[]` | three-step invite flow | no | One entry per step. Each gets its own heading and description. |
| trigger | `boolean` | true | no | Set to false when the opening button lives elsewhere. |
| triggerLabel | `string` | "Invite teammates" | no | Trigger button text. |
| triggerVariant | `"primary" \| "secondary" \| "outline" \| "ghost"` | "outline" | no | Trigger button style. |
| stepLabel | `string` | "Step" | no | First word of the counter text, "Step 2 of 3". Translate it. |
| ofLabel | `string` | "of" | no | Middle word of the counter text. Translate it. |
| backLabel | `string` | "Back" | no | Back button text. |
| nextLabel | `string` | "Next" | no | Next button text. |
| doneLabel | `string` | "Done" | no | Final button text; closes the dialog. |
| closeLabel | `string` | "Close" | no | Accessible name of the close icon button. |
| headingLevel | `2 \| 3 \| 4 \| 5 \| 6` | 2 | no | Heading level of each step title. |
| class | `string` |  | no | Extra classes on the dialog. |

## Accessibility
- showModal() semantics: the page behind is inert, focus stays inside and returns to the trigger on close.
- The dialog's aria-labelledby and aria-describedby follow the current step. Earlier and later steps are inert, so assistive tech and Tab only reach the current panel.
- Moving Back or Next puts focus on the new step's heading; the "Step 2 of 3" counter is plain text above it.
- Without script every step shows as a section in one scrollable dialog with a single Done button, and Back and Next stay hidden.
- Opening uses command and commandfor (Chrome 135, Firefox 144, Safari 26.2); the small shared script covers older browsers. Panels slide over 300 ms; reduced-motion users get none.
- Key Enter / Space: Open the dialog from the trigger; press Back, Next or Done
- Key Tab / Shift+Tab: Move between the current step's controls; focus stays inside the dialog
- Key Escape: Close the whole stack and return focus to the trigger

## Agent prompts

### Install and use

Install the Haze UI component "Dialog stack" with `npx shadcn@latest add @haze/dialog-stack`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import DialogStack from "@/components/haze/ui/dialog-stack.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/dialog-stack.md

### Customize with real content

Adapt the Haze dialog-stack ui for our product. Replace the demo values of these props with our real content: id, steps, trigger, triggerLabel, triggerVariant, stepLabel, ofLabel, backLabel, nextLabel, doneLabel, closeLabel, headingLevel, class. Keep the layout, the heading level rules and these accessibility details: showModal() semantics: the page behind is inert, focus stays inside and returns to the trigger on close. The dialog's aria-labelledby and aria-describedby follow the current step. Earlier and later steps are inert, so assistive tech and Tab only reach the current panel. Moving Back or Next puts focus on the new step's heading; the "Step 2 of 3" counter is plain text above it. Without script every step shows as a section in one scrollable dialog with a single Done button, and Back and Next stay hidden. Opening uses command and commandfor (Chrome 135, Firefox 144, Safari 26.2); the small shared script covers older browsers. Panels slide over 300 ms; reduced-motion users get none. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using dialog-stack, check it fits: use it when a two to four step flow such as invite, choose a role, review, where the user should see progress behind the panel; a short setup wizard that must not leave the current page; steps that share one trigger and one outcome, with back and next between them. Avoid it when a single decision or short form needs only dialog.; a long flow with many fields deserves its own page; use stepper for in-page progress.; side-anchored detail panels fit drawer better than a centered modal.. Alternatives: @haze/dialog, @haze/drawer, @haze/stepper, @haze/alert-dialog.

## Example requests that should lead here
- Add a three-step dialog to invite teammates, choose their role and review
- Build a short onboarding flow in a modal where earlier steps stay visible behind

## Source

```astro
---
import { X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";

interface Step {
  title: string;
  description: string;
  body?: string;
}

interface Props {
  /** Unique on the page. Any button with `command="show-modal" commandfor="<id>"` opens the stack. */
  id: string;
  steps?: Step[];
  /** Set to false when the opening button lives somewhere else on the page. */
  trigger?: boolean;
  triggerLabel?: string;
  triggerVariant?: "primary" | "secondary" | "outline" | "ghost";
  /** Words around the step counter: "Step 2 of 3". Translate both. */
  stepLabel?: string;
  ofLabel?: string;
  backLabel?: string;
  nextLabel?: string;
  doneLabel?: string;
  closeLabel?: string;
  headingLevel?: 2 | 3 | 4 | 5 | 6;
  class?: string;
}

const {
  id,
  steps = [
    {
      title: "Invite teammates",
      description: "Add the people who should join the Bramble Studio workspace.",
      body: "Paste up to ten email addresses, separated by commas. Nobody gets an email until you finish the last step.",
    },
    {
      title: "Choose a role",
      description: "Pick what the new people can do once they join.",
      body: "Editors can change projects and invite others. Viewers can read and comment. You can change a role later in Settings.",
    },
    {
      title: "Review and send",
      description: "Check the details before the invitations go out.",
      body: "Three invitations will be sent today as Editor. Each link works for seven days and can be revoked from the Members page.",
    },
  ],
  trigger = true,
  triggerLabel = "Invite teammates",
  triggerVariant = "outline",
  stepLabel = "Step",
  ofLabel = "of",
  backLabel = "Back",
  nextLabel = "Next",
  doneLabel = "Done",
  closeLabel = "Close",
  headingLevel = 2,
  class: className,
} = Astro.props;

const Heading = `h${headingLevel}` as const;
const last = steps.length - 1;
---

{
  trigger && (
    <Button variant={triggerVariant} command="show-modal" commandfor={id} aria-haspopup="dialog">
      {triggerLabel}
    </Button>
  )
}
<dialog
  id={id}
  data-haze-dialog-stack
  aria-labelledby={`${id}-step-1-title`}
  aria-describedby={`${id}-step-1-description`}
  closedby="any"
  class={cn(
    "m-auto max-h-[calc(100dvh-2rem)] w-[calc(100vw-2rem)] max-w-md overflow-y-auto border-0 bg-transparent p-0 text-popover-foreground data-[enhanced]:overflow-visible",
    "translate-y-2 scale-[0.96] opacity-0 transition-[opacity,scale,translate,overlay,display] transition-discrete duration-200 ease-snappy open:translate-y-0 open:scale-100 open:opacity-100 starting:open:translate-y-2 starting:open:scale-[0.96] starting:open:opacity-0",
    "backdrop:bg-background/60 backdrop:opacity-0 backdrop:transition-[opacity,overlay,display] backdrop:transition-discrete backdrop:duration-200 open:backdrop:opacity-100 starting:open:backdrop:opacity-0",
    className,
  )}
>
  <div class="grid gap-3 [[data-enhanced]_&]:gap-0">
    {
      steps.map((step, index) => (
        <section
          data-ds-step
          aria-labelledby={`${id}-step-${index + 1}-title`}
          class={cn(
            "relative grid origin-top content-start rounded-2xl border border-border bg-popover shadow-float",
            "[[data-enhanced]_&]:col-start-1 [[data-enhanced]_&]:row-start-1 [[data-enhanced]_&]:max-h-[calc(100dvh-4rem)] [[data-enhanced]_&]:overflow-y-auto",
            "transition-[opacity,scale,translate] duration-300 ease-snappy",
            "data-[state=current]:z-10 data-[state=current]:translate-y-0 data-[state=current]:scale-100 data-[state=current]:opacity-100",
            "data-[state=past]:pointer-events-none data-[state=past]:translate-y-[calc(var(--d)*-0.75rem)] data-[state=past]:scale-[calc(1-var(--d)*0.05)] data-[state=past]:opacity-60 data-[state=past]:*:opacity-0",
            "data-[state=future]:pointer-events-none data-[state=future]:translate-y-2 data-[state=future]:scale-[0.96] data-[state=future]:opacity-0",
          )}
        >
          <header class="grid gap-2 border-b border-border p-5 pr-14">
            <p class="text-[0.6875rem]/4 font-medium tracking-wider text-muted-foreground uppercase tabular-nums">
              {stepLabel} {index + 1} {ofLabel} {steps.length}
            </p>
            <Heading
              id={`${id}-step-${index + 1}-title`}
              tabindex="-1"
              class="text-[1.0625rem] leading-[1.4] font-medium tracking-[-0.01em] text-foreground focus-visible:outline-hidden"
            >
              {step.title}
            </Heading>
            <p id={`${id}-step-${index + 1}-description`} class="text-[0.8125rem] leading-[1.4] text-muted-foreground">
              {step.description}
            </p>
          </header>
          {step.body && <p class="p-5 text-[0.8125rem] leading-[1.4]">{step.body}</p>}
          <footer
            class={cn(
              "flex flex-col-reverse gap-2 border-t border-border px-5 py-4 sm:flex-row sm:justify-end",
              index !== last && "hidden [[data-enhanced]_&]:flex",
            )}
          >
            {index > 0 && (
              <Button variant="ghost" data-ds-back hidden>
                {backLabel}
              </Button>
            )}
            {index < last && (
              <Button data-ds-next hidden>
                {nextLabel}
              </Button>
            )}
            {index === last && (
              <form method="dialog" class="contents">
                <Button type="submit" data-ds-done>
                  {doneLabel}
                </Button>
              </form>
            )}
          </footer>
          <form method="dialog" class={cn("absolute right-5 top-5", index > 0 && "hidden [[data-enhanced]_&]:block")}>
            <button
              type="submit"
              aria-label={closeLabel}
              class="inline-flex size-6 cursor-pointer items-center justify-center rounded-lg border border-frame bg-muted/50 text-muted-foreground transition-[background-color,color,scale] duration-150 ease-snappy hover:bg-muted hover:text-foreground active:scale-[0.96] active:duration-100 motion-reduce:transition-none motion-reduce:active:scale-100 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
            >
              <X class="size-3.5" aria-hidden="true" />
            </button>
          </form>
        </section>
      ))
    }
  </div>
</dialog>

<script>
  const root = document.documentElement;

  function setup(dialog: HTMLDialogElement) {
    const id = dialog.id;
    const cards = Array.from(dialog.querySelectorAll<HTMLElement>("[data-ds-step]"));
    if (cards.length === 0) return;
    let current = 0;
    let resetTimer: number | undefined;

    const show = (index: number, moveFocus: boolean) => {
      current = Math.min(cards.length - 1, Math.max(0, index));
      cards.forEach((card, i) => {
        card.dataset.state = i === current ? "current" : i < current ? "past" : "future";
        card.style.setProperty("--d", String(Math.max(0, current - i)));
        card.inert = i !== current;
        card.querySelectorAll<HTMLElement>("[data-ds-back]").forEach((b) => { b.hidden = i !== current || i === 0; });
        card.querySelectorAll<HTMLElement>("[data-ds-next]").forEach((b) => { b.hidden = i !== current; });
      });
      dialog.setAttribute("aria-labelledby", `${id}-step-${current + 1}-title`);
      dialog.setAttribute("aria-describedby", `${id}-step-${current + 1}-description`);
      if (moveFocus) cards[current].querySelector<HTMLElement>("h1, h2, h3, h4, h5, h6")?.focus({ preventScroll: true });
    };

    dialog.addEventListener("click", (event) => {
      const target = (event.target as Element | null)?.closest?.("[data-ds-next], [data-ds-back]");
      if (!target || !dialog.contains(target)) return;
      show(target.hasAttribute("data-ds-next") ? current + 1 : current - 1, true);
    });
    // Start again at step 1 once the closing transition is over.
    dialog.addEventListener("close", () => {
      window.clearTimeout(resetTimer);
      resetTimer = window.setTimeout(() => { if (!dialog.open) show(0, false); }, 320);
    });

    dialog.setAttribute("data-enhanced", "");
    show(0, false);
  }

  const init = () => {
    document.querySelectorAll<HTMLDialogElement>("dialog[data-haze-dialog-stack]:not([data-enhanced])").forEach(setup);
  };
  init();
  if (!root.hasAttribute("data-haze-dialog-stack-listener")) {
    root.setAttribute("data-haze-dialog-stack-listener", "");
    document.addEventListener("astro:page-load", init);
  }

  // Fallback only, shared with dialog.astro: browsers without Invoker Commands or closedby.
  if (!root.hasAttribute("data-haze-invokers")) {
    root.setAttribute("data-haze-invokers", "");

    if (!("command" in HTMLButtonElement.prototype)) {
      document.addEventListener("click", (event) => {
        const button = (event.target as Element | null)?.closest?.("button[commandfor]");
        const target = button && document.getElementById(button.getAttribute("commandfor") ?? "");
        if (!(target instanceof HTMLDialogElement)) return;
        const command = button!.getAttribute("command");
        if (command === "show-modal" && !target.open) target.showModal();
        if (command === "close" && target.open) target.close();
      });
    }

    if (!("closedBy" in HTMLDialogElement.prototype)) {
      document.addEventListener("click", (event) => {
        const dialog = event.target;
        if (dialog instanceof HTMLDialogElement && dialog.open && dialog.getAttribute("closedby") === "any") dialog.close();
      });
    }
  }
</script>
```
