Image Viewer
Opens a thumbnail gallery in a focus-managed lightbox with image navigation and a zoom toggle.
pnpm dlx shadcn@latest add @haze/image-viewer---
import { ChevronLeft, ChevronRight, ZoomIn } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";
import Dialog from "./dialog.astro";
interface ImageItem { src: string; alt: string; caption?: string; thumbnail?: string; fit?: "cover" | "contain" }
interface Props {
id: string;
title?: string;
items: ImageItem[];
emptyLabel?: string;
headingLevel?: 2 | 3 | 4 | 5 | 6;
class?: string;
}
const { id, title = "Image gallery", items, emptyLabel = "No images available.", headingLevel, class: className } = Astro.props;
const first = items[0];
---
<div data-haze-image-viewer class={cn("min-w-0", className)}>
{first ? (
<>
<ul aria-label={title} role="list" class="grid grid-cols-2 gap-2 sm:grid-cols-3">
{items.map((image, index) => (
<li class="min-w-0">
<a href={image.src} data-viewer-thumbnail={index} data-viewer-alt={image.alt} data-viewer-caption={image.caption} data-viewer-fit={image.fit}
class="group/thumb grid h-full min-w-0 grid-rows-[auto_1fr] overflow-hidden rounded-xl border border-frame bg-card text-[0.8125rem]/5 text-card-foreground transition-[border-color,translate,scale] duration-150 ease-snappy hover:-translate-y-0.5 hover:border-frame-strong focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75">
<span class="block overflow-hidden bg-muted">
<img src={image.thumbnail ?? image.src} alt={image.caption ? "" : image.alt} loading="lazy" decoding="async"
class={cn("aspect-video w-full transition-transform duration-300 ease-snappy group-hover/thumb:scale-105", image.fit === "contain" ? "object-contain p-6" : "object-cover")} />
</span>
{image.caption && <span class="px-3 py-2 text-sm font-medium wrap-anywhere">{image.caption}</span>}
</a>
</li>
))}
</ul>
<Dialog id={id} title={title} trigger={false} size="lg" headingLevel={headingLevel} class="[&>div]:p-4 sm:[&>div]:p-6">
<figure class="grid min-w-0 gap-3">
<div data-viewer-pan role="region" aria-label="Image preview"
class="group aspect-video max-h-[48dvh] w-full overflow-auto rounded-lg bg-muted focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring">
<img src={first.src} alt={first.alt} data-viewer-image data-fit={first.fit} loading="lazy" decoding="async"
class="size-full max-w-none object-cover data-[fit=contain]:object-contain data-[fit=contain]:p-10 group-data-[zoomed]:data-[fit=contain]:p-0 group-data-[zoomed]:h-auto group-data-[zoomed]:w-[200%] group-data-[zoomed]:object-top" />
</div>
<div class="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
<figcaption data-viewer-caption-output class="min-w-0 basis-full truncate text-[0.8125rem]/5 font-medium sm:flex-1 sm:basis-0 text-foreground">{first.caption ?? first.alt}</figcaption>
<div class="flex shrink-0 items-center gap-0.5">
<Button variant="ghost" size="icon" aria-label="Previous image" data-viewer-prev hidden={items.length < 2} class="size-9 [&[hidden]]:hidden"><ChevronLeft aria-hidden="true" /></Button>
<span data-viewer-count class="px-1 text-[0.8125rem]/5 text-muted-foreground tabular-nums" aria-live="polite">1 of {items.length}</span>
<Button variant="ghost" size="icon" aria-label="Next image" data-viewer-next hidden={items.length < 2} class="size-9 [&[hidden]]:hidden"><ChevronRight aria-hidden="true" /></Button>
</div>
<Button variant="ghost" size="icon" aria-label="Zoom image" aria-pressed="false" data-viewer-zoom class="ms-auto size-9 shrink-0 sm:ms-0 aria-pressed:bg-accent aria-pressed:text-foreground"><ZoomIn aria-hidden="true" /></Button>
</div>
</figure>
</Dialog>
</>
) : <p class="text-[0.8125rem]/6 text-muted-foreground">{emptyLabel}</p>}
</div>
<script>
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const dialog = root.querySelector<HTMLDialogElement>("dialog");
const image = root.querySelector<HTMLImageElement>("[data-viewer-image]");
const pan = root.querySelector<HTMLElement>("[data-viewer-pan]");
const caption = root.querySelector<HTMLElement>("[data-viewer-caption-output]");
const count = root.querySelector<HTMLElement>("[data-viewer-count]");
const prev = root.querySelector<HTMLButtonElement>("[data-viewer-prev]");
const next = root.querySelector<HTMLButtonElement>("[data-viewer-next]");
const zoom = root.querySelector<HTMLButtonElement>("[data-viewer-zoom]");
if (!dialog || typeof dialog.showModal !== "function" || !image || !pan || !caption || !count || !prev || !next || !zoom) return;
const links = Array.from(root.querySelectorAll<HTMLAnchorElement>("[data-viewer-thumbnail]"));
let index = 0;
let opener: HTMLAnchorElement | undefined;
const setZoom = (zoomed: boolean) => {
zoom.setAttribute("aria-pressed", String(zoomed));
pan.toggleAttribute("data-zoomed", zoomed);
if (zoomed) pan.tabIndex = 0; else pan.removeAttribute("tabindex");
pan.scrollTo(0, 0);
};
const show = (position: number) => {
index = (position + links.length) % links.length;
const link = links[index];
image.src = link.href;
image.alt = link.dataset.viewerAlt ?? "";
image.dataset.fit = link.dataset.viewerFit ?? "";
caption.textContent = link.dataset.viewerCaption ?? image.alt;
count.textContent = `${index + 1} of ${links.length}`;
setZoom(false);
};
for (const [position, link] of links.entries()) {
link.setAttribute("aria-haspopup", "dialog");
link.setAttribute("aria-controls", dialog.id);
link.addEventListener("click", (event) => {
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
event.preventDefault();
opener = link;
show(position);
if (!dialog.open) dialog.showModal();
});
}
dialog.addEventListener("close", () => { opener?.focus({ preventScroll: true }); });
prev.addEventListener("click", () => show(index - 1));
next.addEventListener("click", () => show(index + 1));
zoom.addEventListener("click", () => setZoom(!pan.hasAttribute("data-zoomed")));
dialog.addEventListener("keydown", (event) => {
if (event.target === pan && pan.hasAttribute("data-zoomed")) return;
if (links.length < 2 || (event.key !== "ArrowLeft" && event.key !== "ArrowRight")) return;
event.preventDefault();
show(index + (event.key === "ArrowLeft" ? -1 : 1));
});
root.setAttribute("data-enhanced", "");
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-image-viewer]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-image-viewer-listener")) {
document.documentElement.setAttribute("data-haze-image-viewer-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- Previewing full-size screenshots, design assets, or attachments.
- Users need to inspect details without leaving the page.
When not to use
- Several images need to be compared side by side.
Installation
Add the Haze registry to components.json once, then install Image Viewer with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/image-viewernpx shadcn@latest add @haze/image-vieweryarn dlx shadcn@latest add @haze/image-viewerbunx --bun shadcn@latest add @haze/image-viewerFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique ID for the lightbox dialog. |
| title | string | Image gallery | Name for the gallery and dialog. |
| items* | ImageItem[] | – | Images with a source, alt text, optional caption, and optional thumbnail. |
| emptyLabel | string | – | Message shown if there are no images. |
| headingLevel | 2 | 3 | 4 | 5 | 6 | 2 | Level of the dialog heading. |
| class | string | – | Classes for the gallery wrapper. |
Keyboard interactions
- ←→
- Browse images unless focused on a zoomed preview.
- Tab
- Reach zoom, navigation, and the preview surface.
- Escape
- Close the viewer and return to the thumbnail.
Accessibility
- Thumbnail links open the source image when scripting is unavailable.
- The current image index is announced and focus returns to the opening thumbnail.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Image Viewer" with `npx shadcn@latest add @haze/image-viewer`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/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 ImageViewer from "@/components/haze/ui/image-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: http://localhost:4329/ui/image-viewer.md
Customize with real content
Adapt the Haze image-viewer ui for our product. Replace the demo values of these props with our real content: id, title, items, emptyLabel, headingLevel, class. Keep the layout, the heading level rules and these accessibility details: Thumbnail links open the source image when scripting is unavailable. The current image index is announced and focus returns to the opening thumbnail. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using image-viewer, check it fits: use it when previewing full-size screenshots, design assets, or attachments.; users need to inspect details without leaving the page.. Avoid it when several images need to be compared side by side.. Alternatives: @haze/carousel, @haze/compare-slider, @haze/dialog.
Dependencies
- npm: @lucide/astro
- @haze/button
- @haze/dialog
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.