# Buff Bar

Active effects on the HUD. Each buff or debuff is a round icon with a countdown ring, a short time label ("4:32", "2h"), a stacks badge and a tooltip with the name, description, source and time left. Debuffs use the danger colour, and under 10 seconds an icon gently blinks. Timers use absolute end times.

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

Install: `npx shadcn@latest add @cozy/buff-bar`

### Usage

```tsx
import { BuffBar, type Buff } from "@/components/ui/buff-bar"

const buffs: Buff[] = [
  { id: "fed", name: "Well fed", icon: <BowlIcon />, endsAt: Date.now() + 120_000, duration: 120_000, source: "Rice dumplings" },
  { id: "rain", name: "Rainy day", kind: "debuff", endsAt: Date.now() + 45_000, duration: 45_000 },
  { id: "fest", name: "Festival spirit", stacks: 3 },
]

<BuffBar buffs={buffs} onExpire={(b) => removeBuff(b.id)} />
```

### Props

| Prop | Type | Default | Description |
|---|---|---|---|
| buffs | `Buff<T>[]` | – | { id, name, label?, icon?, description?, kind?, stacks?, endsAt?, duration?, source?, data? }. No endsAt means permanent. `icon` is a React node or an image URL. |
| onExpire | `(buff) => void` | – | Called once when a timer reaches 0. Remove the buff from `buffs`; until then it is hidden. |
| onSelect | `(buff) => void` | – | Makes the icons buttons. |
| max | `number` | `all` | Icons shown; the rest go into a "+n" chip with a tooltip list. |
| size | `"sm" \| "md" \| "lg"` | `"md"` | 40, 52 or 64 px icons. |
| orientation | `"horizontal" \| "vertical"` | `"horizontal"` | Direction of the row. |
| sort | `"time" \| "none"` | `"time"` | "time": debuffs first, then the soonest to end, permanent last. "none" keeps your order. |
| emptyText | `ReactNode` | – | Shown when empty. Without it the component renders nothing. |
| labels | `Partial<BuffBarLabels>` | `English` | bar, timeLeft ("{time} left"), permanent, debuff, source, more ("{count} more effects"). |

Without `duration` the ring starts full when the buff is first shown and empties until `endsAt`.

Tooltips open on hover and keyboard focus; a tap opens and closes them on touch screens. The component has its own TooltipProvider.

Reduced motion stops the blink and the ring transition.

### Example

```tsx
import * as React from "react";
import { BuffBar, type Buff } from "@/components/ui/buff-bar";
import { Button } from "@/components/ui/button";
import { Grain, Sun } from "../art";
import { Lantern, Teapot } from "../art/game";

const art = (A: typeof Grain) => <A width="100%" height="100%" />;
const start = (): Buff[] => {
  const now = Date.now();
  return [
    { id: "fed", name: "Well fed", icon: art(Grain), description: "Crops grow 10% faster.", source: "Rice dumplings", endsAt: now + 120_000, duration: 120_000 },
    { id: "rain", name: "Rainy day", icon: art(Sun), kind: "debuff", description: "Rice cannot dry on the road.", endsAt: now + 45_000, duration: 45_000 },
    { id: "fest", name: "Festival spirit", icon: art(Lantern), stacks: 3, description: "Neighbours cheer you on.", source: "Lantern night" },
    { id: "tea", name: "Tea break", icon: art(Teapot), description: "A short rest restores energy.", source: "Jade teapot", endsAt: now + 12_000, duration: 12_000 },
  ];
};

export default function Demo() {
  const [buffs, setBuffs] = React.useState<Buff[]>(start);
  const [log, setLog] = React.useState("");
  const add = () => setBuffs((list) => {
    const n = Date.now();
    return [...list.filter((b) => b.id !== "tea"), { id: "tea", name: "Tea break", icon: art(Teapot), description: "A short rest restores energy.", source: "Jade teapot", endsAt: n + 30_000, duration: 30_000 }];
  });
  return (
    <div className="grid w-full gap-4">
      <BuffBar
        buffs={buffs}
        onExpire={(b) => { setBuffs((list) => list.filter((x) => x.id !== b.id)); setLog(`${typeof b.name === "string" ? b.name : b.id} wore off`); }}
        onSelect={(b) => setLog(`Selected ${typeof b.name === "string" ? b.name : b.id}`)}
        emptyText="No active effects."
      />
      <div className="flex flex-wrap gap-2">
        <Button size="sm" onClick={add}>Add Tea break (30 s)</Button>
        <Button size="sm" variant="secondary" onClick={() => setBuffs(start())}>Refresh all</Button>
      </div>
      <p className="text-sm text-[var(--cz-text-muted)]" aria-live="polite">{log || "Hover or focus an icon for details."}</p>
    </div>
  );
}
```

