Bulk action bar

A floating toolbar that rises from the bottom (or top) of a list when items are selected and sinks away when the selection clears. It shows a rolling selected count, a basket of removable chips with a '+N' overflow that opens a scrollable list, action buttons and Clear. Destructive actions confirm inline ('Delete 6? Yes / No', focus on No) without a modal, and a finished action leaves an Undo pill in the same bar for a few seconds. Ships a useSelection hook with toggle, shift-click ranges, select all, clear and isSelected. Set a threshold, place it inside the parent or float it over the page; Escape clears, count changes are announced politely and focus is never taken when the bar appears.

Tables & dataComponentTailwind v4

Source

import * as React from "react";
import { createPortal } from "react-dom";
import { Loader2, RotateCcw, X } from "lucide-react";
import { cn } from "@/lib/utils";

export { useSelection } from "./use-selection";

export type BulkItem = { id: string; label: string };

export type BulkAction = {
  id: string;
  label: string;
  icon?: React.ComponentType<{ className?: string; "aria-hidden"?: boolean | "true" }>;
  tone?: "default" | "danger";
  /** Ask "Delete 6? Yes / No" inside the bar before running. */
  confirm?: boolean;
  run: (ids: string[]) => Promise<unknown> | void;
  /** When set, a finished action shows an Undo pill that calls this with the same ids. */
  undo?: (ids: string[]) => Promise<unknown> | void;
  /** Past-tense line for the undo pill, e.g. (n) => `Deleted ${n} files`. */
  done?: (count: number) => string;
};

export type BulkActionBarProps = {
  selected: BulkItem[];
  onRemove: (id: string) => void;
  onClear: () => void;
  actions: BulkAction[];
  /** How many items must be selected before the bar appears. */
  threshold?: number;
  position?: "bottom" | "top";
  /** "parent" sits inside the nearest positioned ancestor, "body" floats over the page. */
  container?: "parent" | "body";
  /** Chips shown before the "+N" overflow. */
  maxChips?: number;
  clearOnEscape?: boolean;
  /** How long the undo pill stays, in ms. */
  undoMs?: number;
  /** Noun for the count and confirm, e.g. ["file", "files"]. */
  noun?: [string, string];
  className?: string;
};

const ring = "outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-popover";
const EXIT_MS = 240;

type UndoState = { text: string; ids: string[]; undo: (ids: string[]) => Promise<unknown> | void };

function RollingCount({ value }: { value: number }) {
  const previous = React.useRef(value);
  const direction = value >= previous.current ? "up" : "down";
  React.useEffect(() => {
    previous.current = value;
  }, [value]);
  return (
    <span className="relative inline-flex h-5 overflow-hidden tabular-nums" aria-hidden="true">
      <span key={value} className={cn("inline-block", direction === "up" ? "motion-safe:animate-[chm-bab-up_.22s_ease-out]" : "motion-safe:animate-[chm-bab-down_.22s_ease-out]")}>
        {value}
      </span>
    </span>
  );
}

