# Inventory

A bag of item slots with drag and drop (mouse, pen and touch), keyboard moving, stack merging, locked slots, category tabs, search, sort and item tooltips. Controlled or uncontrolled.

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

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

### Usage

```tsx
import { Inventory, type InventorySlots } from "@/components/ui/inventory"

const [items, setItems] = useState<InventorySlots>(bag)
<Inventory items={items} onItemsChange={(next) => setItems(next)} slots={24} />
```

### Props

| Prop | Type | Default | Description |
|---|---|---|---|
| items / defaultItems | `(GameItem \| null)[]` | – | Slot contents in order; null is empty. Use items + onItemsChange for controlled, defaultItems for uncontrolled. |
| onItemsChange | `(items, change) => void` | – | New slots after a move, merge or sort. change is { type: "move" | "merge" | "sort", from?, to?, moved?, sortId? }. |
| slots | `number` | `items.length` | Total slots; pads with empty ones. |
| lockedFrom | `number` | – | Slots from this index on are locked (bag upgrades). |
| columns / slotSize | `number` | `fill / 64` | Fixed column count and tile size in px. |
| selected / defaultSelected / onSelect | `number \| null` | – | Selected slot index, controlled or not. |
| onActivate | `(item, index) => void` | – | Double-click or Enter: use, equip or eat. |
| canMove | `(from, to, items) => boolean` | – | Return false to refuse a move, e.g. quest items or a full slot type. |
| movable / stacking | `boolean` | `true` | Turn off moving, or merging of stacks with the same stackKey (or name) up to maxStack. |
| categories | `{ id, label, icon?, match? }[]` | – | Filter tabs. Items match on item.category unless you pass match. Moving pauses while filtered. |
| search / sorts | `boolean \| string / { id, label, compare }[]` | – | A search box, and sort buttons that reorder the bag. |
| tooltip / formatValue / rarities | `boolean / fn / Record` | `true` | Item tooltips, how values print, and custom rarity labels and colours. |
| title / showCapacity / headerEnd / placeholder / emptyText | `ReactNode` | – | Header, used/total count, extra controls, empty-slot content and the no-match text. |

Keyboard: arrows move between slots, Space picks an item up and drops it, Escape cancels, Enter calls onActivate. Moves are announced to screen readers.

GameItem: { id, name, icon, quantity, maxStack, stackKey, rarity, category, type, description, stats, value, level, meter, corner, locked, disabled, tags, data }. Put anything your game needs in data.

applyMove(items, from, to, stacking) is exported, so a server or game loop can apply the same rules.

### Example

```tsx
import { useState } from "react";
import { Inventory, type InventorySlots } from "@/components/ui/inventory";
import { ItemInfo } from "@/components/ui/item-info";
import { BAG, CATEGORIES, SORTS } from "./game-data";

export default function InventoryDemo() {
  const [items, setItems] = useState<InventorySlots>(BAG);
  const [selected, setSelected] = useState<number | null>(2);
  const item = selected != null ? items[selected] : null;
  return (
    <div className="flex w-full flex-wrap items-stretch justify-center gap-4">
      <Inventory
        title="Backpack"
        items={items}
        onItemsChange={(next) => setItems(next)}
        slots={24}
        lockedFrom={18}
        columns={6}
        selected={selected}
        onSelect={(_, i) => setSelected(i)}
        categories={CATEGORIES}
        search
        sorts={SORTS.slice(0, 1)}
        formatValue={(v) => `${v} coins`}
      />
      {item ? (
        <ItemInfo
          item={item}
          formatValue={(v) => `${v} coins`}
          actions={[
            { id: "use", label: "Use", variant: "reward", shortcut: "E" },
            { id: "sell", label: "Sell", variant: "secondary" },
          ]}
        />
      ) : (
        <p className="m-0 max-w-[240px] text-sm text-text-muted">Pick a slot. Drag items to move them; drop a stack on the same item to merge.</p>
      )}
    </div>
  );
}
```

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

