# Gallery

A collection book for anything: items, characters, fish, recipes. Locked entries are silhouettes, a progress bar counts what is found, and opening an entry shows a big view with previous and next.

Docs: https://cozy-ui.solo.engineer/docs/components/gallery/

Install: `npx shadcn@latest add @cozy/gallery`

### Usage

```tsx
import { Gallery } from "@/components/ui/gallery"

<Gallery entries={[{ id: "carp", name: "River carp", image: <Fish />, rarity: "rare" }]} />
```

### Props

| Prop | Type | Default | Description |
|---|---|---|---|
| entries | `GalleryEntry<T>[]` | – | { id, name, label?, image?, rarity?, group?, unlocked?, caption?, description?, badge?, data? }. |
| groups / search | `{ id, label }[] / boolean \| string` | – | Filter tabs and a search box (matches found entries). |
| showProgress / progressLabel | `boolean / ReactNode` | `true / "Found"` | The found/total bar. |
| cardSize | `number` | `132` | Minimum card width in px; cards grow to fill the row. |
| cardHeight / artScale | `number` | `row height / 0.74` | Fixed card height in px (by default every card in a row matches the tallest), and art size as a share of the card width. |
| lockedName / openLocked | `ReactNode / boolean` | `"???" / false` | Name for locked entries, and whether they open. |
| openId / onOpenChange | `string \| null` | – | Control which entry is open. |
| renderCard / renderDetail / detailActions | `(entry) => ReactNode` | – | Your own card inside, big-view body and buttons. |

### Example

```tsx
import { Gallery } from "@/components/ui/gallery";
import { COLLECTION } from "./game-data";

export default function GalleryDemo() {
  return (
    <Gallery
      className="w-full"
      title="Collection"
      entries={COLLECTION}
      groups={[{ id: "crops", label: "Crops" }, { id: "fish", label: "Fish" }, { id: "decor", label: "Decor" }, { id: "treasure", label: "Treasure" }]}
      search
      cardSize={120}
      artScale={0.7}
    />
  );
}
```

### Source (components/ui/gallery.tsx)

