Kanban board

A task board with columns, work-in-progress limits and cards showing a tag, priority, due date, comment count and assignees. Cards move by pointer drag (mouse anywhere on the card, touch from the handle) with a drop placeholder and edge auto-scroll, or by keyboard: focus a card's handle, press Space to pick it up, use the arrow keys, Space to drop and Escape to cancel. Move buttons and live-region announcements cover the same moves. Works controlled or uncontrolled, with an optional inline add-card field and custom card bodies.

Tables & dataBlockTailwind v4

Source

"use client";

import * as React from "react";
import { Calendar, ChevronLeft, ChevronRight, CircleAlert, GripVertical, MessageSquare, Plus, X } from "lucide-react";
import { cn } from "@/lib/utils";

export type Priority = "low" | "medium" | "high" | "urgent";
export type TagTone = "neutral" | "blue" | "green" | "amber" | "rose" | "violet";

export interface KanbanCard {
  id: string;
  title: string;
  tag?: { label: string; tone?: TagTone };
  priority?: Priority;
  /** Short display date, e.g. "Nov 24". */
  due?: string;
  comments?: number;
  /** Initials or names of assignees. */
  assignees?: string[];
}

export interface KanbanColumn<C extends { id: string; title: string } = KanbanCard> {
  id: string;
  title: string;
  cards: C[];
  /** Work-in-progress limit; the count turns amber above it. */
  limit?: number;
}

export interface KanbanBoardProps<C extends { id: string; title: string } = KanbanCard> {
  /** Controlled columns. Pair with onColumnsChange. */
  columns?: KanbanColumn<C>[];
  /** Initial columns when uncontrolled. */
  defaultColumns?: KanbanColumn<C>[];
  onColumnsChange?: (columns: KanbanColumn<C>[]) => void;
  /** Renders the body of a card. Defaults to tag, title, priority, due date, comments and assignees. */
  renderCard?: (card: C) => React.ReactNode;
  /** Creates a card from the inline "Add card" field. Omit to hide the field. */
  createCard?: (title: string, columnId: string) => C;
  /** Accessible name of the board. */
  label?: string;
  className?: string;
}

type Target = { col: string; index: number };

const TAG: Record<TagTone, string> = {
  neutral: "bg-muted text-muted-foreground",
  blue: "bg-sky-500/12 text-sky-700 dark:text-sky-300",
  green: "bg-emerald-500/12 text-emerald-700 dark:text-emerald-300",
  amber: "bg-amber-500/15 text-amber-700 dark:text-amber-300",
  rose: "bg-rose-500/12 text-rose-700 dark:text-rose-300",
  violet: "bg-violet-500/12 text-violet-700 dark:text-violet-300",
};

const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-ring";

function locate(columns: { cards: { id: string }[] }[], id: string) {
  for (let col = 0; col < columns.length; col++) {
    const index = columns[col].cards.findIndex((card) => card.id === id);
    if (index >= 0) return { col, index };
  }
  return null;
}

function moveCard<C extends { id: string; title: string }>(columns: KanbanColumn<C>[], id: string, to: string, index: number) {
  let moving: C | undefined;
  const without = columns.map((column) => {
    const found = column.cards.find((card) => card.id === id);
    if (!found) return column;
    moving = found;
    return { ...column, cards: column.cards.filter((card) => card.id !== id) };
  });
  if (!moving) return columns;
  return without.map((column) =>
    column.id === to ? { ...column, cards: [...column.cards.slice(0, index), moving!, ...column.cards.slice(index)] } : column,
  );
}

function PriorityMark({ priority }: { priority: Priority }) {
  const label = `${priority[0].toUpperCase()}${priority.slice(1)} priority`;
  if (priority === "urgent")
    return (
      <span title={label} className="text-rose-600 dark:text-rose-400">
        <CircleAlert aria-hidden className="size-3.5" />
        <span className="sr-only">{label}</span>
      </span>
    );
  const level = priority === "high" ? 3 : priority === "medium" ? 2 : 1;
  return (
    <span title={label} className="inline-flex h-3 items-end gap-px">
      {[1, 2, 3].map((bar) => (
        <span key={bar} aria-hidden className={cn("w-[3px] rounded-sm", bar <= level ? "bg-foreground/70" : "bg-foreground/15")} style={{ height: 4 + bar * 2.5 }} />
      ))}
      <span className="sr-only">{label}</span>
    </span>
  );
}

