# Story viewer

> Portrait stories frame with segmented progress, tap zones and auto-advance for short sequential updates; a scroll-snap list without script.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/story-viewer`
- File: `src/components/haze/ui/story-viewer.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/avatar, @haze/placeholder, @haze/utils
- Docs page: https://hazeui.com/ui/story-viewer

## Use when
- A short "What's new" sequence of three to six slides in a product or app tour
- Release highlights that read best one at a time in a phone-shaped frame
- Onboarding tips where each step is a title and a sentence

## Avoid when
- Content readers must scan side by side or revisit freely; use carousel
- A stack of cards the reader dismisses one by one; use card-stack
- Long text or forms inside a slide; auto-advance moves on before people finish

## Alternatives
- [carousel](https://hazeui.com/ui/carousel.md)
- [card-stack](https://hazeui.com/ui/card-stack.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique on the page. |
| slides | `{ title: string; body: string; accent?: "default" \| "brand" \| "success" \| "warning" \| "destructive" }[]` | four Ledgerline updates | no | One entry per slide. accent tints the slide surface with a token color. |
| author | `string` | "Ledgerline" | no | Name beside the avatar; its initials fill the avatar. |
| time | `string` | "2 hours ago" | no | Relative time text shown after the author. Written by the caller, never computed. |
| duration | `number` | 5 | no | Seconds each slide stays before the next starts. Ignored under prefers-reduced-motion. |
| headingLevel | `2 \| 3 \| 4 \| 5` | 3 | no | Heading level of each slide title. |
| label | `string` | "What's new in Ledgerline" | no | Accessible name of the viewer. |
| previousLabel | `string` | "Previous slide" | no | Accessible name of the previous button. |
| nextLabel | `string` | "Next slide" | no | Accessible name of the next button. |
| pauseLabel | `string` | "Pause" | no | Accessible name of the pause toggle. |
| slideLabel | `string` | "Slide" | no | Word before the position in announcements and counters, as in "Slide 2 of 4". |
| ofLabel | `string` | "of" | no | Word between position and total in announcements. |
| class | `string` |  | no | Extra classes on the wrapper. |

## Accessibility
- Without script every slide is a list item in a horizontal scroll-snap list inside the frame, each with a visible "1 / 4" counter; the list is focusable so keyboard users can scroll it.
- With script one slide shows at a time and the others are hidden from assistive technology. The segmented progress bars are decorative; the counter text and live region carry the position.
- Auto-advance pauses while the pointer rests on the frame, while keyboard focus is inside it, while the tab is hidden or the viewer is off screen, and through the Pause toggle (aria-pressed).
- Under prefers-reduced-motion nothing advances on its own and the Pause button is removed; readers move with the buttons, tap zones or arrow keys, and the current bar is shown full.
- Slide changes are announced politely only after a reader's own navigation. Automatic advances are never announced.
- Key Left / Right: Go to the previous or next slide while focus is on the frame or one of its buttons
- Key Space: Pause or resume auto-advance while the frame itself has focus
- Key Tab: Move between the frame, Previous, Pause and Next
- Key Enter / Space: Activate the focused button

## Agent prompts

### Install and use

Install the Haze UI component "Story viewer" with `npx shadcn@latest add @haze/story-viewer`. 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 StoryViewer from "@/components/haze/ui/story-viewer.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/story-viewer.md

### Customize with real content

Adapt the Haze story-viewer ui for our product. Replace the demo values of these props with our real content: id, slides, author, time, duration, headingLevel, label, previousLabel, nextLabel, pauseLabel, slideLabel, ofLabel, class. Keep the layout, the heading level rules and these accessibility details: Without script every slide is a list item in a horizontal scroll-snap list inside the frame, each with a visible "1 / 4" counter; the list is focusable so keyboard users can scroll it. With script one slide shows at a time and the others are hidden from assistive technology. The segmented progress bars are decorative; the counter text and live region carry the position. Auto-advance pauses while the pointer rests on the frame, while keyboard focus is inside it, while the tab is hidden or the viewer is off screen, and through the Pause toggle (aria-pressed). Under prefers-reduced-motion nothing advances on its own and the Pause button is removed; readers move with the buttons, tap zones or arrow keys, and the current bar is shown full. Slide changes are announced politely only after a reader's own navigation. Automatic advances are never announced. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using story-viewer, check it fits: use it when a short "what's new" sequence of three to six slides in a product or app tour; release highlights that read best one at a time in a phone-shaped frame; onboarding tips where each step is a title and a sentence. Avoid it when content readers must scan side by side or revisit freely; use carousel; a stack of cards the reader dismisses one by one; use card-stack; long text or forms inside a slide; auto-advance moves on before people finish. Alternatives: @haze/carousel, @haze/card-stack.

## Example requests that should lead here
- Add a What's new story viewer with four release highlights for our mobile app
- Use a slower story viewer of 8 seconds per slide for onboarding tips

## Source

```astro
---
import { ChevronLeft, ChevronRight, Pause, Play } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Avatar from "./avatar.astro";
import Placeholder from "./placeholder.astro";

interface Slide {
  title: string;
  body: string;
  /** Tint of the slide surface. */
  accent?: "default" | "brand" | "success" | "warning" | "destructive";
}

interface Props {
  /** Unique on the page. */
  id: string;
  slides?: Slide[];
  /** Name shown beside the avatar. Its initials fill the avatar. */
  author?: string;
  /** Relative time text beside the author, written by the caller (for example "2 hours ago"). */
  time?: string;
  /** Seconds each slide stays before the next one starts. Ignored under prefers-reduced-motion. */
  duration?: number;
  /** Heading level of each slide title. */
  headingLevel?: 2 | 3 | 4 | 5;
  /** Accessible name of the viewer. */
  label?: string;
  previousLabel?: string;
  nextLabel?: string;
  pauseLabel?: string;
  /** Word before the position in announcements, for example "Slide" in "Slide 2 of 4". */
  slideLabel?: string;
  /** Word between the position and the total, for example "of" in "Slide 2 of 4". */
  ofLabel?: string;
  class?: string;
}

const {
  id,
  slides = [
    { title: "Scheduled payments", body: "Pick a pay date once and Ledgerline sends the transfer that morning. Edit or cancel until midnight before.", accent: "default" },
    { title: "Receipts, matched", body: "Snap a receipt and it attaches itself to the right card transaction. No more month-end hunting.", accent: "default" },
    { title: "Shared budgets", body: "Invite a partner or an accountant to a budget with view-only or edit access.", accent: "default" },
    { title: "Quieter alerts", body: "Choose which balance changes notify you. Payments over your limit always do.", accent: "default" },
  ],
  author = "Ledgerline",
  time = "2 hours ago",
  duration = 5,
  headingLevel = 3,
  label = "What's new in Ledgerline",
  previousLabel = "Previous slide",
  nextLabel = "Next slide",
  pauseLabel = "Pause",
  slideLabel = "Slide",
  ofLabel = "of",
  class: className,
} = Astro.props;

const Heading = ({ 2: "h2", 3: "h3", 4: "h4", 5: "h5" } as const)[headingLevel];
const accents = {
  default: "",
  brand: "bg-muted",
  success: "bg-success/14",
  warning: "bg-warning/14",
  destructive: "bg-destructive/14",
};
const total = slides.length;
const control =
  "inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-frame bg-field text-foreground transition-[background-color,scale] duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-90 active:duration-75 aria-disabled:cursor-default aria-disabled:opacity-52";
---

<div
  id={id}
  data-haze-story-viewer
  data-duration={duration}
  data-slide-label={slideLabel}
  data-of-label={ofLabel}
  class={cn("group mx-auto w-full max-w-80 min-w-0", className)}
>
  <section
    data-sv-frame
    aria-label={label}
    class="relative overflow-hidden rounded-2xl border border-frame bg-card focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"
  >
    <!-- The stage grows past its 9:14 minimum when a slide's text needs more room, so the controls row below never covers content. -->
    <div class="relative grid">
    <div aria-hidden="true" class="pointer-events-none col-start-1 row-start-1 aspect-[9/14]"></div>
    <div aria-hidden="true" class="absolute inset-x-3 top-3 z-10 hidden gap-1 [[data-enhanced]_&]:flex">
      {
        slides.map(() => (
          <div class="h-1 flex-1 overflow-hidden rounded-full bg-foreground/15">
            <span data-sv-fill class="block h-full w-full origin-left rounded-full bg-foreground" style="scale: 0 1"></span>
          </div>
        ))
      }
    </div>

    <ol
      data-sv-list
      tabindex="0"
      class="col-start-1 row-start-1 flex min-w-0 snap-x snap-mandatory overflow-x-auto focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring [[data-enhanced]_&]:overflow-hidden"
    >
      {
        slides.map((slide, index) => (
          <li data-sv-slide class={cn("flex w-full shrink-0 snap-center flex-col gap-4 px-5 pt-9 pb-5", accents[slide.accent ?? "default"])}>
            <div class="flex items-center gap-2">
              <span aria-hidden="true" class="shrink-0"><Avatar name={author} size="sm" /></span>
              <p class="min-w-0 flex-1 text-[0.8125rem]/5 font-medium break-words text-foreground">
                {author} <span class="font-normal text-muted-foreground">· {time}</span>
              </p>
              <p class="shrink-0 text-xs/4 tabular-nums text-muted-foreground">
                <span aria-hidden="true">{index + 1} / {total}</span>
                <span class="sr-only">{slideLabel} {index + 1} {ofLabel} {total}</span>
              </p>
            </div>
            <Placeholder variant="app" class="min-h-12 flex-1 bg-background/60" />
            <div class="grid gap-1.5">
              <Heading data-sv-title class="text-lg/6 font-semibold tracking-tight text-foreground">{slide.title}</Heading>
              <p class="text-sm/6 text-muted-foreground">{slide.body}</p>
            </div>
          </li>
        ))
      }
    </ol>

    <div data-sv-zone="prev" aria-hidden="true" class="absolute top-16 bottom-0 left-0 hidden w-1/3 cursor-pointer touch-manipulation select-none [[data-enhanced]_&]:block"></div>
    <div data-sv-zone="next" aria-hidden="true" class="absolute top-16 right-0 bottom-0 hidden w-2/3 cursor-pointer touch-manipulation select-none [[data-enhanced]_&]:block"></div>
    </div>

    <div class="hidden items-center justify-between gap-2 border-t border-border p-3 [[data-enhanced]_&]:flex">
      <button type="button" data-sv-prev class={control}>
        <ChevronLeft class="size-4" aria-hidden="true" />
        <span class="sr-only">{previousLabel}</span>
      </button>
      <button type="button" data-sv-pause aria-pressed="false" class={cn(control, "group-data-[autoplay=off]:hidden")}>
        <Pause class="size-4 group-data-[paused]:hidden" aria-hidden="true" />
        <Play class="hidden size-4 group-data-[paused]:block" aria-hidden="true" />
        <span class="sr-only">{pauseLabel}</span>
      </button>
      <button type="button" data-sv-next class={control}>
        <ChevronRight class="size-4" aria-hidden="true" />
        <span class="sr-only">{nextLabel}</span>
      </button>
    </div>
  </section>
  <span role="status" aria-live="polite" class="sr-only" data-sv-status></span>
</div>

<script>
  // Enhancement: one slide at a time, auto-advance, tap zones, pause and keyboard. Without script every
  // slide is already readable in the scroll-snap list. Auto-advance is off under prefers-reduced-motion.
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    root.setAttribute("data-enhanced", "");
    const frame = root.querySelector<HTMLElement>("[data-sv-frame]");
    const list = root.querySelector<HTMLElement>("[data-sv-list]");
    const slides = Array.from(root.querySelectorAll<HTMLElement>("[data-sv-slide]"));
    const fills = Array.from(root.querySelectorAll<HTMLElement>("[data-sv-fill]"));
    const prevButton = root.querySelector<HTMLButtonElement>("[data-sv-prev]");
    const nextButton = root.querySelector<HTMLButtonElement>("[data-sv-next]");
    const pauseButton = root.querySelector<HTMLButtonElement>("[data-sv-pause]");
    const status = root.querySelector<HTMLElement>("[data-sv-status]");
    if (!frame || !list || !prevButton || !nextButton || !pauseButton || slides.length === 0) return;

    const total = slides.length;
    const duration = Math.max(1, Number(root.dataset.duration) || 5) * 1000;
    const reduce = matchMedia("(prefers-reduced-motion: reduce)");
    const holds = new Set<string>(["offscreen"]);
    let autoplay = !reduce.matches;
    let index = 0;
    let anim: Animation | null = null;

    list.removeAttribute("tabindex");
    frame.tabIndex = 0;

    const sync = () => {
      if (!anim || anim.playState === "finished") return;
      if (holds.size > 0) anim.pause();
      else anim.play();
    };
    const hold = (reason: string, on: boolean) => {
      if (on) holds.add(reason);
      else holds.delete(reason);
      sync();
    };

    const paint = () => {
      fills.forEach((fill, i) => {
        fill.style.scale = i < index || (i === index && !autoplay) ? "1 1" : "0 1";
      });
      prevButton.setAttribute("aria-disabled", String(index === 0));
      nextButton.setAttribute("aria-disabled", String(index === total - 1));
    };

    const show = (target: number, user: boolean) => {
      const next = Math.min(total - 1, Math.max(0, target));
      // A clamped Prev on the first slide or Next on the last one changes nothing: keep the running progress.
      if (user && next === index) return;
      const changed = next !== index;
      anim?.cancel();
      anim = null;
      index = next;
      slides.forEach((slide, i) => {
        slide.hidden = i !== index;
      });
      paint();
      if (autoplay) {
        anim = fills[index]!.animate([{ scale: "0 1" }, { scale: "1 1" }], { duration, easing: "linear", fill: "forwards" });
        anim.onfinish = () => {
          if (index < total - 1) show(index + 1, false);
        };
        sync();
      }
      if (!changed) return;
      if (!reduce.matches) {
        slides[index]!.animate([{ opacity: 0.6 }, { opacity: 1 }], { duration: 160, easing: "cubic-bezier(0.22, 1, 0.36, 1)" });
      }
      if (user && status) {
        const title = slides[index]!.querySelector("[data-sv-title]")?.textContent ?? "";
        const text = `${root.dataset.slideLabel} ${index + 1} ${root.dataset.ofLabel} ${total}: ${title}`;
        if (status.textContent !== text) status.textContent = text;
      }
    };

    const setAutoplay = (on: boolean) => {
      autoplay = on;
      root.dataset.autoplay = on ? "on" : "off";
      show(index, false);
    };

    const togglePause = () => {
      const on = !holds.has("user");
      hold("user", on);
      pauseButton.setAttribute("aria-pressed", String(on));
      root.toggleAttribute("data-paused", on);
    };

    // Tap zones: left third goes back, right two thirds go forward, press and hold pauses.
    let holdTimer: number | undefined;
    let held = false;
    let suppress = false;
    root.querySelectorAll<HTMLElement>("[data-sv-zone]").forEach((zone) => {
      const forward = zone.dataset.svZone === "next";
      zone.addEventListener("pointerdown", () => {
        held = false;
        suppress = false;
        window.clearTimeout(holdTimer);
        holdTimer = window.setTimeout(() => {
          held = true;
          hold("hold", true);
        }, 250);
      });
      const release = () => {
        window.clearTimeout(holdTimer);
        if (held) {
          hold("hold", false);
          suppress = true;
        }
      };
      zone.addEventListener("pointerup", release);
      zone.addEventListener("pointercancel", release);
      zone.addEventListener("pointerleave", release);
      zone.addEventListener("contextmenu", (event) => event.preventDefault());
      zone.addEventListener("click", () => {
        if (suppress) {
          suppress = false;
          return;
        }
        show(forward ? index + 1 : index - 1, true);
      });
    });

    prevButton.addEventListener("click", () => show(index - 1, true));
    nextButton.addEventListener("click", () => show(index + 1, true));
    pauseButton.addEventListener("click", togglePause);

    root.addEventListener("keydown", (event) => {
      if (event.altKey || event.ctrlKey || event.metaKey) return;
      if (event.key === "ArrowLeft") {
        event.preventDefault();
        show(index - 1, true);
      } else if (event.key === "ArrowRight") {
        event.preventDefault();
        show(index + 1, true);
      } else if (event.key === " " && event.target === frame && autoplay) {
        event.preventDefault();
        togglePause();
      }
    });

    // Pause while the pointer rests on the viewer, while keyboard focus is inside it, and while it is off screen.
    frame.addEventListener("pointerenter", (event) => {
      if (event.pointerType === "mouse") hold("hover", true);
    });
    frame.addEventListener("pointerleave", () => hold("hover", false));
    root.addEventListener("focusin", (event) => {
      if ((event.target as HTMLElement).matches(":focus-visible")) hold("focus", true);
    });
    root.addEventListener("focusout", (event) => {
      if (!root.contains(event.relatedTarget as Node | null)) hold("focus", false);
    });
    root.addEventListener("haze:story-visibility", () => hold("hidden", document.hidden));
    let observer: IntersectionObserver | undefined;
    const onReduce = () => {
      if (!root.isConnected) {
        cleanup();
        return;
      }
      setAutoplay(!reduce.matches);
    };
    // Called once the root has left the document (page swap), so nothing keeps running on a detached viewer.
    const cleanup = () => {
      observer?.disconnect();
      reduce.removeEventListener("change", onReduce);
      anim?.cancel();
      anim = null;
    };
    if ("IntersectionObserver" in window) {
      observer = new IntersectionObserver((entries) => {
        if (!root.isConnected) {
          cleanup();
          return;
        }
        entries.forEach((entry) => hold("offscreen", !entry.isIntersecting));
      });
      observer.observe(frame);
    } else {
      holds.delete("offscreen");
    }
    reduce.addEventListener("change", onReduce);
    document.addEventListener("astro:before-swap", cleanup, { once: true });

    hold("hidden", document.hidden);
    root.dataset.autoplay = autoplay ? "on" : "off";
    show(0, false);
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-story-viewer]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-story-viewer-listener")) {
    document.documentElement.setAttribute("data-haze-story-viewer-listener", "");
    document.addEventListener("astro:page-load", init);
    document.addEventListener("visibilitychange", () => {
      document.querySelectorAll("[data-haze-story-viewer]").forEach((root) => root.dispatchEvent(new Event("haze:story-visibility")));
    });
  }
</script>
```