### Source (components/ui/buff-bar.tsx)

```tsx
import * as React from "react";
import { cn } from "@/lib/utils";
import { GameIcon, formatDuration, useNow } from "./game-core";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./tooltip";

/* Active effects on the HUD: round icons with a countdown ring, a time label,
   a stacks badge and a tooltip. The game owns the list and removes expired
   buffs in `onExpire`; this only shows them. */

/** One active effect. */
export type Buff<T = unknown> = {
  /** Stable id. */
  id: string;
  /** Display name. */
  name: React.ReactNode;
  /** Plain-text name for aria. Falls back to `name` when it is a string, else the id. */
  label?: string;
  /** A React node (SVG, sprite, <img>) or an image URL. Without one the first letter of the name is shown. */
  icon?: React.ReactNode;
  /** What it does, shown in the tooltip. */
  description?: React.ReactNode;
  /** "buff" (default) or "debuff". Debuffs use the danger colour and sort first. */
  kind?: "buff" | "debuff";
  /** Stack count. A badge shows from 2 up. */
  stacks?: number;
  /** When it ends, in epoch ms (Date.now() scale). Missing means permanent. */
  endsAt?: number;
  /** Total length in ms, for the ring. Without it the ring starts full when the buff is first shown. */
  duration?: number;
  /** Where it comes from, shown in the tooltip, e.g. "Jade teapot". */
  source?: React.ReactNode;
  /** Your own object; passed back in every callback. */
  data?: T;
};

/** Every built-in string. `{time}` and `{count}` are replaced. */
export type BuffBarLabels = {
  /** Accessible name of the bar. Default "Active effects". */
  bar: string;
  /** Tooltip line. Default "{time} left". */
  timeLeft: string;
  /** Tooltip line for a buff without `endsAt`. Default "Permanent". */
  permanent: string;
  /** Tag on debuffs in the tooltip. Default "Debuff". */
  debuff: string;
  /** Prefix before `source`. Default "From". */
  source: string;
  /** Accessible name of the overflow chip. Default "{count} more effects". */
  more: string;
};

const DEFAULT_LABELS: BuffBarLabels = {
  bar: "Active effects", timeLeft: "{time} left", permanent: "Permanent", debuff: "Debuff", source: "From", more: "{count} more effects",
};
const fill = (text: string, vars: Record<string, string | number>) => text.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m));
const plainName = (b: Buff<any>) => b.label ?? (typeof b.name === "string" ? b.name : b.id);

/** Short label for the icon: "0:45", "4:32", "2h", "3d". */
function compactTime(ms: number) {
  const s = Math.max(0, Math.ceil(ms / 1000));
  if (s >= 86400) return `${Math.floor(s / 86400)}d`;
  if (s >= 3600) return `${Math.floor(s / 3600)}h`;
  return formatDuration(ms, "clock");
}

type BuffBarProps<T = unknown> = Omit<React.ComponentProps<"div">, "children" | "onSelect"> & {
  /** The active effects. Remove expired ones in `onExpire`. */
  buffs: Buff<T>[];
  /** Called once when a buff's timer reaches 0. The game should remove it from `buffs`; until then it is hidden. */
  onExpire?: (buff: Buff<T>) => void;
  /** Makes the icons buttons. Called with the buff that was clicked, tapped or activated with Enter or Space. */
  onSelect?: (buff: Buff<T>) => void;
  /** Most icons shown; the rest go into a "+3" chip with a tooltip list. Default all. */
  max?: number;
  /** Icon size: sm 40px, md 52px, lg 64px. Default "md". */
  size?: "sm" | "md" | "lg";
  /** Default "horizontal". */
  orientation?: "horizontal" | "vertical";
  /** "time": debuffs first, then the soonest to end, permanent last. "none": keep the order of `buffs`. Default "time". */
  sort?: "time" | "none";
  /** Shown when `buffs` is empty. Default: render nothing. */
  emptyText?: React.ReactNode;
  /** Override built-in text for translation. */
  labels?: Partial<BuffBarLabels>;
};

/** A tooltip that also opens on a tap (Radix opens on hover and keyboard focus only). A tap keeps it open until the next tap elsewhere. */
function Tip({ content, children }: { content: React.ReactNode; children: React.ReactElement }) {
  const [open, setOpen] = React.useState(false);
  const wasOpen = React.useRef(false);
  const touch = React.useRef(false);
  const pinned = React.useRef(false);
  const trigger = React.useRef<HTMLButtonElement>(null);
  React.useEffect(() => {
    if (!open) { pinned.current = false; return; }
    const away = (e: PointerEvent) => {
      const t = e.target as Element | null;
      if (!pinned.current || trigger.current?.contains(t) || t?.closest?.("[data-slot=tooltip-content]")) return;
      pinned.current = false;
      setOpen(false);
    };
    document.addEventListener("pointerdown", away, true);
    return () => document.removeEventListener("pointerdown", away, true);
  }, [open]);
  return (
    <Tooltip open={open} onOpenChange={(next) => { if (!next && pinned.current) return; setOpen(next); }}>
      <TooltipTrigger
        ref={trigger}
        asChild
        onPointerDownCapture={(e: React.PointerEvent) => { touch.current = e.pointerType === "touch"; wasOpen.current = open; }}
        onClick={() => {
          if (!touch.current) return;
          touch.current = false;
          pinned.current = !wasOpen.current;
          setOpen(!wasOpen.current);
        }}
      >
        {children}
      </TooltipTrigger>
      <TooltipContent className="cz-buffs__tip" collisionPadding={8} onEscapeKeyDown={() => { pinned.current = false; setOpen(false); }}>{content}</TooltipContent>
    </Tooltip>
  );
}

function Ring({ fraction }: { fraction: number }) {
  return (
    <svg className="cz-buffs__ring" viewBox="0 0 40 40" aria-hidden>
      <circle className="cz-buffs__track" cx="20" cy="20" r="17" pathLength="100" />
      <circle className="cz-buffs__arc" cx="20" cy="20" r="17" pathLength="100" strokeDasharray="100" strokeDashoffset={100 - 100 * Math.max(0, Math.min(1, fraction))} />
    </svg>
  );
}

/** HUD row of active buffs and debuffs with countdown rings, stacks and tooltips. */
function BuffBar<T = unknown>({
  buffs, onExpire, onSelect, max, size = "md", orientation = "horizontal", sort = "time", emptyText, labels: labelsProp, className, ...props
}: BuffBarProps<T>) {
  const L = { ...DEFAULT_LABELS, ...labelsProp };
  const timed = buffs.some((b) => b.endsAt != null);
  const now = useNow(500, timed);

  // First-seen remaining time, the ring's total when `duration` is missing.
  const totals = React.useRef(new Map<string, number>());
  for (const b of buffs) {
    if (b.endsAt == null) continue;
    const key = `${b.id}:${b.endsAt}`;
    if (!totals.current.has(key)) totals.current.set(key, Math.max(1, b.endsAt - now));
  }

  // onExpire fires once per buff and end time.
  const fired = React.useRef(new Set<string>());
  const onExpireRef = React.useRef(onExpire);
  onExpireRef.current = onExpire;
  React.useEffect(() => {
    const live = new Set<string>();
    for (const b of buffs) {
      if (b.endsAt == null) continue;
      const key = `${b.id}:${b.endsAt}`;
      live.add(key);
      if (b.endsAt <= now && !fired.current.has(key)) { fired.current.add(key); onExpireRef.current?.(b); }
    }
    for (const k of fired.current) if (!live.has(k)) fired.current.delete(k);
    for (const k of totals.current.keys()) if (!live.has(k)) totals.current.delete(k);
  }, [buffs, now]);

  const alive = buffs.filter((b) => b.endsAt == null || b.endsAt > now);
  const end = (b: Buff<T>) => b.endsAt ?? Infinity;
  const sorted = sort === "none" ? alive : alive.map((b, i) => ({ b, i })).sort((x, y) => {
    const dx = x.b.kind === "debuff" ? 0 : 1, dy = y.b.kind === "debuff" ? 0 : 1;
    if (dx !== dy) return dx - dy;
    const ex = end(x.b), ey = end(y.b);
    return ex === ey ? x.i - y.i : ex < ey ? -1 : 1;
  }).map((o) => o.b);

  if (sorted.length === 0) {
    return emptyText != null ? <div data-slot="buff-bar" data-empty className={cn("cz-buffs cz-buffs__empty", className)} {...props}>{emptyText}</div> : null;
  }

  const shown = max != null && max >= 0 && sorted.length > max ? sorted.slice(0, max) : sorted;
  const hidden = sorted.slice(shown.length);

  const tipBody = (b: Buff<T>) => {
    const left = b.endsAt != null ? b.endsAt - now : null;
    return (
      <div className="cz-buffs__tipbody">
        <div className="cz-buffs__tiphead">
          <strong>{b.name}</strong>
          {b.stacks != null && b.stacks > 1 && <span>×{b.stacks}</span>}
          {b.kind === "debuff" && <em>{L.debuff}</em>}
        </div>
        {b.description != null && <div>{b.description}</div>}
        {b.source != null && <div className="cz-buffs__tipmeta">{L.source} {b.source}</div>}
        <div className="cz-buffs__tipmeta">{left != null ? fill(L.timeLeft, { time: formatDuration(left, "short") }) : L.permanent}</div>
      </div>
    );
  };

  return (
    <TooltipProvider delayDuration={150}>
      <div
        data-slot="buff-bar"
        data-size={size}
        data-orientation={orientation}
        role="list"
        aria-label={L.bar}
        className={cn("cz-buffs", className)}
        {...props}
      >
        {shown.map((b) => {
          const left = b.endsAt != null ? Math.max(0, b.endsAt - now) : null;
          const total = b.duration ?? totals.current.get(`${b.id}:${b.endsAt}`) ?? 1;
          const fraction = left == null ? 1 : left / Math.max(1, total);
          const urgent = left != null && left < 10000;
          const name = plainName(b);
          const aria = `${name}${b.stacks && b.stacks > 1 ? `, ×${b.stacks}` : ""}${b.kind === "debuff" ? `, ${L.debuff}` : ""}, ${left != null ? fill(L.timeLeft, { time: formatDuration(left, "short") }) : L.permanent}`;
          const Tag = onSelect ? "button" : "span";
          return (
            <div role="listitem" key={b.id} className="cz-buffs__slot">
              <Tip content={tipBody(b)}>
                <Tag
                  {...(onSelect ? { type: "button" as const, onClick: () => onSelect(b) } : { role: "img" })}
                  tabIndex={0}
                  aria-label={aria}
                  data-slot="buff"
                  data-kind={b.kind === "debuff" ? "debuff" : "buff"}
                  data-urgent={urgent || undefined}
                  data-permanent={left == null || undefined}
                  className="cz-buffs__buff"
                >
                  <Ring fraction={fraction} />
                  <span className="cz-buffs__icon" aria-hidden>
                    {b.icon != null ? <GameIcon icon={b.icon} alt="" /> : <span className="cz-buffs__letter">{name.charAt(0).toUpperCase()}</span>}
                  </span>
                  {b.kind === "debuff" && <span className="cz-buffs__mark" aria-hidden>−</span>}
                  {b.stacks != null && b.stacks > 1 && <span className="cz-buffs__stacks" aria-hidden>×{b.stacks}</span>}
                  {left != null && <span className="cz-buffs__time" aria-hidden>{compactTime(left)}</span>}
                </Tag>
              </Tip>
            </div>
          );
        })}
        {hidden.length > 0 && (
          <div role="listitem" className="cz-buffs__slot">
            <Tip
              content={
                <div className="cz-buffs__more">
                  {hidden.map((b) => (
                    <div key={b.id} className="cz-buffs__row" data-kind={b.kind === "debuff" ? "debuff" : "buff"}>
                      <span className="cz-buffs__rowicon" aria-hidden>{b.icon != null ? <GameIcon icon={b.icon} alt="" /> : plainName(b).charAt(0).toUpperCase()}</span>
                      <span className="cz-buffs__rowname">{b.name}{b.stacks != null && b.stacks > 1 ? ` ×${b.stacks}` : ""}</span>
                      <span className="cz-buffs__rowtime">{b.endsAt != null ? formatDuration(b.endsAt - now, "short") : "∞"}</span>
                    </div>
                  ))}
                </div>
              }
            >
              <button type="button" tabIndex={0} data-slot="buff-overflow" className="cz-buffs__buff cz-buffs__chip" aria-label={fill(L.more, { count: hidden.length })}>
                +{hidden.length}
              </button>
            </Tip>
          </div>
        )}
      </div>
    </TooltipProvider>
  );
}

export { BuffBar };
export type { BuffBarProps };
```

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