export function DefaultCardBody({ card }: { card: KanbanCard }) {
  return (
    <>
      {card.tag && <span className={cn("mb-2 inline-flex rounded px-1.5 py-0.5 text-[11px] font-medium", TAG[card.tag.tone || "neutral"])}>{card.tag.label}</span>}
      <p className="text-sm leading-snug font-medium">{card.title}</p>
      {(card.priority || card.due || card.comments || card.assignees?.length) && (
        <div className="mt-3 flex items-center gap-3 text-xs text-muted-foreground">
          {card.priority && <PriorityMark priority={card.priority} />}
          {card.due && (
            <span className="inline-flex items-center gap-1">
              <Calendar aria-hidden className="size-3.5" />
              <span className="sr-only">Due</span>
              {card.due}
            </span>
          )}
          {!!card.comments && (
            <span className="inline-flex items-center gap-1 tabular-nums">
              <MessageSquare aria-hidden className="size-3.5" />
              {card.comments}
              <span className="sr-only">comments</span>
            </span>
          )}
          {!!card.assignees?.length && (
            <span className="ml-auto flex -space-x-1.5">
              {card.assignees.map((person) => (
                <span key={person} title={person} className="grid size-6 place-items-center rounded-full bg-muted text-[10px] font-semibold text-foreground ring-2 ring-card">
                  {person.length <= 3 ? person : person.split(/\s+/).map((part) => part[0]).join("").slice(0, 2)}
                </span>
              ))}
            </span>
          )}
        </div>
      )}
    </>
  );
}

