Kanban
SaveA board of columns and cards you move by pointer or keyboard, with column counts, WIP limits, an empty state and an add field, where a card in flight tilts with its speed.
- Category
- Data display
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Kanban preview
Press Space or Enter to lift the card. Use the arrow keys to move it, left and right to change column. Press Space or Enter to drop it, Escape to cancel.
Installation
npx @shakenui/cli add kanbanReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add kanban --dry-runUsage
kanban-example.tsx
"use client";
import { useState } from "react";
import { Kanban, type KanbanColumnData } from "@/components/shaken/ui/kanban";
const initial: KanbanColumnData[] = [
{
id: "backlog",
title: "Backlog",
cards: [
{ id: "shk-212", title: "Retry tool calls that time out", meta: "SHK-212", assignee: "Priya Raman" },
{ id: "shk-219", title: "Show cached tokens in the usage panel", meta: "SHK-219" },
{ id: "shk-224", title: "Export a run trace as JSON", description: "Include every step, its inputs, and the model's raw output.", meta: "SHK-224", assignee: "Kenji Mori" },
],
},
{
id: "doing",
title: "In progress",
limit: 3,
cards: [
{ id: "shk-198", title: "Approval step for payouts over $5,000", meta: "SHK-198", assignee: "Ines Duarte" },
{ id: "shk-205", title: "Stream reasoning into the side panel", meta: "SHK-205", assignee: "Tomás Okafor" },
{ id: "shk-207", title: "Rate limit the public search endpoint", meta: "SHK-207", assignee: "Priya Raman" },
],
},
{
id: "review",
title: "Review",
limit: 2,
cards: [{ id: "shk-191", title: "Fix the 504 on long fetch_page calls", description: "Raise the gateway timeout and stream partial results.", meta: "SHK-191", assignee: "Kenji Mori" }],
},
{ id: "done", title: "Done", cards: [] },
];
export default function KanbanExample() {
const [columns, setColumns] = useState(initial);
return <Kanban aria-label="Agent platform sprint" columns={columns} onColumnsChange={setColumns} className="max-w-full" />;
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| columns | { id, title, limit?, cards: Card[] }[] | — | The board. Cards need an id and a title; description, meta and assignee are optional. It is controlled. |
| onColumnsChange | (columns) => void | — | Called with the next board after a move or an added card. |
| onCardMove | (move: { card, from, to }) => void | — | Called after a card lands somewhere new, with column ids and indexes. |
| renderCard | (card, { lifted }) => ReactNode | — | Custom card content. Defaults to title, description, meta and assignee initials. |
| addable | boolean | true | Shows an Add card control at the foot of each column. |
| createCard | (title: string, columnId: string) => Card | — | Builds a card from the typed title. Defaults to a generated id and the title. |
| disabled | boolean | false | Turns off moving and adding. |
Accessibility
- Each column is a section named by its heading; its count says how many cards it holds and the limit, and "Over limit" is written out, not only shown in amber.
- Cards are focusable buttons described by the keyboard instructions. With nothing lifted, the arrow keys move focus between cards and columns.
- Space or Enter lifts a card (aria-pressed="true"); Arrow Up and Down move it within the column, Arrow Left and Right move it to the next column, Space or Enter drops it, and Escape returns it. Focus follows the card.
- Pick up, each new position (column, position and count), drop, cancel, added cards and going over a WIP limit are announced in an assertive live region.
- Escape cancels a pointer drag. A press only becomes a drag after the pointer moves 4px, so cards still take clicks and focus.
- The add field is labeled with its column; Escape or Cancel closes it and returns focus to the Add card button.
- Keyboard moves do not animate position. With reduced motion the floating card does not tilt or scale, cards do not glide, and a drop lands at once.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/ui/kanban.tsxkanban- npm packages: motion@^14.14.0React and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/kanban/0.1.0.json.
ui/kanban.tsxShowHide
ui/kanban.tsx
"use client";
import {
animate,
motion,
useMotionValue,
useReducedMotion,
useSpring,
useTransform,
useVelocity,
type Transition,
} from "motion/react";
import {
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
type ComponentProps,
type FormEvent,
type KeyboardEvent,
type PointerEvent as ReactPointerEvent,
type ReactNode,
} from "react";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
const glide: Transition = { type: "spring", duration: 0.35, bounce: 0 };
const settle: Transition = { type: "spring", duration: 0.32, bounce: 0 };
/** Pixels a pointer must travel before a press becomes a drag, so cards still take clicks and focus. */
const THRESHOLD = 4;
export interface KanbanCardData {
id: string;
title: string;
/** A line or two of detail under the title. */
description?: string;
/** A short identifier at the card's foot, such as an issue key. */
meta?: string;
/** A person's name; the card shows their initials. */
assignee?: string;
}
export interface KanbanColumnData<Card extends KanbanCardData = KanbanCardData> {
id: string;
title: string;
/** Work-in-progress limit. The count turns amber and says so once the column holds more. */
limit?: number;
cards: Card[];
}
export interface KanbanPosition {
columnId: string;
index: number;
}
export interface KanbanMove<Card extends KanbanCardData = KanbanCardData> {
card: Card;
from: KanbanPosition;
to: KanbanPosition;
}
export interface KanbanProps<Card extends KanbanCardData = KanbanCardData>
extends Omit<ComponentProps<"div">, "children" | "onChange"> {
/** The board. It is controlled: apply changes from `onColumnsChange`. */
columns: KanbanColumnData<Card>[];
/** Called with the next board after a card moves or is added. */
onColumnsChange: (columns: KanbanColumnData<Card>[]) => void;
/** Called after a card lands somewhere new, with where it came from and went. */
onCardMove?: (move: KanbanMove<Card>) => void;
/** Renders a card's content. Defaults to the title, description, meta and assignee initials. */
renderCard?: (card: Card, state: { lifted: boolean }) => ReactNode;
/** Shows an "Add card" control at the foot of each column. Defaults to true. */
addable?: boolean;
/** Builds a card from the title typed into a column's add field. */
createCard?: (title: string, columnId: string) => Card;
/** Turns off moving and adding. */
disabled?: boolean;
}
type Mode = "pointer" | "keyboard";
type Drag = { id: string; mode: Mode; from: KanbanPosition; to: KanbanPosition };
type Pending = {
id: string;
pointerId: number;
startX: number;
startY: number;
grabX: number;
grabY: number;
el: HTMLElement;
started: boolean;
};
function locate<Card extends KanbanCardData>(columns: KanbanColumnData<Card>[], id: string) {
for (const column of columns) {
const index = column.cards.findIndex((card) => card.id === id);
if (index !== -1) return { columnId: column.id, index, card: column.cards[index]! };
}
return null;
}
function moveCard<Card extends KanbanCardData>(columns: KanbanColumnData<Card>[], id: string, to: KanbanPosition) {
const found = locate(columns, id);
if (!found) return columns;
const without = columns.map((column) =>
column.id === found.columnId ? { ...column, cards: column.cards.filter((card) => card.id !== id) } : column,
);
return without.map((column) => {
if (column.id !== to.columnId) return column;
const cards = column.cards.slice();
cards.splice(Math.min(to.index, cards.length), 0, found.card);
return { ...column, cards };
});
}
function defaultCreateCard(title: string, columnId: string) {
return { id: `${columnId}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`, title } as KanbanCardData;
}
function initials(name: string) {
return name
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part[0]!.toUpperCase())
.join("");
}
/**
* A board of columns and cards. Drag a card within or between columns: it lifts, tilts a little
* with the pointer's speed, the column under it highlights, and the other cards glide aside around
* a dashed slot. From the keyboard, Space or Enter lifts a focused card, the arrow keys move it
* (left and right change column), Space or Enter drops it and Escape returns it. Columns show
* their count, an optional WIP limit, an empty state, and an add field.
*/
export function Kanban<Card extends KanbanCardData = KanbanCardData>({
columns,
onColumnsChange,
onCardMove,
renderCard,
addable = true,
createCard = defaultCreateCard as unknown as (title: string, columnId: string) => Card,
disabled = false,
className,
...props
}: KanbanProps<Card>) {
const instructionsId = useId();
const reduce = useReducedMotion() ?? false;
const columnsRef = useRef(columns);
columnsRef.current = columns;
const scroller = useRef<HTMLDivElement>(null);
const content = useRef<HTMLDivElement>(null);
const lanes = useRef(new Map<string, HTMLElement>());
const lists = useRef(new Map<string, HTMLUListElement>());
const cardEls = useRef(new Map<string, HTMLLIElement>());
const cardButtons = useRef(new Map<string, HTMLDivElement>());
const [drag, setDragState] = useState<Drag | null>(null);
const dragRef = useRef<Drag | null>(null);
const setDrag = (next: Drag | null) => {
dragRef.current = next;
setDragState(next);
};
const [ghost, setGhost] = useState<{ card: Card; width: number; height: number } | null>(null);
const [settlingId, setSettlingId] = useState<string | null>(null);
const [glideOn, setGlideOn] = useState(true);
const [message, setMessage] = useState("");
const [addingTo, setAddingTo] = useState<string | null>(null);
const pending = useRef<Pending | null>(null);
const addButtons = useRef(new Map<string, HTMLButtonElement>());
const refocusAdd = useRef<string | null>(null);
const refocus = useRef<string | null>(null);
const moving = useRef(false);
// The floating card: position, a lean that follows horizontal speed, and a small lift.
const gx = useMotionValue(0);
const gy = useMotionValue(0);
const vx = useVelocity(gx);
const lean = useSpring(useTransform(vx, [-1400, 0, 1400], [-5, 0, 5], { clamp: true }), { stiffness: 320, damping: 30 });
const titleOf = (id: string) => locate(columnsRef.current, id)?.card.title ?? "Card";
const columnTitle = (id: string) => columnsRef.current.find((column) => column.id === id)?.title ?? "";
const columnSize = (columnId: string, without: string) =>
columnsRef.current.find((column) => column.id === columnId)?.cards.filter((card) => card.id !== without).length ?? 0;
function describe(id: string, to: KanbanPosition) {
const size = columnSize(to.columnId, id) + 1;
return `${columnTitle(to.columnId)}, position ${to.index + 1} of ${size}`;
}
function limitNote(id: string, to: KanbanPosition) {
const column = columnsRef.current.find((c) => c.id === to.columnId);
const size = columnSize(to.columnId, id) + 1;
return column?.limit != null && size > column.limit ? ` ${column.title} is over its limit of ${column.limit}.` : "";
}
function commit(id: string, from: KanbanPosition, to: KanbanPosition) {
if (from.columnId === to.columnId && from.index === to.index) return;
const card = locate(columnsRef.current, id)?.card;
const next = moveCard(columnsRef.current, id, to);
columnsRef.current = next;
onColumnsChange(next);
if (card) onCardMove?.({ card, from, to });
}
// ---- Pointer ----
function targetAt(clientX: number, centerY: number, id: string): KanbanPosition | null {
let best: { columnId: string; distance: number } | null = null;
for (const column of columnsRef.current) {
const lane = lanes.current.get(column.id);
if (!lane) continue;
const rect = lane.getBoundingClientRect();
const distance = clientX < rect.left ? rect.left - clientX : clientX > rect.right ? clientX - rect.right : 0;
if (!best || distance < best.distance) best = { columnId: column.id, distance };
}
if (!best) return null;
const list = lists.current.get(best.columnId);
const column = columnsRef.current.find((c) => c.id === best.columnId);
if (!list || !column) return null;
// Count the cards whose middle sits above the floating card's middle, laid out as if the
// dragged card were gone; layout offsets ignore in-flight glides, so the slot never flickers.
const style = getComputedStyle(list);
const gap = parseFloat(style.rowGap) || 0;
let top = list.getBoundingClientRect().top + (parseFloat(style.paddingTop) || 0);
let index = 0;
for (const card of column.cards) {
if (card.id === id) continue;
const el = cardEls.current.get(card.id);
if (!el) continue;
if (top + el.offsetHeight / 2 < centerY) index++;
top += el.offsetHeight + gap;
}
return { columnId: best.columnId, index };
}
function startPointerDrag(p: Pending) {
const found = locate(columnsRef.current, p.id);
const box = content.current;
if (!found || !box) return;
const rect = p.el.getBoundingClientRect();
const origin = box.getBoundingClientRect();
p.started = true;
p.grabX = p.startX - rect.left;
p.grabY = p.startY - rect.top;
gx.jump(rect.left - origin.left);
gy.jump(rect.top - origin.top);
lean.jump(0);
setGlideOn(true);
setSettlingId(null);
setGhost({ card: found.card, width: rect.width, height: rect.height });
const from = { columnId: found.columnId, index: found.index };
setDrag({ id: p.id, mode: "pointer", from, to: from });
setMessage(`Picked up ${found.card.title}. ${describe(p.id, from)}.`);
}
function onWindowPointerMove(event: PointerEvent) {
const p = pending.current;
if (!p || event.pointerId !== p.pointerId) return;
if (!p.started) {
if (Math.hypot(event.clientX - p.startX, event.clientY - p.startY) < THRESHOLD) return;
startPointerDrag(p);
}
const box = content.current;
const d = dragRef.current;
if (!box || !d) return;
event.preventDefault();
const origin = box.getBoundingClientRect();
gx.set(event.clientX - origin.left - p.grabX);
gy.set(event.clientY - origin.top - p.grabY);
// Nudge the board sideways when the pointer nears its edges, for narrow screens.
const strip = scroller.current;
if (strip) {
const r = strip.getBoundingClientRect();
if (event.clientX < r.left + 40) strip.scrollLeft -= 14;
else if (event.clientX > r.right - 40) strip.scrollLeft += 14;
}
const height = ghost?.height ?? p.el.offsetHeight;
const to = targetAt(event.clientX, event.clientY - p.grabY + height / 2, d.id);
if (to && (to.columnId !== d.to.columnId || to.index !== d.to.index)) {
setDrag({ ...d, to });
setMessage(`${titleOf(d.id)}, ${describe(d.id, to)}.`);
}
}
function onWindowPointerUp(event: PointerEvent) {
const p = pending.current;
if (!p || event.pointerId !== p.pointerId) return;
detachWindow();
pending.current = null;
if (p.started) finishPointer(event.type === "pointercancel");
}
function onWindowKey(event: globalThis.KeyboardEvent) {
if (event.key !== "Escape" || !pending.current?.started) return;
event.preventDefault();
detachWindow();
pending.current = null;
finishPointer(true);
}
// Window listeners outlive the card element, which unmounts while it floats.
const listeners = useRef({ move: onWindowPointerMove, up: onWindowPointerUp, key: onWindowKey });
listeners.current = { move: onWindowPointerMove, up: onWindowPointerUp, key: onWindowKey };
const stable = useRef({
move: (e: PointerEvent) => listeners.current.move(e),
up: (e: PointerEvent) => listeners.current.up(e),
key: (e: globalThis.KeyboardEvent) => listeners.current.key(e),
}).current;
function attachWindow() {
window.addEventListener("pointermove", stable.move, { passive: false });
window.addEventListener("pointerup", stable.up);
window.addEventListener("pointercancel", stable.up);
window.addEventListener("keydown", stable.key);
}
function detachWindow() {
window.removeEventListener("pointermove", stable.move);
window.removeEventListener("pointerup", stable.up);
window.removeEventListener("pointercancel", stable.up);
window.removeEventListener("keydown", stable.key);
}
useEffect(() => detachWindow, []); // eslint-disable-line react-hooks/exhaustive-deps
// The grabbing cursor holds for the whole drag, wherever the pointer goes.
useEffect(() => {
if (drag?.mode !== "pointer") return;
const body = document.body.style;
const previous = { cursor: body.cursor, userSelect: body.userSelect };
body.cursor = "grabbing";
body.userSelect = "none";
return () => {
body.cursor = previous.cursor;
body.userSelect = previous.userSelect;
};
}, [drag?.mode]);
function onCardPointerDown(id: string, event: ReactPointerEvent<HTMLDivElement>) {
if (disabled || event.button !== 0 || dragRef.current || pending.current) return;
if ((event.target as HTMLElement).closest("a,button,input,textarea,select")) return;
pending.current = {
id,
pointerId: event.pointerId,
startX: event.clientX,
startY: event.clientY,
grabX: 0,
grabY: 0,
el: event.currentTarget,
started: false,
};
attachWindow();
}
function finishPointer(cancel: boolean) {
const d = dragRef.current;
if (!d) return;
const to = cancel ? d.from : d.to;
const title = titleOf(d.id);
commit(d.id, d.from, to);
setDrag(null);
setSettlingId(d.id);
setMessage(
cancel
? `Move cancelled. ${title} returned to ${describe(d.id, d.from)}.`
: `Dropped ${title} in ${describe(d.id, to)}.${limitNote(d.id, to)}`,
);
}
// Fly the floating card into the slot it landed in, then hand over to the real card.
useLayoutEffect(() => {
if (!settlingId) return;
const el = cardEls.current.get(settlingId);
const box = content.current;
const done = () => {
setGhost(null);
setSettlingId(null);
};
if (!el || !box || reduce) {
done();
return;
}
const target = el.getBoundingClientRect();
const origin = box.getBoundingClientRect();
const x = animate(gx, target.left - origin.left, settle);
const y = animate(gy, target.top - origin.top, settle);
lean.set(0);
Promise.all([x, y]).then(done, done);
return () => {
x.stop();
y.stop();
};
}, [settlingId, reduce, gx, gy, lean]);
// ---- Keyboard ----
useLayoutEffect(() => {
if (refocus.current) {
const el = cardButtons.current.get(refocus.current);
if (el && document.activeElement !== el) el.focus({ preventScroll: false });
refocus.current = null;
}
if (refocusAdd.current) {
addButtons.current.get(refocusAdd.current)?.focus();
refocusAdd.current = null;
}
moving.current = false;
});
function focusCard(id: string | undefined) {
if (id) cardButtons.current.get(id)?.focus();
}
function onCardKeyDown(id: string, event: KeyboardEvent<HTMLDivElement>) {
if (event.target !== event.currentTarget) return;
const current = dragRef.current;
const board = columnsRef.current;
if (!current) {
const here = locate(board, id);
if (!here) return;
const col = board.findIndex((c) => c.id === here.columnId);
if ((event.key === " " || event.key === "Enter") && !disabled) {
event.preventDefault();
const from = { columnId: here.columnId, index: here.index };
setGlideOn(false);
moving.current = true;
refocus.current = id;
setDrag({ id, mode: "keyboard", from, to: from });
setMessage(`Lifted ${here.card.title}. ${describe(id, from)}. Use the arrow keys to move it, Space to drop, Escape to cancel.`);
return;
}
// Arrow keys walk between cards when nothing is lifted.
let next: string | undefined;
if (event.key === "ArrowDown") next = board[col]!.cards[here.index + 1]?.id;
else if (event.key === "ArrowUp") next = board[col]!.cards[here.index - 1]?.id;
else if (event.key === "ArrowRight" || event.key === "ArrowLeft") {
const step = event.key === "ArrowRight" ? 1 : -1;
for (let c = col + step; c >= 0 && c < board.length; c += step) {
const cards = board[c]!.cards;
if (cards.length) {
next = cards[Math.min(here.index, cards.length - 1)]!.id;
break;
}
}
} else return;
event.preventDefault();
focusCard(next);
return;
}
if (current.mode !== "keyboard" || current.id !== id) return;
const title = titleOf(id);
let to = current.to;
const col = board.findIndex((c) => c.id === to.columnId);
switch (event.key) {
case "ArrowUp":
to = { ...to, index: Math.max(0, to.index - 1) };
break;
case "ArrowDown":
to = { ...to, index: Math.min(columnSize(to.columnId, id), to.index + 1) };
break;
case "ArrowLeft":
case "ArrowRight": {
const target = board[col + (event.key === "ArrowRight" ? 1 : -1)];
if (!target) {
event.preventDefault();
return;
}
to = { columnId: target.id, index: Math.min(to.index, columnSize(target.id, id)) };
break;
}
case " ":
case "Enter":
event.preventDefault();
moving.current = true;
refocus.current = id;
commit(id, current.from, current.to);
setDrag(null);
setMessage(`Dropped ${title} in ${describe(id, current.to)}.${limitNote(id, current.to)}`);
return;
case "Escape":
event.preventDefault();
moving.current = true;
refocus.current = id;
setDrag(null);
setMessage(`Move cancelled. ${title} returned to ${describe(id, current.from)}.`);
return;
default:
return;
}
event.preventDefault();
if (to.columnId === current.to.columnId && to.index === current.to.index) return;
// The card's node moves or remounts in another column; the layout effect focuses it again.
moving.current = true;
refocus.current = id;
setDrag({ ...current, to });
setMessage(`${title}, ${describe(id, to)}.`);
}
function onCardBlur(id: string) {
const current = dragRef.current;
if (moving.current || current?.mode !== "keyboard" || current.id !== id) return;
// Tabbing or clicking away drops the card where it is.
commit(id, current.from, current.to);
setDrag(null);
setMessage(`Dropped ${titleOf(id)} in ${describe(id, current.to)}.`);
}
function addCard(columnId: string, title: string) {
const card = createCard(title, columnId);
const next = columnsRef.current.map((column) => (column.id === columnId ? { ...column, cards: [...column.cards, card] } : column));
columnsRef.current = next;
onColumnsChange(next);
setMessage(`Added ${title} to ${columnTitle(columnId)}.`);
}
// ---- Render ----
const lifted = drag ? locate(columns, drag.id)?.card : undefined;
const show = (card: Card, state: { lifted: boolean }) => (renderCard ? renderCard(card, state) : <DefaultCard card={card} />);
return (
<div className={cx("relative w-full", className)} {...props}>
<div ref={scroller} className="-mx-1 overflow-x-auto px-1 pb-2 [scrollbar-width:thin]">
<div ref={content} className="relative flex w-max items-start gap-3">
{columns.map((column) => {
const entries: ({ kind: "card"; card: Card; lifted?: boolean } | { kind: "slot" })[] = column.cards
.filter((card) => card.id !== drag?.id)
.map((card) => ({ kind: "card", card }));
const isTarget = drag?.to.columnId === column.id;
if (drag && isTarget && lifted) {
entries.splice(
drag.to.index,
0,
drag.mode === "pointer" ? { kind: "slot" } : { kind: "card", card: lifted, lifted: true },
);
}
const count = entries.length;
const over = column.limit != null && count > column.limit;
const headingId = `${instructionsId}-${column.id}`;
return (
<section
key={column.id}
ref={(el) => {
if (el) lanes.current.set(column.id, el);
else lanes.current.delete(column.id);
}}
aria-labelledby={headingId}
className={cx(
"flex w-[17rem] shrink-0 flex-col rounded-xl p-1.5",
"ring-1 ring-inset transition-[background-color,box-shadow] duration-150 ease-out motion-reduce:transition-none",
// The column under a moving card highlights; amber when the card would push it past its limit.
!isTarget
? "bg-zinc-950/[0.025] ring-transparent dark:bg-white/[0.03]"
: over
? "bg-amber-500/[0.06] ring-amber-500/35"
: "bg-zinc-950/[0.05] ring-zinc-950/15 dark:bg-white/[0.06] dark:ring-white/20",
)}
>
<header className="flex h-9 items-center gap-2 px-2">
<h3 id={headingId} className="min-w-0 truncate text-sm font-medium text-zinc-950 dark:text-white">
{column.title}
</h3>
<span
className={cx(
"font-mono text-xs tabular-nums transition-colors duration-150 motion-reduce:transition-none",
over ? "text-amber-600 dark:text-amber-400" : "text-zinc-500",
)}
>
{column.limit != null ? `${count}/${column.limit}` : count}
<span className="sr-only">
{column.limit != null ? ` cards, limit ${column.limit}` : count === 1 ? " card" : " cards"}
</span>
</span>
{over ? <span className="text-xs text-amber-600 dark:text-amber-400">Over limit</span> : null}
</header>
<ul
ref={(el) => {
if (el) lists.current.set(column.id, el);
else lists.current.delete(column.id);
}}
className="relative grid min-h-16 grid-cols-[minmax(0,1fr)] gap-1.5"
>
{entries.map((entry) => {
if (entry.kind === "slot") {
return (
<motion.li
key="slot"
layout={glideOn && !reduce ? "position" : false}
transition={glide}
aria-hidden="true"
style={{ height: ghost?.height }}
className="rounded-lg border border-dashed border-zinc-950/20 bg-zinc-950/[0.02] dark:border-white/20 dark:bg-white/[0.02]"
/>
);
}
const { card } = entry;
const isLifted = entry.lifted === true;
return (
<motion.li
key={card.id}
ref={(el: HTMLLIElement | null) => {
if (el) cardEls.current.set(card.id, el);
else cardEls.current.delete(card.id);
}}
layout={glideOn && !reduce ? "position" : false}
transition={glide}
className={cx("relative", isLifted && "z-10", settlingId === card.id && "invisible")}
>
<motion.div
ref={(el: HTMLDivElement | null) => {
if (el) cardButtons.current.set(card.id, el);
else cardButtons.current.delete(card.id);
}}
role="button"
tabIndex={0}
aria-roledescription="Movable card"
aria-describedby={instructionsId}
aria-pressed={isLifted}
aria-disabled={disabled || undefined}
onPointerDown={(event) => onCardPointerDown(card.id, event)}
onKeyDown={(event) => onCardKeyDown(card.id, event)}
onBlur={() => onCardBlur(card.id)}
animate={{ scale: isLifted && !reduce ? 1.02 : 1 }}
transition={{ type: "spring", duration: 0.25, bounce: 0 }}
className={cx(cardSurface(isLifted), !disabled && "cursor-grab touch-none", "select-none")}
>
{show(card, { lifted: isLifted })}
</motion.div>
</motion.li>
);
})}
{count === 0 && !drag ? (
<li className="flex min-h-16 items-center justify-center rounded-lg border border-dashed border-zinc-950/10 px-3 text-center text-xs text-zinc-500 dark:border-white/10">
No cards yet
</li>
) : null}
</ul>
{addable && !disabled ? (
addingTo === column.id ? (
<AddCardForm
columnTitle={column.title}
onAdd={(title) => addCard(column.id, title)}
onClose={(returnFocus) => {
if (returnFocus) refocusAdd.current = column.id;
setAddingTo(null);
}}
/>
) : (
<button
type="button"
ref={(el) => {
if (el) addButtons.current.set(column.id, el);
else addButtons.current.delete(column.id);
}}
onClick={() => setAddingTo(column.id)}
className={cx(
"mt-1.5 inline-flex h-8 items-center gap-1.5 rounded-lg px-2 text-sm text-zinc-500",
"transition-colors duration-150 ease-out hover:bg-zinc-950/[0.04] hover:text-zinc-950 motion-reduce:transition-none",
"dark:hover:bg-white/[0.06] dark:hover:text-white",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
)}
>
<svg aria-hidden="true" viewBox="0 0 16 16" className="size-4">
<path d="M8 3.5v9M3.5 8h9" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
Add card<span className="sr-only"> to {column.title}</span>
</button>
)
) : null}
</section>
);
})}
{ghost ? (
<motion.div
aria-hidden="true"
className="pointer-events-none absolute top-0 left-0 z-20"
style={{ x: gx, y: gy, width: ghost.width, rotate: reduce ? 0 : lean }}
>
<motion.div
initial={{ scale: 1 }}
animate={{ scale: settlingId || reduce ? 1 : 1.03 }}
transition={{ type: "spring", duration: 0.25, bounce: 0 }}
className={cardSurface(true)}
>
{show(ghost.card, { lifted: true })}
</motion.div>
</motion.div>
) : null}
</div>
</div>
<p id={instructionsId} hidden>
Press Space or Enter to lift the card. Use the arrow keys to move it, left and right to change column. Press Space or
Enter to drop it, Escape to cancel.
</p>
<span aria-live="assertive" aria-atomic="true" className="sr-only">
{message}
</span>
</div>
);
}
function cardSurface(lifted: boolean) {
return cx(
"relative block rounded-lg border bg-white p-3 text-left text-sm text-zinc-950 dark:bg-black dark:text-white",
"shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
"transition-[border-color] duration-150 ease-out motion-reduce:transition-none",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
// The lift shadow sits on a pseudo-element so only its opacity changes.
"after:pointer-events-none after:absolute after:-inset-px after:rounded-[inherit] after:content-['']",
"after:shadow-[0_16px_36px_-12px_rgb(0_0_0/0.3),0_4px_10px_-4px_rgb(0_0_0/0.12)]",
"dark:after:shadow-[0_20px_44px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.1)]",
"after:transition-opacity after:duration-200 motion-reduce:after:transition-none",
lifted
? "border-zinc-950/15 after:opacity-100 dark:border-white/25"
: "border-zinc-950/10 after:opacity-0 hover:border-zinc-950/20 dark:border-white/10 dark:hover:border-white/20",
);
}
function DefaultCard({ card }: { card: KanbanCardData }) {
return (
<div className="grid gap-1.5">
<p className="leading-5 font-medium">{card.title}</p>
{card.description ? <p className="line-clamp-2 text-xs leading-4 text-zinc-600 dark:text-zinc-400">{card.description}</p> : null}
{card.meta || card.assignee ? (
<div className="mt-1 flex items-center justify-between gap-2">
<span className="font-mono text-xs text-zinc-500">{card.meta}</span>
{card.assignee ? (
<span
title={card.assignee}
className="inline-flex size-5 items-center justify-center rounded-full border border-zinc-950/10 text-[10px] font-medium text-zinc-600 dark:border-white/15 dark:text-zinc-300"
>
<span aria-hidden="true">{initials(card.assignee)}</span>
<span className="sr-only">Assigned to {card.assignee}</span>
</span>
) : null}
</div>
) : null}
</div>
);
}
function AddCardForm({
columnTitle,
onAdd,
onClose,
}: {
columnTitle: string;
onAdd: (title: string) => void;
/** `returnFocus` is true when the person closed the field on purpose (Escape or Cancel). */
onClose: (returnFocus: boolean) => void;
}) {
const [value, setValue] = useState("");
const submit = (event: FormEvent) => {
event.preventDefault();
const title = value.trim();
if (!title) return;
onAdd(title);
setValue("");
};
return (
<form
onSubmit={submit}
onKeyDown={(event) => {
if (event.key === "Escape") {
event.preventDefault();
onClose(true);
}
}}
onBlur={(event) => {
if (!value.trim() && !event.currentTarget.contains(event.relatedTarget as Node | null)) onClose(false);
}}
className="mt-1.5 grid gap-1.5"
>
<input
autoFocus
value={value}
onChange={(event) => setValue(event.target.value)}
aria-label={`New card title in ${columnTitle}`}
placeholder="Card title"
className={cx(
"h-9 w-full rounded-lg border border-zinc-950/15 bg-white px-3 text-sm text-zinc-950 placeholder:text-zinc-500",
"dark:border-white/20 dark:bg-black dark:text-white",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500",
)}
/>
<div className="flex items-center gap-1.5">
<button
type="submit"
className={cx(
"inline-flex h-8 items-center rounded-lg bg-zinc-950 px-3 text-sm font-medium text-white",
"shadow-[inset_0_1px_0_rgb(255_255_255/0.12),0_1px_2px_rgb(0_0_0/0.2)] hover:bg-zinc-800",
"dark:bg-white dark:text-black dark:shadow-[inset_0_-1px_0_rgb(0_0_0/0.12)] dark:hover:bg-zinc-200",
"transition-[background-color,scale] duration-100 ease-out motion-safe:active:scale-[0.97] motion-reduce:transition-none",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
)}
>
Add
</button>
<button
type="button"
onClick={() => onClose(true)}
className={cx(
"inline-flex h-8 items-center rounded-lg px-3 text-sm text-zinc-600 dark:text-zinc-400",
"transition-colors duration-150 ease-out hover:bg-zinc-950/[0.04] hover:text-zinc-950 motion-reduce:transition-none",
"dark:hover:bg-white/[0.06] dark:hover:text-white",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
)}
>
Cancel
</button>
</div>
</form>
);
}