# Notification stack

> Dismissible updates with a layered stack and swipe dismissal. A promise row morphs from spinner to success or error.

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

## Use when
- A panel lists recent events people can read at their own pace
- Each event can be independently dismissed for the current view

## Avoid when
- The message requires an immediate decision. Use alert-dialog.
- The notice is a single inline status. Use alert.

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

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique prefix for the component and its labelled controls. |
| label | `string` | "Notifications" | no | Heading for the updates list. |
| items | `Notification[]` |  | no | Items with title, optional description, and optional info, success, warning, or destructive variant. |
| emptyLabel | `string` | "You’re caught up." | no | Message after all items are dismissed. |
| dismissLabel | `string` | "Dismiss" | no | Accessible prefix for the dismiss button. |
| headingLevel | `2 \| 3 \| 4 \| 5 \| 6` | 2 | no | Heading level for the title. |
| stacked | `boolean` | false | no | Layer three peeking cards. Hover, focus or the expand button fans them out. Touch can swipe right to dismiss. |
| class | `string` |  | no | Additional classes on the section. |
| hazeNotice.promise(task, options) | `script API on the section element` |  | no | Adds a pending row at the top with a spinner and the loading text, then morphs the same row to success or error when the promise settles: the icon pops in, the text swaps and the height eases over 200 ms. Options: loading, success and error (a string, a { title, description } object, or for success and error a function of the result), and duration in ms before a settled row leaves (default 4000, paused while hovered or focused). Returns the original promise. |

## Accessibility
- Each button includes the notification title in its accessible name.
- A promise row announces its loading text and then its result through the polite status line; the spinner and result icons are decorative. Settled rows dismiss themselves after the duration unless hovered or focused. Under reduced motion the spinner is static and the height change is instant.
- Dismissal moves focus to a remaining dismiss button or to the section heading.
- The persistent list is readable with scripts off. Dismissal applies to the current page view.
- Key Tab then Enter or Space: Focus and dismiss an update.

## Agent prompts

### Install and use