```tsx
import * as React from "react";
import { cn } from "@/lib/utils";
import { TooltipProvider } from "@/components/ui/tooltip";
import { GameIcon, ItemSlot, rarityLabel, rarityStyle, type GameItem, type RarityConfig } from "./game-core";
import { ItemTooltip } from "./item-info";

/* A bag of item slots. Works controlled (items + onItemsChange) or
   uncontrolled (defaultItems). Drag and drop works with mouse, pen and touch;
   keyboard users pick an item up with Space, move with the arrows and drop
   with Space (Escape cancels). Stacks of the same item merge up to maxStack. */

export type InventorySlots = (GameItem | null)[];
export type InventoryChange =
  | { type: "move"; from: number; to: number }
  | { type: "merge"; from: number; to: number; moved: number }
  | { type: "sort"; sortId: string };

export type InventoryCategory = { id: string; label: React.ReactNode; match?: (item: GameItem) => boolean; icon?: React.ReactNode };
export type InventorySort = { id: string; label: string; compare: (a: GameItem, b: GameItem) => number };

type InventoryProps = Omit<React.ComponentProps<"div">, "onSelect" | "defaultValue"> & {
  /** Slot contents in order; null is an empty slot. Controlled. */
  items?: InventorySlots;
  defaultItems?: InventorySlots;
  onItemsChange?: (items: InventorySlots, change: InventoryChange) => void;
  /** Total slots, padded with empties. Default: items.length. */
  slots?: number;
  /** Slots from this index on are locked (bag upgrades). */
  lockedFrom?: number;
  /** Fixed column count; default fills the width. */
  columns?: number;
  /** Tile size in px. Default 64. */
  slotSize?: number;
  selected?: number | null;
  defaultSelected?: number | null;
  onSelect?: (item: GameItem | null, index: number) => void;
  /** Double click or Enter on an item. */
  onActivate?: (item: GameItem, index: number) => void;
  /** Return false to refuse a move (e.g. quest items). */
  canMove?: (from: number, to: number, items: InventorySlots) => boolean;
  /** Turn off drag and drop and keyboard moving. */
  movable?: boolean;
  /** Merge stacks with the same stackKey (or name). Default true. */
  stacking?: boolean;
  /** Tabs to filter by category; an "All" tab is added first. */
  categories?: InventoryCategory[];
  allLabel?: React.ReactNode;
  /** Show a search box (true) or set its placeholder. */
  search?: boolean | string;
  /** Sort buttons; sorting reorders the bag and emits a "sort" change. */
  sorts?: InventorySort[];
  /** Show compact ItemInfo on hover and focus. Default true. */
  tooltip?: boolean;
  /** Formats item values in tooltips. */
  formatValue?: (value: number, item: GameItem) => React.ReactNode;
  rarities?: Record<string, RarityConfig>;
  /** Content for empty slots (e.g. a faint icon). */
  placeholder?: React.ReactNode;
  title?: React.ReactNode;
  /** Show "used / total" in the header. Default true when title is set. */
  showCapacity?: boolean;
  /** Text when a filter matches nothing. */
  emptyText?: React.ReactNode;
  /** Extra controls at the right of the header. */
  headerEnd?: React.ReactNode;
  /** Accessible name; defaults to the title or "Inventory". */
  label?: string;
};

const keyOf = (i: GameItem) => i.stackKey ?? i.name;

function applyMove(items: InventorySlots, from: number, to: number, stacking: boolean): [InventorySlots, InventoryChange] {
  const next = items.slice();
  const a = next[from], b = next[to];
  if (stacking && a && b && keyOf(a) === keyOf(b) && (b.maxStack ?? 1) > 1) {
    const room = (b.maxStack ?? 1) - (b.quantity ?? 1);
    if (room > 0) {
      const moved = Math.min(room, a.quantity ?? 1);
      next[to] = { ...b, quantity: (b.quantity ?? 1) + moved };
      const left = (a.quantity ?? 1) - moved;
      next[from] = left > 0 ? { ...a, quantity: left } : null;
      return [next, { type: "merge", from, to, moved }];
    }
  }
  next[from] = b ?? null;
  next[to] = a ?? null;
  return [next, { type: "move", from, to }];
}

function Inventory({
  items: itemsProp, defaultItems, onItemsChange, slots, lockedFrom, columns, slotSize = 64,
  selected: selectedProp, defaultSelected = null, onSelect, onActivate, canMove, movable = true, stacking = true,
  categories, allLabel = "All", search, sorts, tooltip = true, formatValue, rarities, placeholder,
  title, showCapacity, emptyText = "Nothing here", headerEnd, label, className, style, ...props
}: InventoryProps) {
  const [inner, setInner] = React.useState<InventorySlots>(() => defaultItems ?? []);
  const raw = itemsProp ?? inner;
  const total = Math.max(slots ?? 0, raw.length);
  const items = React.useMemo(() => Array.from({ length: total }, (_, i) => raw[i] ?? null), [raw, total]);
  const [selInner, setSelInner] = React.useState<number | null>(defaultSelected);
  const selected = selectedProp !== undefined ? selectedProp : selInner;
  const [category, setCategory] = React.useState<string>("__all");
  const [query, setQuery] = React.useState("");
  const [focus, setFocus] = React.useState(0);
  const [grabbed, setGrabbed] = React.useState<number | null>(null);
  const [drag, setDrag] = React.useState<{ from: number; x: number; y: number; over: number | null } | null>(null);
  const [announce, setAnnounce] = React.useState("");
  const gridRef = React.useRef<HTMLDivElement>(null);
  const down = React.useRef<{ index: number; x: number; y: number; id: number } | null>(null);
  const [cols, setCols] = React.useState(columns ?? 6);
  const baseId = React.useId();

  const isLocked = (i: number) => lockedFrom != null && i >= lockedFrom;
  const cat = categories?.find((c) => c.id === category);
  const q = query.trim().toLowerCase();
  const filtering = category !== "__all" || q !== "";
  const visible = React.useMemo(() => {
    const all = items.map((item, index) => ({ item, index }));
    if (!filtering) return all;
    return all.filter(({ item }) => item && (!cat || (cat.match ? cat.match(item) : item.category === cat.id)) && (!q || `${item.name} ${item.type ?? ""} ${(item.tags ?? []).join(" ")}`.toLowerCase().includes(q)));
  }, [items, filtering, cat, q]);
  const canDrag = movable && !filtering;

  // measure columns so arrow keys move by rows
  React.useEffect(() => {
    if (columns) { setCols(columns); return; }
    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();
  }, [columns]);

  const commit = (next: InventorySlots, change: InventoryChange) => {
    if (itemsProp === undefined) setInner(next);
    onItemsChange?.(next, change);
  };
  const doMove = (from: number, to: number) => {
    if (from === to || isLocked(to) || isLocked(from) || !items[from]) return false;
    if (canMove && !canMove(from, to, items)) return false;
    const [next, change] = applyMove(items, from, to, stacking);
    commit(next, change);
    return true;
  };
  const select = (i: number) => {
    if (selectedProp === undefined) setSelInner(i);
    onSelect?.(items[i] ?? null, i);
  };
  const focusSlot = (pos: number) => {
    const p = Math.max(0, Math.min(visible.length - 1, pos));
    setFocus(p);
    gridRef.current?.querySelector<HTMLButtonElement>(`[data-pos="${p}"]`)?.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(); focusSlot(focus + map[e.key]); return; }
    if (e.key === "Home") { e.preventDefault(); focusSlot(0); return; }
    if (e.key === "End") { e.preventDefault(); focusSlot(visible.length - 1); return; }
    const here = visible[focus];
    if (!here) return;
    if (e.key === " ") {
      e.preventDefault();
      if (!canDrag) { select(here.index); return; }
      if (grabbed == null) {
        if (!here.item || isLocked(here.index)) { select(here.index); return; }
        setGrabbed(here.index);
        setAnnounce(`Picked up ${here.item.name}. Use the arrow keys, then Space to drop or Escape to cancel.`);
      } else {
        const ok = doMove(grabbed, here.index);
        setAnnounce(ok ? `Dropped in slot ${here.index + 1}.` : "Cannot drop there.");
        setGrabbed(null);
        select(here.index);
      }
    } else if (e.key === "Escape" && grabbed != null) {
      e.preventDefault(); setGrabbed(null); setAnnounce("Move cancelled.");
    } else if (e.key === "Enter" && here.item) {
      e.preventDefault(); onActivate?.(here.item, here.index);
    }
  };

  // pointer drag and drop (mouse, pen, touch)
  const slotAt = (x: number, y: number) => {
    const el = document.elementFromPoint(x, y)?.closest<HTMLElement>("[data-inv-index]");
    if (!el || !gridRef.current?.contains(el)) return null;
    return Number(el.dataset.invIndex);
  };
  const onPointerDown = (e: React.PointerEvent, index: number) => {
    if (!canDrag || e.button !== 0 || !items[index] || isLocked(index)) return;
    down.current = { index, x: e.clientX, y: e.clientY, id: e.pointerId };
  };
  React.useEffect(() => {
    const move = (e: PointerEvent) => {
      const d = down.current;
      if (!d || e.pointerId !== d.id) return;
      if (!drag && Math.hypot(e.clientX - d.x, e.clientY - d.y) < 6) return;
      e.preventDefault();
      setDrag({ from: d.index, x: e.clientX, y: e.clientY, over: slotAt(e.clientX, e.clientY) });
    };
    const up = (e: PointerEvent) => {
      const d = down.current;
      if (!d || e.pointerId !== d.id) return;
      down.current = null;
      if (drag) {
        const to = slotAt(e.clientX, e.clientY);
        if (to != null) { doMove(drag.from, to); select(to); }
        setDrag(null);
      }
    };
    const cancel = () => { down.current = null; setDrag(null); };
    window.addEventListener("pointermove", move, { passive: false });
    window.addEventListener("pointerup", up);
    window.addEventListener("pointercancel", cancel);
    return () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", up); window.removeEventListener("pointercancel", cancel); };
  });

  const sortBy = (s: InventorySort) => {
    const unlocked = items.filter((_, i) => !isLocked(i));
    const filled = unlocked.filter(Boolean) as GameItem[];
    filled.sort(s.compare);
    const next: InventorySlots = items.map((it, i) => (isLocked(i) ? it : filled[i] ?? null));
    commit(next, { type: "sort", sortId: s.id });
  };

  const used = items.filter(Boolean).length;
  const capacity = lockedFrom != null ? Math.min(lockedFrom, total) : total;
  const dragItem = drag ? items[drag.from] : null;
  const name = label ?? (typeof title === "string" ? title : "Inventory");

  return (
    <TooltipProvider delayDuration={250}>
      <div data-slot="inventory" className={cn("cz-inventory", className)} style={{ "--slot": `${slotSize}px`, ...(columns ? { "--cols": columns } : null), ...style } as React.CSSProperties} {...props}>
        {(title != null || headerEnd != null || (showCapacity ?? title != null)) && (
          <div className="cz-inventory__head">
            {title != null && <div className="cz-inventory__title">{title}</div>}
            {(showCapacity ?? title != null) && <span className="cz-inventory__cap" aria-label={`${used} of ${capacity} slots used`}>{used} / {capacity}</span>}
            {headerEnd != null && <div className="cz-inventory__end">{headerEnd}</div>}
          </div>
        )}
        {(categories?.length || search || sorts?.length) ? (
          <div className="cz-inventory__tools">
            {categories?.length ? (
              <div className="cz-inventory__tabs" role="tablist" aria-label="Categories">
                {[{ id: "__all", label: allLabel, icon: undefined as React.ReactNode }, ...categories].map((c) => (
                  <button key={c.id} type="button" role="tab" aria-selected={category === c.id} className="cz-inventory__tab" onClick={() => { setCategory(c.id); setFocus(0); }}>
                    {c.icon != null && <span className="cz-inventory__tab-icon">{c.icon}</span>}{c.label}
                  </button>
                ))}
              </div>
            ) : null}
            {search ? (
              <input type="search" className="cz-input cz-inventory__search" placeholder={typeof search === "string" ? search : "Search items…"} aria-label="Search items" value={query} onChange={(e) => { setQuery(e.target.value); setFocus(0); }} />
            ) : null}
            {sorts?.map((s) => (
              <button key={s.id} type="button" className="cz-inventory__sort" onClick={() => sortBy(s)}>{s.label}</button>
            ))}
          </div>
        ) : null}
        <div ref={gridRef} role="group" aria-label={name} aria-describedby={`${baseId}-help`} className="cz-inventory__grid" data-cols={columns ? "" : undefined} onKeyDown={onKeyDown} data-dragging={drag ? true : undefined}>
          {visible.length === 0 && <div className="cz-inventory__empty">{emptyText}</div>}
          {visible.map(({ item, index }, pos) => {
            const locked = isLocked(index);
            const labelText = locked ? `Slot ${index + 1}, locked` : item ? `Slot ${index + 1}: ${item.name}${item.quantity && item.quantity > 1 ? `, ${item.quantity}` : ""}${item.rarity ? `, ${rarityLabel(item.rarity, rarities)}` : ""}` : `Slot ${index + 1}, empty`;
            const slot = (
              <ItemSlot
                key={index}
                item={item}
                locked={locked}
                placeholder={placeholder}
                rarities={rarities}
                data-inv-index={index}
                data-pos={pos}
                tabIndex={pos === Math.min(focus, visible.length - 1) ? 0 : -1}
                selected={selected === index}
                grabbed={grabbed === index || drag?.from === index}
                dropTarget={(drag != null && drag.over === index && drag.from !== index) || (grabbed != null && pos === focus && grabbed !== index)}
                aria-label={labelText}
                aria-pressed={selected === index}
                onFocus={() => setFocus(pos)}
                onClick={() => { if (!drag) select(index); }}
                onDoubleClick={() => item && onActivate?.(item, index)}
                onPointerDown={(e) => onPointerDown(e, index)}
                style={{ touchAction: canDrag && item ? "none" : undefined }}
              />
            );
            return item && tooltip && !drag ? (
              <ItemTooltip key={index} item={item} rarities={rarities} formatValue={formatValue}>{slot}</ItemTooltip>
            ) : slot;
          })}
        </div>
        <p id={`${baseId}-help`} className="cz-sr-only">
          {canDrag ? "Arrow keys move between slots. Space picks an item up and drops it. Enter uses it." : "Arrow keys move between slots. Enter uses an item."}
        </p>
        <div aria-live="polite" className="cz-sr-only">{announce}</div>
        {drag && dragItem && (
          <div className="cz-slot cz-inventory__ghost" style={{ left: drag.x, top: drag.y, ...rarityStyle(dragItem.rarity, rarities) }} aria-hidden>
            <span className="cz-slot__icon"><GameIcon icon={dragItem.icon} /></span>
            {dragItem.quantity != null && dragItem.quantity > 1 && <span className="cz-slot__qty">{dragItem.quantity}</span>}
          </div>
        )}
      </div>
    </TooltipProvider>
  );
}

export { Inventory, applyMove };
export type { InventoryProps };
```

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