export function KanbanBoard<C extends { id: string; title: string } = KanbanCard>({
  columns: controlled,
  defaultColumns,
  onColumnsChange,
  renderCard,
  createCard,
  label = "Board",
  className,
}: KanbanBoardProps<C>) {
  const [inner, setInner] = React.useState<KanbanColumn<C>[]>(defaultColumns ?? []);
  const columns = controlled ?? inner;
  const columnsRef = React.useRef(columns);
  columnsRef.current = columns;

  const [press, setPress] = React.useState<{ id: string; startX: number; startY: number; rect: DOMRect } | null>(null);
  const [ghost, setGhost] = React.useState<{ id: string; x: number; y: number; width: number; height: number } | null>(null);
  const [target, setTarget] = React.useState<Target | null>(null);
  const [grabbed, setGrabbed] = React.useState<{ id: string; snapshot: KanbanColumn<C>[] } | null>(null);
  const [adding, setAdding] = React.useState<string | null>(null);
  const [message, setMessage] = React.useState("");
  const lists = React.useRef(new Map<string, HTMLElement>());
  const scroller = React.useRef<HTMLDivElement>(null);
  const focusAfter = React.useRef<string | null>(null);
  const instructionsId = React.useId();

  const setColumns = (next: KanbanColumn<C>[]) => {
    columnsRef.current = next;
    if (!controlled) setInner(next);
    onColumnsChange?.(next);
  };
  const titleOf = (id: string) => {
    const at = locate(columnsRef.current, id);
    return at ? columnsRef.current[at.col].cards[at.index].title : "Card";
  };
  const describe = (id: string) => {
    const at = locate(columnsRef.current, id);
    if (!at) return "";
    const column = columnsRef.current[at.col];
    return `${column.title}, position ${at.index + 1} of ${column.cards.length}`;
  };

  // Keyboard moves remount the card in its new column; put focus back on its handle.
  React.useLayoutEffect(() => {
    if (!focusAfter.current) return;
    const id = focusAfter.current;
    focusAfter.current = null;
    scroller.current?.querySelector<HTMLElement>(`[data-handle-for="${CSS.escape(id)}"]`)?.focus();
  });

  function moveBy(id: string, dCol: number, dIndex: number) {
    const cols = columnsRef.current;
    const at = locate(cols, id);
    if (!at) return;
    const col = at.col + dCol;
    if (col < 0 || col >= cols.length) return;
    const index = dCol ? Math.min(at.index, cols[col].cards.length) : at.index + dIndex;
    if (!dCol && (index < 0 || index >= cols[col].cards.length)) return;
    focusAfter.current = id;
    setColumns(moveCard(cols, id, cols[col].id, index));
    setMessage(`${titleOf(id)} moved to ${describe(id)}.`);
  }

  // Pointer dragging: a 5px threshold separates clicks from drags; Escape cancels.
  function hitTest(x: number, y: number, dragId: string): Target | null {
    let best: { col: string; distance: number; list: HTMLElement } | null = null;
    for (const [col, list] of lists.current) {
      const rect = list.getBoundingClientRect();
      const distance = x < rect.left ? rect.left - x : x > rect.right ? x - rect.right : 0;
      if (!best || distance < best.distance) best = { col, distance, list };
    }
    if (!best || best.distance > 120) return null;
    const cards = Array.from(best.list.querySelectorAll<HTMLElement>("[data-card-id]")).filter((node) => node.dataset.cardId !== dragId);
    let index = cards.length;
    for (let i = 0; i < cards.length; i++) {
      const rect = cards[i].getBoundingClientRect();
      if (y < rect.top + rect.height / 2) {
        index = i;
        break;
      }
    }
    return { col: best.col, index };
  }

  React.useEffect(() => {
    if (!press) return;
    let active = false;
    let last: Target | null = null;
    const reset = () => {
      document.body.style.userSelect = "";
      document.body.style.cursor = "";
    };
    const onMove = (event: PointerEvent) => {
      if (!active) {
        if (Math.hypot(event.clientX - press.startX, event.clientY - press.startY) < 5) return;
        active = true;
        document.body.style.userSelect = "none";
        document.body.style.cursor = "grabbing";
        const at = locate(columnsRef.current, press.id);
        if (at) last = { col: columnsRef.current[at.col].id, index: at.index };
        setMessage(`Picked up ${titleOf(press.id)}.`);
      }
      event.preventDefault();
      setGhost({
        id: press.id,
        x: event.clientX - (press.startX - press.rect.left),
        y: event.clientY - (press.startY - press.rect.top),
        width: press.rect.width,
        height: press.rect.height,
      });
      last = hitTest(event.clientX, event.clientY, press.id) ?? last;
      setTarget(last);
      const box = scroller.current?.getBoundingClientRect();
      if (box && scroller.current) {
        if (event.clientX < box.left + 48) scroller.current.scrollLeft -= 14;
        else if (event.clientX > box.right - 48) scroller.current.scrollLeft += 14;
      }
    };
    const finish = (commit: boolean) => {
      if (active && commit && last) {
        setColumns(moveCard(columnsRef.current, press.id, last.col, last.index));
        setMessage(`${titleOf(press.id)} dropped in ${describe(press.id)}.`);
      } else if (active) setMessage("Move cancelled.");
      setGhost(null);
      setTarget(null);
      setPress(null);
      reset();
    };
    const onUp = () => finish(true);
    const onCancel = () => finish(false);
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape" && active) {
        event.preventDefault();
        finish(false);
      }
    };
    window.addEventListener("pointermove", onMove, { passive: false });
    window.addEventListener("pointerup", onUp);
    window.addEventListener("pointercancel", onCancel);
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("pointermove", onMove);
      window.removeEventListener("pointerup", onUp);
      window.removeEventListener("pointercancel", onCancel);
      window.removeEventListener("keydown", onKey);
      reset();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [press]);

  function onPointerDown(event: React.PointerEvent<HTMLElement>, id: string) {
    if (event.button !== 0 || grabbed) return;
    const node = event.target as HTMLElement;
    if (node.closest("button:not([data-drag-handle]), a, input, textarea")) return;
    // Touch and pen start from the handle so the board can still scroll.
    if (event.pointerType !== "mouse" && !node.closest("[data-drag-handle]")) return;
    setPress({ id, startX: event.clientX, startY: event.clientY, rect: event.currentTarget.getBoundingClientRect() });
  }

  function onHandleKeyDown(event: React.KeyboardEvent<HTMLButtonElement>, id: string, col: number, index: number) {
    const key = event.key;
    if (key === " " || key === "Enter") {
      event.preventDefault();
      if (grabbed?.id === id) {
        setGrabbed(null);
        setMessage(`${titleOf(id)} dropped in ${describe(id)}.`);
      } else {
        setGrabbed({ id, snapshot: columnsRef.current });
        setMessage(`Picked up ${titleOf(id)}, ${describe(id)}. Use arrow keys to move, Space to drop, Escape to cancel.`);
      }
      return;
    }
    if (grabbed?.id === id) {
      const moves: Record<string, [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] };
      if (moves[key]) {
        event.preventDefault();
        moveBy(id, ...moves[key]);
      } else if (key === "Escape") {
        event.preventDefault();
        focusAfter.current = id;
        setColumns(grabbed.snapshot);
        setGrabbed(null);
        setMessage(`Move cancelled. ${titleOf(id)} is back in ${describe(id)}.`);
      }
      return;
    }
    // Not holding a card: arrow keys move focus between cards.
    const cols = columnsRef.current;
    const focusCard = (c: number, i: number) => {
      const card = cols[c]?.cards[Math.max(0, Math.min(i, cols[c].cards.length - 1))];
      if (!card) return false;
      scroller.current?.querySelector<HTMLElement>(`[data-handle-for="${CSS.escape(card.id)}"]`)?.focus();
      return true;
    };
    if (key === "ArrowDown" || key === "ArrowUp") {
      event.preventDefault();
      focusCard(col, index + (key === "ArrowDown" ? 1 : -1));
    } else if (key === "ArrowLeft" || key === "ArrowRight") {
      event.preventDefault();
      const step = key === "ArrowRight" ? 1 : -1;
      for (let c = col + step; c >= 0 && c < cols.length; c += step) if (focusCard(c, index)) break;
    }
  }

  function addCard(columnId: string, title: string) {
    if (!createCard || !title.trim()) return;
    const card = createCard(title.trim(), columnId);
    setColumns(columnsRef.current.map((column) => (column.id === columnId ? { ...column, cards: [...column.cards, card] } : column)));
    setMessage(`Added ${card.title} to ${columns.find((column) => column.id === columnId)?.title}.`);
  }

  const ghostCard = ghost ? columns.flatMap((column) => column.cards).find((card) => card.id === ghost.id) : undefined;
  const body = (card: C) => (renderCard ? renderCard(card) : <DefaultCardBody card={card as unknown as KanbanCard} />);

  return (
    <div className={cn("min-w-0", className)}>
      <p id={instructionsId} className="sr-only">
        Press Space or Enter to pick up a card. While holding it, arrow keys move it between columns and positions, Space drops it and Escape cancels.
      </p>
      <div ref={scroller} role="region" aria-label={label} className="flex snap-x snap-mandatory gap-3 overflow-x-auto pb-3 sm:gap-4">
        {columns.map((column, colIndex) => {
          const visible = column.cards.filter((card) => card.id !== ghost?.id);
          const over = column.limit !== undefined && column.cards.length > column.limit;
          const items: (C | "placeholder")[] = [...visible];
          if (ghost && target?.col === column.id) items.splice(Math.min(target.index, items.length), 0, "placeholder");
          const headingId = `${instructionsId}-${column.id}`;
          return (
            <section
              key={column.id}
              aria-labelledby={headingId}
              className={cn(
                "flex w-[min(18rem,82vw)] shrink-0 snap-start flex-col rounded-xl bg-muted/60 p-2 transition-colors dark:bg-muted/40",
                ghost && target?.col === column.id && "bg-muted dark:bg-muted/70",
              )}
            >
              <header className="flex items-center gap-2 px-2 pt-1 pb-2.5">
                <h3 id={headingId} className="text-sm font-semibold">
                  {column.title}
                </h3>
                <span
                  className={cn(
                    "rounded-full px-1.5 text-xs tabular-nums",
                    over ? "bg-amber-500/15 font-medium text-amber-700 dark:text-amber-400" : "text-muted-foreground",
                  )}
                >
                  {column.cards.length}
                  {column.limit !== undefined && `/${column.limit}`}
                  {over && <span className="sr-only">, over the limit</span>}
                </span>
                {createCard && (
                  <button
                    type="button"
                    onClick={() => setAdding(column.id)}
                    aria-label={`Add card to ${column.title}`}
                    className={cn("ml-auto grid size-7 place-items-center rounded-md text-muted-foreground hover:bg-background hover:text-foreground", focusRing)}
                  >
                    <Plus aria-hidden className="size-4" />
                  </button>
                )}
              </header>

              <ul
                ref={(node) => {
                  if (node) lists.current.set(column.id, node);
                  else lists.current.delete(column.id);
                }}
                className="flex min-h-24 flex-1 flex-col gap-2"
              >
                {items.map((item, index) => {
                  if (item === "placeholder")
                    return (
                      <li
                        key="placeholder"
                        aria-hidden
                        className="rounded-lg border-2 border-dashed border-muted-foreground/25 bg-background/40"
                        style={{ height: ghost?.height }}
                      />
                    );
                  const card = item;
                  const isGrabbed = grabbed?.id === card.id;
                  const cardIndex = column.cards.indexOf(card);
                  return (
                    <li key={card.id} data-card-id={card.id}>
                      <article
                        onPointerDown={(event) => onPointerDown(event, card.id)}
                        className={cn(
                          "group relative min-h-[5.5rem] cursor-grab rounded-lg border bg-card p-3 pr-9 text-card-foreground shadow-xs transition-shadow hover:shadow-sm active:cursor-grabbing",
                          isGrabbed && "z-10 ring-2 ring-ring shadow-lg motion-safe:-rotate-1",
                        )}
                      >
                        {body(card)}
                        <div className="absolute inset-y-1.5 right-1.5 flex flex-col items-center justify-between">
                          <button
                            type="button"
                            data-drag-handle
                            data-handle-for={card.id}
                            aria-roledescription="draggable card"
                            aria-describedby={instructionsId}
                            aria-pressed={isGrabbed}
                            aria-label={`${card.title}, ${column.title}, position ${cardIndex + 1} of ${column.cards.length}`}
                            onKeyDown={(event) => onHandleKeyDown(event, card.id, colIndex, cardIndex)}
                            onBlur={() => {
                              if (isGrabbed && !focusAfter.current) setGrabbed(null);
                            }}
                            className={cn(
                              "grid h-7 w-6 touch-none place-items-center rounded-md text-muted-foreground/60 hover:bg-muted hover:text-foreground",
                              focusRing,
                              isGrabbed && "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground",
                            )}
                          >
                            <GripVertical aria-hidden className="size-4" />
                          </button>
                          <div className="flex flex-col gap-0.5 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100">
                            {colIndex > 0 && (
                              <button
                                type="button"
                                onClick={() => moveBy(card.id, -1, 0)}
                                aria-label={`Move to ${columns[colIndex - 1].title}`}
                                className={cn("grid size-6 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground", focusRing)}
                              >
                                <ChevronLeft aria-hidden className="size-3.5" />
                              </button>
                            )}
                            {colIndex < columns.length - 1 && (
                              <button
                                type="button"
                                onClick={() => moveBy(card.id, 1, 0)}
                                aria-label={`Move to ${columns[colIndex + 1].title}`}
                                className={cn("grid size-6 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground", focusRing)}
                              >
                                <ChevronRight aria-hidden className="size-3.5" />
                              </button>
                            )}
                          </div>
                        </div>
                      </article>
                    </li>
                  );
                })}
                {!items.length && (
                  <li aria-hidden className="grid flex-1 place-items-center rounded-lg border border-dashed border-muted-foreground/25 text-xs text-muted-foreground">
                    No cards
                  </li>
                )}
              </ul>

              {createCard && adding === column.id && (
                <form
                  className="mt-2"
                  onSubmit={(event) => {
                    event.preventDefault();
                    const input = event.currentTarget.elements.namedItem("title") as HTMLInputElement;
                    addCard(column.id, input.value);
                    input.value = "";
                  }}
                >
                  <div className="flex gap-1.5">
                    <input
                      name="title"
                      autoFocus
                      aria-label={`New card in ${column.title}`}
                      placeholder="Card title"
                      onKeyDown={(event) => event.key === "Escape" && setAdding(null)}
                      className="h-9 min-w-0 flex-1 rounded-md border border-input bg-background px-2.5 text-sm outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30"
                    />
                    <button
                      type="button"
                      onClick={() => setAdding(null)}
                      aria-label="Cancel"
                      className={cn("grid size-9 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-background hover:text-foreground", focusRing)}
                    >
                      <X aria-hidden className="size-4" />
                    </button>
                  </div>
                </form>
              )}
            </section>
          );
        })}
      </div>

      {ghost && ghostCard && (
        <div
          aria-hidden
          className="pointer-events-none fixed top-0 left-0 z-50 min-h-[5.5rem] rounded-lg border bg-card p-3 pr-9 text-card-foreground shadow-xl ring-1 ring-ring/30 motion-safe:rotate-2"
          style={{ width: ghost.width, transform: `translate(${ghost.x}px, ${ghost.y}px)` }}
        >
          {body(ghostCard)}
        </div>
      )}
      <p aria-live="assertive" className="sr-only">
        {message}
      </p>
    </div>
  );
}