Install the Haze UI component "Notification stack" with `npx shadcn@latest add @haze/notification-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 NotificationStack from "@/components/haze/ui/notification-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/notification-stack.md

### Customize with real content

Adapt the Haze notification-stack ui for our product. Replace the demo values of these props with our real content: id, label, items, emptyLabel, dismissLabel, headingLevel, stacked, class, hazeNotice.promise(task, options). Keep the layout, the heading level rules and these accessibility details: Each button includes the notification title in its accessible name. A promise row announces its loading text and then its result through the polite status line; the spinner and result icons are decorative. Settled rows dismiss themselves after the duration unless hovered or focused. Under reduced motion the spinner is static and the height change is instant. Dismissal moves focus to a remaining dismiss button or to the section heading. The persistent list is readable with scripts off. Dismissal applies to the current page view. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using notification-stack, check it fits: use it when a panel lists recent events people can read at their own pace; each event can be independently dismissed for the current view. Avoid it when the message requires an immediate decision. use alert-dialog.; the notice is a single inline status. use alert.. Alternatives: @haze/alert, @haze/alert-dialog, @haze/empty.

## Example requests that should lead here
- Add a project updates panel with three dismissible notifications and an empty state.

## Source

```astro
---
import { ChevronDown, CircleAlert, CircleCheck, Info, LoaderCircle, TriangleAlert, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";

type Notification = { title: string; description?: string; variant?: "info" | "success" | "warning" | "destructive" };
interface Props {
  id: string;
  label?: string;
  items?: Notification[];
  emptyLabel?: string;
  dismissLabel?: string;
  headingLevel?: 2 | 3 | 4 | 5 | 6;
  stacked?: boolean;
  class?: string;
}

const {
  id, label = "Notifications", emptyLabel = "You’re caught up.", dismissLabel = "Dismiss",
  headingLevel = 2, stacked = false, class: className,
  items = [
    { title: "Export complete", variant: "success", description: "The usage report is ready to download." },
    { title: "Review due tomorrow", variant: "info" },
  ],
} = Astro.props;
const Heading = `h${headingLevel}` as const;
const rowClass = "flex min-w-0 touch-pan-y items-start gap-3 overflow-hidden rounded-xl border border-frame bg-popover py-3 pr-3 pl-4 text-popover-foreground opacity-100 shadow-lift transition-[display,opacity,translate,scale,background-color,border-color] transition-discrete duration-200 ease-snappy *:transition-opacity *:duration-200 *:ease-snappy data-[behind]:border-border data-[behind]:bg-muted data-[behind]:*:opacity-0 data-[dismissed]:hidden data-[dismissed]:-translate-y-1 data-[dismissed]:opacity-0";
const variants = {
  info: { Icon: Info, classes: "bg-brand/14 text-brand" },
  success: { Icon: CircleCheck, classes: "bg-success/14 text-success" },
  warning: { Icon: TriangleAlert, classes: "bg-warning/14 text-warning" },
  destructive: { Icon: CircleAlert, classes: "bg-destructive/14 text-destructive" },
};
---

<section id={id} data-haze-notification-stack data-stacked={stacked || undefined} aria-labelledby={`${id}-title`} class={cn("group/notices grid min-w-0 gap-3", className)}>
  <Heading id={`${id}-title`} data-notice-heading tabindex="-1" class="rounded-sm text-[0.9375rem]/5 font-medium tracking-[-0.01em] text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring">{label}</Heading>
  <button data-notice-expand type="button" aria-expanded="false" class="group/toggle -mt-1 hidden h-6 cursor-pointer items-center gap-1 justify-self-start rounded-md text-[0.8125rem]/5 font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring group-data-[stack-ready]/notices:inline-flex">
    <span data-notice-expand-label>Show all notifications</span>
    <ChevronDown aria-hidden="true" class="size-3.5 transition-transform duration-200 ease-snappy group-aria-expanded/toggle:rotate-180" />
  </button>
  <ul data-notice-list class="relative grid min-w-0 gap-2 empty:hidden motion-safe:transition-[height] motion-safe:duration-300 motion-safe:ease-snappy">
    {items.map(({ title, description, variant = "info" }) => {
      const { Icon, classes } = variants[variant];
      return (
        <li data-notice data-notice-title={title} class={rowClass}>
          <span class={cn("grid size-7 shrink-0 place-items-center rounded-full", classes)}>
            <Icon aria-hidden="true" class="size-4" />
          </span>
          <div class="grid min-w-0 flex-1 gap-0.5">
            <p class="wrap-anywhere text-[0.8125rem]/5 font-medium tracking-[-0.01em]">{title}</p>
            {description && <p class="wrap-anywhere text-xs/5 text-muted-foreground">{description}</p>}
          </div>
          <Button data-notice-dismiss size="icon" variant="ghost" aria-label={`${dismissLabel} ${title}`}
            class="hidden size-7 rounded-full text-muted-foreground [[data-haze-notification-stack][data-enhanced]_&]:inline-flex active:scale-90 [&_svg]:size-3.5">
            <X aria-hidden="true" />
          </Button>
        </li>
      );
    })}
  </ul>
  <template data-notice-template>
    <li data-notice data-state="pending" data-notice-title="" class={cn("group/notice", rowClass)}>
      <span class="grid size-7 shrink-0 place-items-center rounded-full bg-muted text-muted-foreground transition-[background-color,color] duration-200 ease-snappy group-data-[state=error]/notice:bg-destructive/14 group-data-[state=error]/notice:text-destructive group-data-[state=success]/notice:bg-success/14 group-data-[state=success]/notice:text-success">
        <LoaderCircle aria-hidden="true" class="col-start-1 row-start-1 size-4 opacity-0 transition-opacity duration-150 ease-snappy group-data-[state=pending]/notice:opacity-100 motion-safe:animate-spin" />
        <CircleCheck aria-hidden="true" class="col-start-1 row-start-1 size-4 opacity-0 group-data-[state=success]/notice:opacity-100 motion-safe:group-data-[state=success]/notice:animate-pop" />
        <CircleAlert aria-hidden="true" class="col-start-1 row-start-1 size-4 opacity-0 group-data-[state=error]/notice:opacity-100 motion-safe:group-data-[state=error]/notice:animate-pop" />
      </span>
      <div class="grid min-w-0 flex-1 gap-0.5">
        <p data-notice-text class="wrap-anywhere text-[0.8125rem]/5 font-medium tracking-[-0.01em]"></p>
        <p data-notice-desc class="wrap-anywhere text-xs/5 text-muted-foreground empty:hidden"></p>
      </div>
      <Button data-notice-dismiss size="icon" variant="ghost" aria-label={dismissLabel}
        class="hidden size-7 rounded-full text-muted-foreground [[data-haze-notification-stack][data-enhanced]_&]:inline-flex active:scale-90 [&_svg]:size-3.5">
        <X aria-hidden="true" />
      </Button>
    </li>
  </template>
  <p data-notice-empty hidden={items.length > 0} class="rounded-xl border border-border bg-card px-4 py-3 text-[0.8125rem]/5 text-muted-foreground">{emptyLabel}</p>
  <p data-notice-status aria-live="polite" class="sr-only"></p>
</section>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const heading = root.querySelector<HTMLElement>("[data-notice-heading]");
    const list = root.querySelector<HTMLUListElement>("[data-notice-list]");
    const empty = root.querySelector<HTMLElement>("[data-notice-empty]");
    const status = root.querySelector<HTMLElement>("[data-notice-status]");
    const expand = root.querySelector<HTMLButtonElement>("[data-notice-expand]");
    const expandLabel = root.querySelector<HTMLElement>("[data-notice-expand-label]");
    if (!heading || !list || !empty || !status) return;

    const stacked = root.hasAttribute("data-stacked");
    const reduced = matchMedia("(prefers-reduced-motion: reduce)");
    let expanded = false, hovered = false;
    const rows = () => [...list.querySelectorAll<HTMLLIElement>(":scope > [data-notice]:not([data-dismissed])")];
    const layout = () => {
      if (!stacked) return;
      const active = rows();
      const fan = expanded || hovered || list.contains(document.activeElement);
      let height = 0;
      // Take every row out of flow first so the front row is measured at its final width and natural height.
      active.forEach(row => { row.style.position = "absolute"; row.style.insetInline = "0"; row.style.top = "0"; row.style.height = ""; });
      const frontHeight = active[0]?.offsetHeight ?? 0;
      active.forEach((row, index) => {
        const visible = fan || index < 3;
        row.inert = !visible;
        row.setAttribute("aria-hidden", String(!visible));
        row.style.position = "absolute";
        row.style.insetInline = "0";
        row.style.top = "0";
        row.style.zIndex = String(active.length - index);
        row.style.transformOrigin = "center bottom";
        row.style.scale = fan ? "1" : String(1 - Math.min(index, 2) * .05);
        row.style.opacity = visible ? "1" : "0";
        row.toggleAttribute("data-behind", !fan && index > 0);
        row.style.height = !fan && index > 0 ? `${frontHeight}px` : "";
        row.style.pointerEvents = !fan && index > 0 ? "none" : "";
        row.style.translate = `0 ${fan ? height : Math.min(index, 2) * 8}px`;
        if (fan) height += row.offsetHeight + 6;
      });
      list.style.height = `${active.length ? fan ? Math.max(0, height - 6) : active[0].offsetHeight + Math.min(active.length - 1, 2) * 8 : 0}px`;
      if (expand) {
        expand.hidden = active.length < 2;
        expand.style.display = active.length < 2 ? "none" : "inline-flex";
        expand.classList.toggle("hidden", active.length < 2);
        expand.setAttribute("aria-expanded", String(fan));
        if (expandLabel) expandLabel.textContent = fan ? "Collapse notifications" : `Show all ${active.length} notifications`;
      }
    };
    const snappy = () => getComputedStyle(root).getPropertyValue("--ease-snappy").trim() || "cubic-bezier(0.22, 1, 0.36, 1)";
    const dismiss = (row: HTMLLIElement) => {
      if (row.parentElement !== list || row.hasAttribute("data-dismissed")) return;
      const active = rows();
      const positions = new Map(active.map(item => [item, item.getBoundingClientRect().top]));
      const index = active.indexOf(row);
      const sibling = active[index + 1] ?? active[index - 1];
      const focused = row.contains(document.activeElement);
      row.inert = true;
      row.setAttribute("data-dismissed", "");
      row.style.opacity = "";
      row.style.translate = "";
      status.textContent = sibling ? `Dismissed ${row.dataset.noticeTitle}.` : empty.textContent?.trim() ?? "";
      if (focused) {
        if (sibling) { sibling.inert = false; sibling.removeAttribute("aria-hidden"); }
        (sibling?.querySelector<HTMLButtonElement>("[data-notice-dismiss]") ?? heading).focus({ preventScroll: true });
      }
      Promise.allSettled(row.getAnimations().map(animation => animation.finished)).then(() => {
        row.remove();
        if (!list.children.length) empty.hidden = false;
        layout();
        if (!stacked && !reduced.matches) rows().forEach(item => {
          const offset = (positions.get(item) ?? item.getBoundingClientRect().top) - item.getBoundingClientRect().top;
          if (offset) item.animate([{ translate: `0 ${offset}px` }, { translate: "0 0" }], { duration: 250, easing: getComputedStyle(root).getPropertyValue("--ease-snappy").trim() || "ease" });
        });
      });
    };
    list.addEventListener("click", (event) => {
      const button = (event.target as Element).closest<HTMLButtonElement>("[data-notice-dismiss]");
      const row = button?.closest<HTMLLIElement>("[data-notice]");
      if (row && !row.inert) dismiss(row);
    });
    if (stacked) {
      root.setAttribute("data-stack-ready", "");
      expand?.addEventListener("click", () => { expanded = !expanded; layout(); });
      list.addEventListener("pointerenter", event => { if (event.pointerType === "mouse") { hovered = true; layout(); } });
      list.addEventListener("pointerleave", () => { hovered = false; layout(); });
      list.addEventListener("focusin", layout);
      list.addEventListener("focusout", () => queueMicrotask(layout));
      new ResizeObserver(layout).observe(root);
      let drag: { row: HTMLLIElement; x: number; y: number; top: string; time: number; dx: number } | undefined;
      list.addEventListener("pointerdown", event => {
        if (reduced.matches || event.button !== 0 || (event.target as Element).closest("button,a,input")) return;
        const row = (event.target as Element).closest<HTMLLIElement>("[data-notice]");
        if (!row || row.inert) return;
        drag = { row, x: event.clientX, y: event.clientY, top: row.style.translate.split(" ")[1] || "0px", time: performance.now(), dx: 0 };
      });
      list.addEventListener("pointermove", event => {
        if (!drag) return;
        const dx = event.clientX - drag.x, dy = event.clientY - drag.y;
        if (Math.abs(dy) > Math.abs(dx) && Math.abs(dy) > 8) { drag = undefined; layout(); return; }
        if (Math.abs(dx) < 8) return;
        drag.dx = dx;
        if (!drag.row.hasPointerCapture(event.pointerId)) drag.row.setPointerCapture(event.pointerId);
        drag.row.style.transitionDuration = "0s";
        drag.row.style.translate = `${dx > 0 ? dx : dx / 5}px ${drag.top}`;
        drag.row.style.opacity = String(1 - Math.min(.8, Math.max(0, dx) / drag.row.clientWidth));
      });
      const finish = (event: PointerEvent) => {
        if (!drag) return;
        const { row, dx, time } = drag;
        drag = undefined;
        if (row.hasPointerCapture(event.pointerId)) row.releasePointerCapture(event.pointerId);
        row.style.transitionDuration = "";
        if (event.type !== "pointercancel" && (dx > row.clientWidth * .35 || dx > 35 && dx / Math.max(1, performance.now() - time) > .7)) dismiss(row);
        else layout();
      };
      list.addEventListener("pointerup", finish);
      list.addEventListener("pointercancel", finish);
      layout();
    }

    // Script API: root.hazeNotice.promise(task, { loading, success, error, duration? }).
    // One row shows a spinner, then morphs in place to success or error, and leaves after `duration` ms once settled.
    type Text = string | { title: string; description?: string };
    type PromiseOptions<T> = { loading: Text; success: Text | ((value: T) => Text); error: Text | ((reason: unknown) => Text); duration?: number };
    const template = root.querySelector<HTMLTemplateElement>("template[data-notice-template]");
    const say = (value: Text) => typeof value === "string" ? { title: value, description: "" } : { title: value.title, description: value.description ?? "" };
    const write = (row: HTMLLIElement, value: Text) => {
      const { title, description } = say(value);
      row.dataset.noticeTitle = title;
      row.querySelector("[data-notice-text]")!.textContent = title;
      row.querySelector("[data-notice-desc]")!.textContent = description;
      const button = row.querySelector("[data-notice-dismiss]");
      button?.setAttribute("aria-label", `${button.getAttribute("data-dismiss-label")} ${title}`);
      return title;
    };
    const promise = <T,>(task: Promise<T>, options: PromiseOptions<T>) => {
      const row = template?.content.firstElementChild?.cloneNode(true) as HTMLLIElement | undefined;
      if (!row) return task;
      const dismissLabel = row.querySelector("[data-notice-dismiss]")?.getAttribute("aria-label") ?? "Dismiss";
      row.querySelector("[data-notice-dismiss]")?.setAttribute("data-dismiss-label", dismissLabel);
      row.classList.add("motion-safe:animate-rise");
      status.textContent = write(row, options.loading) + ".";
      list.prepend(row);
      empty.hidden = true;
      layout();
      const settle = (state: "success" | "error", value: Text) => {
        if (!row.isConnected || row.hasAttribute("data-dismissed")) return;
        const before = row.offsetHeight;
        row.dataset.state = state;
        status.textContent = write(row, value) + ".";
        const after = row.offsetHeight;
        layout();
        if (!reduced.matches && before !== after) row.animate([{ height: `${before}px` }, { height: `${after}px` }], { duration: 200, easing: snappy() });
        const leave = () => {
          if (!row.isConnected || row.hasAttribute("data-dismissed")) return;
          if (row.matches(":hover") || row.contains(document.activeElement)) { window.setTimeout(leave, 1000); return; }
          dismiss(row);
        };
        window.setTimeout(leave, options.duration ?? 4000);
      };
      task.then(
        (value) => settle("success", typeof options.success === "function" ? options.success(value) : options.success),
        (reason) => settle("error", typeof options.error === "function" ? options.error(reason) : options.error),
      );
      return task;
    };
    (root as HTMLElement & { hazeNotice?: { promise: typeof promise } }).hazeNotice = { promise };
    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-notification-stack]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-notification-stack-listener")) {
    document.documentElement.setAttribute("data-haze-notification-stack-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