export function BulkActionBar({
  selected,
  onRemove,
  onClear,
  actions,
  threshold = 1,
  position = "bottom",
  container = "parent",
  maxChips = 3,
  clearOnEscape = true,
  undoMs = 5000,
  noun = ["item", "items"],
  className,
}: BulkActionBarProps) {
  const [undo, setUndo] = React.useState<UndoState | null>(null);
  const [confirming, setConfirming] = React.useState<string | null>(null);
  const [busy, setBusy] = React.useState<string | null>(null);
  const [overflowOpen, setOverflowOpen] = React.useState(false);
  const [mounted, setMounted] = React.useState(false);
  const initiallyOpen = React.useRef(selected.length >= threshold);
  const [present, setPresent] = React.useState(initiallyOpen.current);
  const [shown, setShown] = React.useState(initiallyOpen.current);
  const [announce, setAnnounce] = React.useState("");
  const last = React.useRef<BulkItem[]>(selected);
  const barRef = React.useRef<HTMLDivElement>(null);
  const noRef = React.useRef<HTMLButtonElement>(null);
  const moreRef = React.useRef<HTMLButtonElement>(null);
  const popRef = React.useRef<HTMLDivElement>(null);
  const undoTimer = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  const popId = React.useId();

  const open = selected.length >= threshold || !!undo;
  if (selected.length >= threshold) last.current = selected;
  const items = selected.length >= threshold ? selected : last.current;
  const count = items.length;
  const word = count === 1 ? noun[0] : noun[1];

  React.useEffect(() => setMounted(true), []);

  /* Mount, then flip to shown on the next frame so the rise can transition; the reverse waits for the sink. */
  React.useEffect(() => {
    if (open) {
      if (initiallyOpen.current) {
        initiallyOpen.current = false;
        return;
      }
      setPresent(true);
      const frame = requestAnimationFrame(() => requestAnimationFrame(() => setShown(true)));
      return () => cancelAnimationFrame(frame);
    }
    initiallyOpen.current = false;
    setShown(false);
    setConfirming(null);
    setOverflowOpen(false);
    const timer = setTimeout(() => setPresent(false), EXIT_MS);
    return () => clearTimeout(timer);
  }, [open]);

  React.useEffect(() => {
    if (undo) return;
    const timer = setTimeout(() => setAnnounce(selected.length ? `${selected.length} ${selected.length === 1 ? noun[0] : noun[1]} selected` : "Selection cleared"), 250);
    return () => clearTimeout(timer);
  }, [selected.length, undo, noun]);

  React.useEffect(() => {
    if (!open || !clearOnEscape) return;
    const onKey = (event: KeyboardEvent) => {
      if (event.key !== "Escape" || event.defaultPrevented || confirming || overflowOpen) return;
      if (selected.length) onClear();
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, clearOnEscape, confirming, overflowOpen, selected.length, onClear]);

  React.useEffect(() => {
    if (confirming) noRef.current?.focus();
  }, [confirming]);

  React.useEffect(() => {
    if (!overflowOpen) return;
    const onDown = (event: PointerEvent) => {
      const target = event.target as Node;
      if (!popRef.current?.contains(target) && !moreRef.current?.contains(target)) setOverflowOpen(false);
    };
    document.addEventListener("pointerdown", onDown);
    return () => document.removeEventListener("pointerdown", onDown);
  }, [overflowOpen]);

  const startUndoTimer = React.useCallback(() => {
    clearTimeout(undoTimer.current);
    undoTimer.current = setTimeout(() => setUndo(null), undoMs);
  }, [undoMs]);
  const pauseUndoTimer = () => clearTimeout(undoTimer.current);
  React.useEffect(() => () => clearTimeout(undoTimer.current), []);

  const run = async (action: BulkAction) => {
    const ids = items.map((item) => item.id);
    setConfirming(null);
    setBusy(action.id);
    try {
      await action.run(ids);
      setAnnounce(action.done ? action.done(ids.length) : `${action.label}: ${ids.length} ${ids.length === 1 ? noun[0] : noun[1]}`);
      if (action.undo) {
        setUndo({ text: action.done ? action.done(ids.length) : `${action.label} done`, ids, undo: action.undo });
        startUndoTimer();
        requestAnimationFrame(() => barRef.current?.querySelector<HTMLButtonElement>("[data-undo]")?.focus());
      }
      onClear();
    } finally {
      setBusy(null);
    }
  };

  const doUndo = async () => {
    if (!undo) return;
    clearTimeout(undoTimer.current);
    await undo.undo(undo.ids);
    setAnnounce("Undone");
    setUndo(null);
  };

  const removeChip = (id: string, from: "bar" | "pop") => {
    const scope = from === "pop" ? popRef.current : barRef.current;
    const buttons = Array.from(scope?.querySelectorAll<HTMLButtonElement>("[data-chip]") || []);
    const index = buttons.findIndex((button) => button.dataset.chip === id);
    onRemove(id);
    requestAnimationFrame(() => {
      const next = Array.from(scope?.querySelectorAll<HTMLButtonElement>("[data-chip]") || []);
      (next[index] || next[index - 1] || barRef.current?.querySelector<HTMLButtonElement>("[data-clear]"))?.focus();
    });
  };

  /* Arrow keys move between the bar's controls, as in any toolbar; Tab still works. */
  const onToolbarKey = (event: React.KeyboardEvent) => {
    if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
    const controls = Array.from(barRef.current?.querySelectorAll<HTMLElement>("button:not([disabled])") || []);
    const index = controls.indexOf(document.activeElement as HTMLElement);
    if (index < 0) return;
    event.preventDefault();
    controls[(index + (event.key === "ArrowRight" ? 1 : -1) + controls.length) % controls.length]?.focus();
  };

  const chips = items.slice(0, maxChips);
  const hidden = items.slice(maxChips);
  const bottom = position === "bottom";

  const bar = present ? (
    <div
      className={cn(
        "@container pointer-events-none inset-x-0 z-40 flex justify-center px-3 sm:px-4",
        container === "body" ? "fixed" : "absolute",
        bottom ? "bottom-3 sm:bottom-5" : "top-3 sm:top-5",
      )}
    >
      <div
        ref={barRef}
        role="toolbar"
        aria-label={undo ? undo.text : `${count} ${word} selected`}
        onKeyDown={onToolbarKey}
        onMouseEnter={undo ? pauseUndoTimer : undefined}
        onMouseLeave={undo ? startUndoTimer : undefined}
        onFocus={undo ? pauseUndoTimer : undefined}
        onBlur={undo ? startUndoTimer : undefined}
        className={cn(
          "pointer-events-auto relative w-full max-w-3xl rounded-2xl border border-border bg-popover text-popover-foreground shadow-[0_18px_50px_-12px_rgb(0_0_0/0.35)]",
          "transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-opacity",
          shown ? "translate-y-0 opacity-100" : cn("opacity-0", bottom ? "motion-safe:translate-y-[calc(100%+1.5rem)]" : "motion-safe:-translate-y-[calc(100%+1.5rem)]"),
          undo && "w-auto",
          className,
        )}
      >
        {undo ? (
          <div className="flex items-center gap-3 py-2 pl-4 pr-2 text-sm">
            <span className="font-medium">{undo.text}</span>
            <button
              type="button"
              data-undo
              onClick={doUndo}
              className={cn("inline-flex h-8 items-center gap-1.5 rounded-full bg-primary px-3 text-sm font-medium text-primary-foreground hover:opacity-90", ring)}
            >
              <RotateCcw className="size-3.5" aria-hidden="true" />
              Undo
            </button>
            <button type="button" onClick={() => setUndo(null)} aria-label="Dismiss" className={cn("grid size-8 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground", ring)}>
              <X className="size-4" aria-hidden="true" />
            </button>
          </div>
        ) : (
          <div className="flex flex-wrap items-center gap-x-2 gap-y-2 p-2 @2xl:flex-nowrap">
            <div className="flex min-w-0 flex-1 basis-full items-center gap-2 @2xl:basis-auto">
              <span className="flex shrink-0 items-center gap-1.5 rounded-xl bg-primary px-2.5 py-1.5 text-sm font-semibold text-primary-foreground">
                <RollingCount value={count} />
                <span className="font-medium">selected</span>
              </span>
              <ul aria-label={`Selected ${noun[1]}`} className="flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto [mask-image:linear-gradient(to_right,#000_calc(100%-1.5rem),transparent)] pr-4 [scrollbar-width:none]">
                {chips.map((item) => (
                  <li key={item.id} className="flex shrink-0 items-center rounded-lg border border-border bg-background py-0.5 pl-2.5 pr-0.5 text-[13px] motion-safe:animate-[chm-bab-chip_.18s_ease-out]">
                    <span className="max-w-[9rem] truncate">{item.label}</span>
                    <button
                      type="button"
                      data-chip={item.id}
                      onClick={() => removeChip(item.id, "bar")}
                      aria-label={`Deselect ${item.label}`}
                      className={cn("ml-0.5 grid size-6 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground", ring)}
                    >
                      <X className="size-3.5" aria-hidden="true" />
                    </button>
                  </li>
                ))}
              </ul>
              {hidden.length > 0 && (
                <button
                  ref={moreRef}
                  type="button"
                  aria-expanded={overflowOpen}
                  aria-controls={overflowOpen ? popId : undefined}
                  aria-label={`${hidden.length} more selected`}
                  onClick={() => setOverflowOpen((value) => !value)}
                  className={cn("h-7 shrink-0 rounded-lg bg-muted px-2.5 text-[13px] font-medium hover:bg-accent", overflowOpen && "bg-accent", ring)}
                >
                  +{hidden.length}
                </button>
              )}
            </div>

            <div className="ml-auto flex shrink-0 items-center gap-1">
              {confirming ? (
                (() => {
                  const action = actions.find((item) => item.id === confirming)!;
                  return (
                    <div
                      className="flex items-center gap-1.5 rounded-xl bg-destructive/10 py-1 pl-3 pr-1 motion-safe:animate-[chm-bab-chip_.16s_ease-out]"
                      onKeyDown={(event) => {
                        if (event.key === "Escape") {
                          event.preventDefault();
                          event.stopPropagation();
                          setConfirming(null);
                          requestAnimationFrame(() => barRef.current?.querySelector<HTMLButtonElement>(`[data-action="${action.id}"]`)?.focus());
                        }
                      }}
                    >
                      <span className="text-sm font-medium text-destructive" id={`${popId}-q`}>
                        {action.label} {count}?
                      </span>
                      <button
                        type="button"
                        onClick={() => run(action)}
                        aria-describedby={`${popId}-q`}
                        className={cn("h-8 rounded-lg bg-destructive px-3 text-sm font-medium text-white hover:opacity-90", ring)}
                      >
                        Yes
                      </button>
                      <button
                        ref={noRef}
                        type="button"
                        onClick={() => {
                          setConfirming(null);
                          requestAnimationFrame(() => barRef.current?.querySelector<HTMLButtonElement>(`[data-action="${action.id}"]`)?.focus());
                        }}
                        aria-describedby={`${popId}-q`}
                        className={cn("h-8 rounded-lg px-3 text-sm font-medium hover:bg-accent", ring)}
                      >
                        No
                      </button>
                    </div>
                  );
                })()
              ) : (
                actions.map((action) => {
                  const Icon = action.icon;
                  const danger = action.tone === "danger";
                  return (
                    <button
                      key={action.id}
                      type="button"
                      data-action={action.id}
                      disabled={!!busy}
                      aria-label={action.label}
                      title={action.label}
                      onClick={() => (action.confirm ? setConfirming(action.id) : run(action))}
                      className={cn(
                        "inline-flex h-9 items-center gap-1.5 rounded-xl px-2.5 text-sm font-medium transition-colors disabled:opacity-50",
                        danger ? "text-destructive hover:bg-destructive/10" : "hover:bg-accent",
                        ring,
                      )}
                    >
                      {busy === action.id ? <Loader2 className="size-4 motion-safe:animate-spin" aria-hidden="true" /> : Icon ? <Icon className="size-4" aria-hidden="true" /> : null}
                      <span className={cn(Icon && "hidden @4xl:inline")}>{action.label}</span>
                    </button>
                  );
                })
              )}
              <span className="mx-1 h-6 w-px bg-border" aria-hidden="true" />
              <button
                type="button"
                data-clear
                onClick={onClear}
                aria-label="Clear selection"
                className={cn("inline-flex h-9 items-center gap-1 rounded-xl px-2.5 text-sm text-muted-foreground hover:bg-accent hover:text-foreground", ring)}
              >
                <X className="size-4" aria-hidden="true" />
                <span className="hidden @4xl:inline">Clear</span>
              </button>
            </div>

            {overflowOpen && hidden.length > 0 && (
              <div
                ref={popRef}
                id={popId}
                role="group"
                aria-label="More selected"
                onKeyDown={(event) => {
                  if (event.key === "Escape") {
                    event.preventDefault();
                    event.stopPropagation();
                    setOverflowOpen(false);
                    moreRef.current?.focus();
                  }
                }}
                className={cn(
                  "absolute left-2 z-10 w-64 max-w-[calc(100%-1rem)] rounded-xl border border-border bg-popover p-1.5 shadow-lg motion-safe:animate-[chm-bab-chip_.16s_ease-out]",
                  bottom ? "bottom-full mb-2" : "top-full mt-2",
                )}
              >
                <ul className="max-h-56 overflow-y-auto">
                  {hidden.map((item) => (
                    <li key={item.id} className="flex items-center justify-between gap-2 rounded-lg py-1 pl-2.5 pr-1 text-sm hover:bg-accent/60">
                      <span className="truncate">{item.label}</span>
                      <button
                        type="button"
                        data-chip={item.id}
                        onClick={() => removeChip(item.id, "pop")}
                        aria-label={`Deselect ${item.label}`}
                        className={cn("grid size-7 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground", ring)}
                      >
                        <X className="size-3.5" aria-hidden="true" />
                      </button>
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  ) : null;

  return (
    <>
      <style href="chm-bulk-action-bar" precedence="default">{`@keyframes chm-bab-up{from{transform:translateY(100%);opacity:0}to{transform:none;opacity:1}}@keyframes chm-bab-down{from{transform:translateY(-100%);opacity:0}to{transform:none;opacity:1}}@keyframes chm-bab-chip{from{opacity:0;transform:scale(.94)}to{opacity:1;transform:none}}`}</style>
      <span className="sr-only" role="status" aria-live="polite">{announce}</span>
      {container === "body" && mounted ? createPortal(bar, document.body) : container === "body" ? null : bar}
    </>
  );
}