```tsx
import * as React from "react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
import { GameIcon, RarityBadge, rarityStyle, type Rarity, type RarityConfig } from "./game-core";

/* A collection book for anything: items, characters, fish, recipes. Entries
   you have not found yet show as silhouettes; opening an entry shows a big
   view with previous and next. Bring your own card and detail renderers. */

export type GalleryEntry<T = unknown> = {
  id: string;
  name: React.ReactNode;
  /** Plain-text name for search and accessible labels (defaults to name if it is a string). */
  label?: string;
  /** A React node or an image URL. */
  image?: React.ReactNode;
  rarity?: Rarity;
  /** Group id for the filter tabs. */
  group?: string;
  /** False shows a silhouette and hides the name. Default true. */
  unlocked?: boolean;
  /** Small text under the name, e.g. "Spring · River". */
  caption?: React.ReactNode;
  description?: React.ReactNode;
  /** Shown on the card corner, e.g. "×3" or "New". */
  badge?: React.ReactNode;
  data?: T;
};

export type GalleryGroup = { id: string; label: React.ReactNode };

type GalleryProps<T> = Omit<React.ComponentProps<"div">, "children"> & {
  entries: GalleryEntry<T>[];
  groups?: GalleryGroup[];
  allLabel?: React.ReactNode;
  /** Show a search box (true) or set its placeholder. */
  search?: boolean | string;
  /** Show the "found / total" progress bar. Default true. */
  showProgress?: boolean;
  progressLabel?: React.ReactNode;
  /** Minimum card width in px; cards grow to fill the row. Default 132. */
  cardSize?: number;
  /** Fixed card height in px. By default every card in a row matches the tallest one. */
  cardHeight?: number;
  /** Art size as a share of the card width, 0–1. Default 0.74. */
  artScale?: number;
  /** Name shown for locked entries. Default "???". */
  lockedName?: React.ReactNode;
  /** Let people open locked entries (as a silhouette). Default false. */
  openLocked?: boolean;
  rarities?: Record<string, RarityConfig>;
  /** Controlled open entry id. */
  openId?: string | null;
  onOpenChange?: (id: string | null, entry: GalleryEntry<T> | null) => void;
  /** Replace the card's inside (keep it small). */
  renderCard?: (entry: GalleryEntry<T>, state: { locked: boolean }) => React.ReactNode;
  /** Replace the body of the big view. */
  renderDetail?: (entry: GalleryEntry<T>) => React.ReactNode;
  /** Buttons in the big view, e.g. "Set as avatar". */
  detailActions?: (entry: GalleryEntry<T>) => React.ReactNode;
  emptyText?: React.ReactNode;
  title?: React.ReactNode;
  label?: string;
};

const plain = (e: GalleryEntry<unknown>) => e.label ?? (typeof e.name === "string" ? e.name : e.id);

function Gallery<T = unknown>({
  entries, groups, allLabel = "All", search, showProgress = true, progressLabel = "Found", cardSize = 132, cardHeight, artScale, lockedName = "???",
  openLocked = false, rarities, openId: openProp, onOpenChange, renderCard, renderDetail, detailActions, emptyText = "Nothing here yet",
  title, label, className, style, ...props
}: GalleryProps<T>) {
  const [group, setGroup] = React.useState("__all");
  const [query, setQuery] = React.useState("");
  const [openInner, setOpenInner] = React.useState<string | null>(null);
  const openId = openProp !== undefined ? openProp : openInner;
  const [focus, setFocus] = React.useState(0);
  const [cols, setCols] = React.useState(4);
  const gridRef = React.useRef<HTMLDivElement>(null);

  const q = query.trim().toLowerCase();
  const visible = entries.filter((e) => (group === "__all" || e.group === group) && (!q || ((e.unlocked ?? true) && plain(e).toLowerCase().includes(q))));
  const found = entries.filter((e) => e.unlocked ?? true).length;
  const openable = (e: GalleryEntry<T>) => openLocked || (e.unlocked ?? true);
  const openIdx = visible.findIndex((e) => e.id === openId);
  const current = openIdx >= 0 ? visible[openIdx] : entries.find((e) => e.id === openId) ?? null;

  const setOpen = (id: string | null) => {
    if (openProp === undefined) setOpenInner(id);
    onOpenChange?.(id, id ? entries.find((e) => e.id === id) ?? null : null);
  };
  const step = (d: number) => {
    if (openIdx < 0) return;
    for (let k = 1; k <= visible.length; k++) {
      const n = visible[(openIdx + d * k + visible.length * k) % visible.length];
      if (openable(n)) { setOpen(n.id); return; }
    }
  };

  React.useEffect(() => {
    const el = gridRef.current;
    if (!el) return;
    const ro = new ResizeObserver(() => setCols(Math.max(1, getComputedStyle(el).gridTemplateColumns.split(" ").filter(Boolean).length)));
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  const focusCard = (p: number) => {
    const n = Math.max(0, Math.min(visible.length - 1, p));
    setFocus(n);
    gridRef.current?.querySelector<HTMLElement>(`[data-pos="${n}"]`)?.focus();
  };
  const onKeyDown = (e: React.KeyboardEvent) => {
    const map: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -cols, ArrowDown: cols };
    if (e.key in map) { e.preventDefault(); focusCard(focus + map[e.key]); }
    else if (e.key === "Home") { e.preventDefault(); focusCard(0); }
    else if (e.key === "End") { e.preventDefault(); focusCard(visible.length - 1); }
  };

  const name = label ?? (typeof title === "string" ? title : "Gallery");
  const locked = current ? !(current.unlocked ?? true) : false;

  return (
    <div data-slot="gallery" className={cn("cz-gallery", className)} style={{ "--card": `${cardSize}px`, ...(cardHeight ? { "--card-h": `${cardHeight}px` } : null), ...(artScale ? { "--art": `${artScale * 100}%` } : null), ...style } as React.CSSProperties} {...props}>
      {(title != null || showProgress) && (
        <div className="cz-gallery__head">
          {title != null && <div className="cz-gallery__title">{title}</div>}
          {showProgress && (
            <div className="cz-gallery__progress">
              <span>{progressLabel} {found} / {entries.length}</span>
              <div className="cz-statbar__track" role="meter" aria-label={`${found} of ${entries.length} found`} aria-valuemin={0} aria-valuemax={entries.length} aria-valuenow={found}>
                <div className="cz-statbar__fill" style={{ width: `${entries.length ? (found / entries.length) * 100 : 0}%`, "--fill": "var(--cz-reward)" } as React.CSSProperties} />
              </div>
            </div>
          )}
        </div>
      )}
      {(groups?.length || search) ? (
        <div className="cz-inventory__tools">
          {groups?.length ? (
            <div className="cz-inventory__tabs" role="tablist" aria-label="Groups">
              {[{ id: "__all", label: allLabel }, ...groups].map((g) => (
                <button key={g.id} type="button" role="tab" aria-selected={group === g.id} className="cz-inventory__tab" onClick={() => { setGroup(g.id); setFocus(0); }}>{g.label}</button>
              ))}
            </div>
          ) : null}
          {search ? <input type="search" className="cz-input cz-inventory__search" placeholder={typeof search === "string" ? search : "Search…"} aria-label="Search" value={query} onChange={(e) => { setQuery(e.target.value); setFocus(0); }} /> : null}
        </div>
      ) : null}
      <div ref={gridRef} role="list" aria-label={name} className="cz-gallery__grid" onKeyDown={onKeyDown}>
        {visible.length === 0 && <div className="cz-inventory__empty">{emptyText}</div>}
        {visible.map((e, pos) => {
          const isLocked = !(e.unlocked ?? true);
          return (
            <div role="listitem" key={e.id} className="cz-gallery__cell">
              <button
                type="button"
                data-pos={pos}
                tabIndex={pos === Math.min(focus, visible.length - 1) ? 0 : -1}
                className="cz-gallery__card"
                data-locked={isLocked || undefined}
                data-rarity={e.rarity}
                style={rarityStyle(isLocked ? undefined : e.rarity, rarities)}
                aria-label={isLocked ? `Not found yet${openLocked ? "" : ", locked"}` : plain(e)}
                aria-disabled={!openable(e) || undefined}
                onFocus={() => setFocus(pos)}
                onClick={() => openable(e) && setOpen(e.id)}
              >
                {renderCard ? renderCard(e, { locked: isLocked }) : (
                  <>
                    <span className="cz-gallery__art"><GameIcon icon={e.image} alt="" /></span>
                    <span className="cz-gallery__name">{isLocked ? lockedName : e.name}</span>
                    {!isLocked && e.caption != null && <span className="cz-gallery__caption">{e.caption}</span>}
                    {!isLocked && e.badge != null && <span className="cz-gallery__badge">{e.badge}</span>}
                  </>
                )}
              </button>
            </div>
          );
        })}
      </div>

      <Dialog open={!!current} onOpenChange={(o) => !o && setOpen(null)}>
        {current && (
          <DialogContent className="cz-gallery__viewer" style={rarityStyle(locked ? undefined : current.rarity, rarities)}>
            <div className="cz-gallery__stage" data-locked={locked || undefined}><GameIcon icon={current.image} alt="" /></div>
            <DialogTitle className="cz-gallery__vname">{locked ? lockedName : current.name}</DialogTitle>
            {!locked && (current.rarity || current.caption != null) && (
              <div className="cz-gallery__vmeta"><RarityBadge rarity={current.rarity} rarities={rarities} />{current.caption}</div>
            )}
            {renderDetail && !locked ? renderDetail(current) : (
              <DialogDescription className="cz-gallery__vdesc">{locked ? "Not found yet. Keep exploring!" : current.description ?? ""}</DialogDescription>
            )}
            <div className="cz-gallery__vnav" onKeyDown={(e) => { if (e.key === "ArrowLeft") { e.preventDefault(); step(-1); } if (e.key === "ArrowRight") { e.preventDefault(); step(1); } }}>
              <Button size="sm" variant="outline" onClick={() => step(-1)} disabled={openIdx < 0} aria-label="Previous">‹ Prev</Button>
              {openIdx >= 0 && <span className="cz-gallery__count">{openIdx + 1} / {visible.length}</span>}
              {!locked && detailActions?.(current)}
              <Button size="sm" variant="outline" onClick={() => step(1)} disabled={openIdx < 0} aria-label="Next">Next ›</Button>
            </div>
          </DialogContent>
        )}
      </Dialog>
    </div>
  );
}

export { Gallery };
export type { GalleryProps };
```

npm: `import { Gallery } from "@0xtrou/cozy-ui"` (after `npm install @0xtrou/cozy-ui` and `import "@0xtrou/cozy-ui/styles.css"`).
