Kanban board
Drag cards across columns, keys too.
Installation
Run the CLI
Run
pnpm dlx asta-ui@latest initonce, then this. The file lands incomponents/astabyte/, installsradix-ui@base-ui/reactand the colour tokens go into your CSS. This is the Radix build. Drop --radix for Base UI.This is the Base UI build, the default. Want Radix? Add --radix.$ pnpm dlx asta-ui@latest add kanban --radixOr install the package
Don’t want the file? Import from
asta-uiasta-ui/baseand update withpnpm update asta-ui. Add the stylesheet once. More.$ pnpm add asta-ui radix-ui @base-ui/reactimport { Kanban } from "asta-ui";import { Kanban } from "asta-ui/base";Or copy it by hand
Install
radix-ui@base-ui/react, then copy these files. Keep the paths, or fix the@/imports. Then add the tokens fromglobals.css."use client"; import { useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type PointerEvent } from "react"; import { Avatar } from "@/components/kit/avatar"; const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); const EASE = "ease-[cubic-bezier(.16,1,.3,1)]"; const CURVE = "cubic-bezier(.16,1,.3,1)"; const GAP = 8; // matches gap-2 on the lists export interface KanbanColumn { id: string; title: string; } export interface KanbanCard { id: string; column: string; title: string; tag?: string; assignee?: string; due?: string; } export interface KanbanProps { columns: KanbanColumn[]; defaultCards: KanbanCard[]; /** Called with the new order after every drop. */ onChange?: (cards: KanbanCard[]) => void; className?: string; } interface ColGeo { id: string; left: number; right: number; top: number; ids: string[]; box: Record<string, { top: number; h: number }>; /** Midpoints of the cards left in this column once the dragged one is lifted, top to bottom. */ mids: number[]; } interface Drag { id: string; from: string; w: number; h: number; ox: number; oy: number; target: { col: string; index: number }; geo: ColGeo[]; dropping?: boolean; } /** First index whose value is greater than v in a sorted array (binary search). */ function upperBound(a: number[], v: number) { let lo = 0; let hi = a.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (a[mid] <= v) lo = mid + 1; else hi = mid; } return lo; } const reduced = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches; /** Put `card` into `col` at `index` (counted among that column's cards). */ function place(cards: KanbanCard[], card: KanbanCard, col: string, index: number) { const rest = cards.filter((c) => c.id !== card.id); const inCol = rest.filter((c) => c.column === col); const before = inCol[index]; const at = before ? rest.indexOf(before) : inCol.length ? rest.indexOf(inCol[inCol.length - 1]) + 1 : rest.length; rest.splice(at, 0, { ...card, column: col }); return rest; } /** How far a card is pushed while something is dragged: up to close the hole it left, down to open the gap. */ function shiftOf(d: Drag, g: ColGeo, id: string) { const D = d.h + GAP; const i = g.ids.indexOf(id); const src = g.id === d.from ? g.ids.indexOf(d.id) : -1; const after = src >= 0 && i > src; const compact = after ? i - 1 : i; return (after ? -D : 0) + (g.id === d.target.col && compact >= d.target.index ? D : 0); } /** Top of the gap in the target column, in list coordinates. */ function gapTop(d: Drag, g: ColGeo) { const D = d.h + GAP; const src = g.id === d.from ? g.ids.indexOf(d.id) : -1; const adj = (id: string) => (src >= 0 && g.ids.indexOf(id) > src ? -D : 0); const compact = g.ids.filter((id) => id !== d.id); if (d.target.index < compact.length) { const id = compact[d.target.index]; return g.box[id].top + adj(id); } const last = compact[compact.length - 1]; return last ? g.box[last].top + adj(last) + g.box[last].h + GAP : 0; } function CardBody({ card }: { card: KanbanCard }) { return ( <> <p className="text-[13.5px] leading-snug text-ink">{card.title}</p> {(card.tag || card.assignee || card.due) && ( <div className="mt-3 flex items-center gap-2 text-[11.5px] text-mute"> {card.tag && <span className="rounded-md bg-paper-2 px-1.5 leading-5">{card.tag}</span>} {card.due && <span className="tabular-nums">{card.due}</span>} {card.assignee && <Avatar name={card.assignee} size="xs" className="ml-auto" />} </div> )} </> ); } const cardCls = "rounded-[10px] bg-paper p-3 shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_9%,transparent),0_1px_2px_rgb(0_0_0/0.04)]"; /** * A board with columns of cards. Drag a card with the pointer and the gap opens where it will land. * With the keyboard: focus a card, press Space to pick it up, arrows to move it, Space to drop and * Escape to cancel. Counts follow along and every move is announced. */ export function Kanban({ columns, defaultCards, onChange, className }: KanbanProps) { const [cards, setCards] = useState(defaultCards); const [drag, setDrag] = useState<Drag | null>(null); const [picked, setPicked] = useState<{ id: string; origin: KanbanCard[] } | null>(null); const [msg, setMsg] = useState(""); const hintId = useId(); const root = useRef<HTMLDivElement>(null); const lists = useRef(new Map<string, HTMLElement>()); const els = useRef(new Map<string, HTMLElement>()); const press = useRef<{ id: string; sx: number; sy: number } | null>(null); const flip = useRef<Map<string, DOMRect> | null>(null); const refocus = useRef<string | null>(null); // Pointer drags: everything is measured once at pick-up and the floating card moves through CSS variables. const floating = useRef<HTMLDivElement>(null); const pos = useRef({ x: 0, y: 0 }); const board = useRef({ left: 0, top: 0 }); const frame = useRef(0); const landing = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); const pickedRef = useRef(picked); useEffect(() => { pickedRef.current = picked; }, [picked]); useEffect( () => () => { clearTimeout(landing.current); cancelAnimationFrame(frame.current); }, [], ); const paint = () => { frame.current = 0; const el = floating.current; if (!el) return; el.style.setProperty("--kx", `${pos.current.x}px`); el.style.setProperty("--ky", `${pos.current.y}px`); }; // Place the floating card before the first paint of a drag, and again when it starts to land. const dragId = drag?.id; const dropping = drag?.dropping; useLayoutEffect(() => { if (dragId) paint(); }, [dragId, dropping]); // The board moves under a still pointer when the page or the board scrolls: re-read it then, not per move. useEffect(() => { if (!dragId) return; const onScroll = () => { const r = root.current?.getBoundingClientRect(); if (r) board.current = { left: r.left, top: r.top }; }; window.addEventListener("scroll", onScroll, { capture: true, passive: true }); return () => window.removeEventListener("scroll", onScroll, { capture: true }); }, [dragId]); const inCol = (list: KanbanCard[], col: string) => list.filter((c) => c.column === col); const titleOf = (col: string) => columns.find((c) => c.id === col)?.title ?? col; const where = (list: KanbanCard[], id: string) => { const card = list.find((c) => c.id === id)!; const col = inCol(list, card.column); return `${titleOf(card.column)}, position ${col.indexOf(card) + 1} of ${col.length}`; }; // FLIP for keyboard moves: cards glide from where they were to where they are now. useLayoutEffect(() => { const from = flip.current; flip.current = null; if (from && !reduced()) { from.forEach((r, id) => { const el = els.current.get(id); if (!el) return; const n = el.getBoundingClientRect(); const dx = r.left - n.left; const dy = r.top - n.top; if (dx || dy) el.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: "none" }], { duration: 340, easing: CURVE }); }); } // Moving to another column re-mounts the card, so put focus back on it. const id = picked?.id ?? refocus.current; refocus.current = null; if (id && document.activeElement !== els.current.get(id)) els.current.get(id)?.focus(); }, [cards, picked]); /* ---------- pointer ---------- */ const start = (e: PointerEvent, card: KanbanCard) => { const b = root.current!.getBoundingClientRect(); board.current = { left: b.left, top: b.top }; const r = els.current.get(card.id)!.getBoundingClientRect(); const D = r.height + GAP; const geo = columns.map((c) => { const lr = lists.current.get(c.id)!.getBoundingClientRect(); const ids = inCol(cards, c.id).map((k) => k.id); const box = Object.fromEntries(ids.map((id) => [id, { top: els.current.get(id)!.offsetTop, h: els.current.get(id)!.offsetHeight }])); // Cards below the lifted one close its hole, so their midpoints move up by one card. const src = c.id === card.column ? ids.indexOf(card.id) : -1; const mids = ids.flatMap((id, i) => (i === src ? [] : [box[id].top + (src >= 0 && i > src ? -D : 0) + box[id].h / 2])); return { id: c.id, left: lr.left - b.left, right: lr.right - b.left, top: lr.top - b.top, ids, box, mids }; }); const index = geo.find((g) => g.id === card.column)!.ids.indexOf(card.id); pos.current = { x: r.left - b.left, y: r.top - b.top }; setDrag({ id: card.id, from: card.column, w: r.width, h: r.height, ox: e.clientX - r.left, oy: e.clientY - r.top, target: { col: card.column, index }, geo, }); }; // Columns sit left to right: find the one under the pointer (or the nearest) by binary search. const columnAt = (geo: ColGeo[], px: number) => { let lo = 0; let hi = geo.length - 1; while (lo < hi) { const mid = (lo + hi) >> 1; if (geo[mid].right < px) lo = mid + 1; else hi = mid; } const g = geo[lo]; if (px >= g.left || lo === 0) return g; const p = geo[lo - 1]; return Math.abs((p.left + p.right) / 2 - px) < Math.abs((g.left + g.right) / 2 - px) ? p : g; }; // Per move: one rAF write for the floating card, and a re-render only when the drop target changes. const move = (e: PointerEvent, d: Drag) => { const x = e.clientX - board.current.left - d.ox; const y = e.clientY - board.current.top - d.oy; pos.current = { x, y }; if (!frame.current) frame.current = requestAnimationFrame(paint); const g = columnAt(d.geo, e.clientX - board.current.left); // Compare the card's centre with the midpoints of the cards left in that column. const index = upperBound(g.mids, y + d.h / 2 - g.top); if (g.id === d.target.col && index === d.target.index) return; setDrag((cur) => (cur && cur.id === d.id && !cur.dropping ? { ...cur, target: { col: g.id, index } } : cur)); }; const commit = (d: Drag) => { const card = cards.find((c) => c.id === d.id)!; const next = place(cards, card, d.target.col, d.target.index); setCards(next); setDrag(null); setMsg(`Dropped ${card.title} in ${where(next, card.id)}.`); onChange?.(next); }; const drop = (d: Drag) => { if (reduced()) return commit(d); const g = d.geo.find((c) => c.id === d.target.col)!; cancelAnimationFrame(frame.current); frame.current = 0; pos.current = { x: g.left, y: g.top + gapTop(d, g) }; setDrag({ ...d, dropping: true }); clearTimeout(landing.current); landing.current = setTimeout(() => commit(d), 260); }; // Put a keyboard pick-up back where it started, like Escape. const cancelPick = (focus: boolean) => { const p = pickedRef.current; if (!p) return; pickedRef.current = null; const card = p.origin.find((c) => c.id === p.id)!; flip.current = new Map([...els.current].map(([id, el]) => [id, el.getBoundingClientRect()])); if (focus) refocus.current = p.id; setCards(p.origin); setPicked(null); setMsg(`Cancelled. ${card.title} is back in ${where(p.origin, p.id)}.`); }; const pointer = { down: (e: PointerEvent<HTMLElement>, card: KanbanCard) => { if (picked) return cancelPick(false); if (e.button !== 0 || drag) return; press.current = { id: card.id, sx: e.clientX, sy: e.clientY }; e.currentTarget.setPointerCapture(e.pointerId); }, move: (e: PointerEvent<HTMLElement>, card: KanbanCard) => { const p = press.current; if (!p || p.id !== card.id) return; if (drag) { if (!drag.dropping) move(e, drag); } else if (Math.hypot(e.clientX - p.sx, e.clientY - p.sy) > 4) start(e, card); }, up: () => { press.current = null; if (drag && !drag.dropping) drop(drag); }, cancel: () => { press.current = null; if (drag && !drag.dropping) setDrag(null); }, }; /* ---------- keyboard ---------- */ const keyMove = (card: KanbanCard, dx: number, dy: number) => { const ci = columns.findIndex((c) => c.id === card.column); const nci = Math.min(columns.length - 1, Math.max(0, ci + dx)); const col = columns[nci].id; const here = inCol(cards, card.column).indexOf(card); const others = inCol(cards, col).filter((c) => c.id !== card.id); const index = dx ? Math.min(here, others.length) : Math.min(others.length, Math.max(0, here + dy)); if (col === card.column && index === here) return; flip.current = new Map([...els.current].map(([id, el]) => [id, el.getBoundingClientRect()])); const next = place(cards, card, col, index); setCards(next); setMsg(`${card.title}: ${where(next, card.id)}.`); }; const onKey = (e: KeyboardEvent, card: KanbanCard) => { const held = picked?.id === card.id; if (e.key === " " || e.key === "Enter") { e.preventDefault(); if (held) { setPicked(null); setMsg(`Dropped ${card.title} in ${where(cards, card.id)}.`); onChange?.(cards); } else if (!picked) { setPicked({ id: card.id, origin: cards }); setMsg(`Picked up ${card.title}. Use the arrow keys to move it, Space to drop, Escape to cancel.`); } return; } if (!held) return; const dir = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[e.key]; if (dir) { e.preventDefault(); keyMove(card, dir[0], dir[1]); } else if (e.key === "Escape") { e.preventDefault(); cancelPick(true); } }; // Focus leaving the held card cancels the pick-up. Moves re-mount or reorder the card and focus // comes back in the layout effect, so check after that has run. const onBlur = (id: string) => { if (pickedRef.current?.id !== id) return; setTimeout(() => { if (pickedRef.current?.id === id && document.activeElement !== els.current.get(id)) cancelPick(false); }); }; const dragged = drag ? cards.find((c) => c.id === drag.id) : undefined; return ( <div className={cx("w-full overflow-x-auto", className)}> <style href="asta-kanban" precedence="asta">{` @keyframes kit-kb-lift { to { transform: rotate(1.5deg) scale(1.03); } } @keyframes kit-kb-land { from { transform: rotate(1.5deg) scale(1.03); } } @keyframes kit-kb-fade { from { opacity: 0; } } @keyframes kit-kb-out { to { opacity: 0; } } @keyframes kit-kb-count { from { opacity: 0; transform: translateY(4px); } } .kit-kb-float { position: relative; animation: kit-kb-lift .22s ${CURVE} both; } .kit-kb-float::after { content: ""; position: absolute; inset: 0; border-radius: inherit; pointer-events: none; box-shadow: 0 18px 36px -14px rgb(0 0 0 / .28); animation: kit-kb-fade .22s ${CURVE} both; } .kit-kb-float[data-dropping] { animation: kit-kb-land .26s ${CURVE} both; } .kit-kb-float[data-dropping]::after { animation: kit-kb-out .26s ${CURVE} both; } @media (prefers-reduced-motion: reduce) { .kit-kb, .kit-kb * { animation: none !important; transition-duration: 0s !important; } .kit-kb-float::after { opacity: 0; } } `}</style> <p id={hintId} className="sr-only"> Press Space to pick up a card. Use the arrow keys to move it, Space to drop, Escape to cancel. </p> <p className="sr-only" aria-live="polite"> {msg} </p> <div ref={root} className="kit-kb relative grid min-w-[620px] gap-3" style={{ gridTemplateColumns: `repeat(${columns.length}, minmax(0, 1fr))` }}> {columns.map((col) => { const list = inCol(cards, col.id); const g = drag?.geo.find((c) => c.id === col.id); const count = list.length - (drag?.from === col.id ? 1 : 0) + (drag?.target.col === col.id ? 1 : 0); return ( <section key={col.id} aria-label={col.title} className="flex min-h-[340px] flex-col rounded-xl bg-paper-2 p-2"> <header className="flex items-center gap-2 px-1.5 pb-2.5 pt-1"> <h4 className="text-[13px] font-medium text-ink">{col.title}</h4> <span key={count} className="text-[12px] tabular-nums text-mute" style={{ animation: `kit-kb-count .4s ${CURVE}` }}> {count} </span> </header> <ul ref={(el) => { if (el) lists.current.set(col.id, el); }} className="relative flex flex-1 flex-col gap-2" > {drag && g && drag.target.col === col.id && ( <li key={`gap-${col.id}`} aria-hidden className={cx( "pointer-events-none absolute inset-x-0 top-0 rounded-[10px] bg-[color-mix(in_srgb,var(--color-brand)_5%,transparent)] shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-brand)_28%,transparent)] transition-transform duration-300", EASE, )} style={{ height: drag.h, transform: `translateY(${gapTop(drag, g)}px)`, animation: `kit-kb-fade .25s ${CURVE}` }} /> )} {list.map((card) => { const held = picked?.id === card.id; const hidden = drag?.id === card.id; const dy = drag && g ? shiftOf(drag, g, card.id) : 0; return ( <li key={card.id} ref={(el) => { if (!el) return; els.current.set(card.id, el); return () => { if (els.current.get(card.id) === el) els.current.delete(card.id); }; }} tabIndex={0} aria-roledescription="draggable card" aria-describedby={hintId} data-picked={held || undefined} onPointerDown={(e) => pointer.down(e, card)} onPointerMove={(e) => pointer.move(e, card)} onPointerUp={pointer.up} onPointerCancel={pointer.cancel} onKeyDown={(e) => onKey(e, card)} onBlur={() => onBlur(card.id)} className={cx( cardCls, "relative cursor-grab touch-none select-none outline-none focus-visible:ring-2 focus-visible:ring-brand/50", drag && "transition-transform duration-300", EASE, hidden && "opacity-0", held && "z-10 scale-[1.02] !shadow-[inset_0_0_0_1.5px_var(--color-brand),0_14px_30px_-14px_rgb(0_0_0/0.3)] transition-[scale,box-shadow] duration-300", )} style={dy ? { transform: `translateY(${dy}px)` } : undefined} > <CardBody card={card} /> </li> ); })} </ul> </section> ); })} {/* The card under the pointer. */} {drag && dragged && ( <div ref={floating} aria-hidden className="pointer-events-none absolute left-0 top-0 z-30" style={{ width: drag.w, transform: "translate3d(var(--kx, 0px), var(--ky, 0px), 0)", transition: drag.dropping ? `transform .26s ${CURVE}` : "none", }} > <div className={cx(cardCls, "kit-kb-float cursor-grabbing")} data-dropping={drag.dropping || undefined}> <CardBody card={dragged} /> </div> </div> )} </div> </div> ); } export default Kanban;"use client"; import { useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type PointerEvent } from "react"; import { Avatar } from "@/components/kit/base/avatar"; const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); const EASE = "ease-[cubic-bezier(.16,1,.3,1)]"; const CURVE = "cubic-bezier(.16,1,.3,1)"; const GAP = 8; // matches gap-2 on the lists export interface KanbanColumn { id: string; title: string; } export interface KanbanCard { id: string; column: string; title: string; tag?: string; assignee?: string; due?: string; } export interface KanbanProps { columns: KanbanColumn[]; defaultCards: KanbanCard[]; /** Called with the new order after every drop. */ onChange?: (cards: KanbanCard[]) => void; className?: string; } interface ColGeo { id: string; left: number; right: number; top: number; ids: string[]; box: Record<string, { top: number; h: number }>; /** Midpoints of the cards left in this column once the dragged one is lifted, top to bottom. */ mids: number[]; } interface Drag { id: string; from: string; w: number; h: number; ox: number; oy: number; target: { col: string; index: number }; geo: ColGeo[]; dropping?: boolean; } /** First index whose value is greater than v in a sorted array (binary search). */ function upperBound(a: number[], v: number) { let lo = 0; let hi = a.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (a[mid] <= v) lo = mid + 1; else hi = mid; } return lo; } const reduced = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches; /** Put `card` into `col` at `index` (counted among that column's cards). */ function place(cards: KanbanCard[], card: KanbanCard, col: string, index: number) { const rest = cards.filter((c) => c.id !== card.id); const inCol = rest.filter((c) => c.column === col); const before = inCol[index]; const at = before ? rest.indexOf(before) : inCol.length ? rest.indexOf(inCol[inCol.length - 1]) + 1 : rest.length; rest.splice(at, 0, { ...card, column: col }); return rest; } /** How far a card is pushed while something is dragged: up to close the hole it left, down to open the gap. */ function shiftOf(d: Drag, g: ColGeo, id: string) { const D = d.h + GAP; const i = g.ids.indexOf(id); const src = g.id === d.from ? g.ids.indexOf(d.id) : -1; const after = src >= 0 && i > src; const compact = after ? i - 1 : i; return (after ? -D : 0) + (g.id === d.target.col && compact >= d.target.index ? D : 0); } /** Top of the gap in the target column, in list coordinates. */ function gapTop(d: Drag, g: ColGeo) { const D = d.h + GAP; const src = g.id === d.from ? g.ids.indexOf(d.id) : -1; const adj = (id: string) => (src >= 0 && g.ids.indexOf(id) > src ? -D : 0); const compact = g.ids.filter((id) => id !== d.id); if (d.target.index < compact.length) { const id = compact[d.target.index]; return g.box[id].top + adj(id); } const last = compact[compact.length - 1]; return last ? g.box[last].top + adj(last) + g.box[last].h + GAP : 0; } function CardBody({ card }: { card: KanbanCard }) { return ( <> <p className="text-[13.5px] leading-snug text-ink">{card.title}</p> {(card.tag || card.assignee || card.due) && ( <div className="mt-3 flex items-center gap-2 text-[11.5px] text-mute"> {card.tag && <span className="rounded-md bg-paper-2 px-1.5 leading-5">{card.tag}</span>} {card.due && <span className="tabular-nums">{card.due}</span>} {card.assignee && <Avatar name={card.assignee} size="xs" className="ml-auto" />} </div> )} </> ); } const cardCls = "rounded-[10px] bg-paper p-3 shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_9%,transparent),0_1px_2px_rgb(0_0_0/0.04)]"; /** * A board with columns of cards. Drag a card with the pointer and the gap opens where it will land. * With the keyboard: focus a card, press Space to pick it up, arrows to move it, Space to drop and * Escape to cancel. Counts follow along and every move is announced. */ export function Kanban({ columns, defaultCards, onChange, className }: KanbanProps) { const [cards, setCards] = useState(defaultCards); const [drag, setDrag] = useState<Drag | null>(null); const [picked, setPicked] = useState<{ id: string; origin: KanbanCard[] } | null>(null); const [msg, setMsg] = useState(""); const hintId = useId(); const root = useRef<HTMLDivElement>(null); const lists = useRef(new Map<string, HTMLElement>()); const els = useRef(new Map<string, HTMLElement>()); const press = useRef<{ id: string; sx: number; sy: number } | null>(null); const flip = useRef<Map<string, DOMRect> | null>(null); const refocus = useRef<string | null>(null); // Pointer drags: everything is measured once at pick-up and the floating card moves through CSS variables. const floating = useRef<HTMLDivElement>(null); const pos = useRef({ x: 0, y: 0 }); const board = useRef({ left: 0, top: 0 }); const frame = useRef(0); const landing = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); const pickedRef = useRef(picked); useEffect(() => { pickedRef.current = picked; }, [picked]); useEffect( () => () => { clearTimeout(landing.current); cancelAnimationFrame(frame.current); }, [], ); const paint = () => { frame.current = 0; const el = floating.current; if (!el) return; el.style.setProperty("--kx", `${pos.current.x}px`); el.style.setProperty("--ky", `${pos.current.y}px`); }; // Place the floating card before the first paint of a drag, and again when it starts to land. const dragId = drag?.id; const dropping = drag?.dropping; useLayoutEffect(() => { if (dragId) paint(); }, [dragId, dropping]); // The board moves under a still pointer when the page or the board scrolls: re-read it then, not per move. useEffect(() => { if (!dragId) return; const onScroll = () => { const r = root.current?.getBoundingClientRect(); if (r) board.current = { left: r.left, top: r.top }; }; window.addEventListener("scroll", onScroll, { capture: true, passive: true }); return () => window.removeEventListener("scroll", onScroll, { capture: true }); }, [dragId]); const inCol = (list: KanbanCard[], col: string) => list.filter((c) => c.column === col); const titleOf = (col: string) => columns.find((c) => c.id === col)?.title ?? col; const where = (list: KanbanCard[], id: string) => { const card = list.find((c) => c.id === id)!; const col = inCol(list, card.column); return `${titleOf(card.column)}, position ${col.indexOf(card) + 1} of ${col.length}`; }; // FLIP for keyboard moves: cards glide from where they were to where they are now. useLayoutEffect(() => { const from = flip.current; flip.current = null; if (from && !reduced()) { from.forEach((r, id) => { const el = els.current.get(id); if (!el) return; const n = el.getBoundingClientRect(); const dx = r.left - n.left; const dy = r.top - n.top; if (dx || dy) el.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: "none" }], { duration: 340, easing: CURVE }); }); } // Moving to another column re-mounts the card, so put focus back on it. const id = picked?.id ?? refocus.current; refocus.current = null; if (id && document.activeElement !== els.current.get(id)) els.current.get(id)?.focus(); }, [cards, picked]); /* ---------- pointer ---------- */ const start = (e: PointerEvent, card: KanbanCard) => { const b = root.current!.getBoundingClientRect(); board.current = { left: b.left, top: b.top }; const r = els.current.get(card.id)!.getBoundingClientRect(); const D = r.height + GAP; const geo = columns.map((c) => { const lr = lists.current.get(c.id)!.getBoundingClientRect(); const ids = inCol(cards, c.id).map((k) => k.id); const box = Object.fromEntries(ids.map((id) => [id, { top: els.current.get(id)!.offsetTop, h: els.current.get(id)!.offsetHeight }])); // Cards below the lifted one close its hole, so their midpoints move up by one card. const src = c.id === card.column ? ids.indexOf(card.id) : -1; const mids = ids.flatMap((id, i) => (i === src ? [] : [box[id].top + (src >= 0 && i > src ? -D : 0) + box[id].h / 2])); return { id: c.id, left: lr.left - b.left, right: lr.right - b.left, top: lr.top - b.top, ids, box, mids }; }); const index = geo.find((g) => g.id === card.column)!.ids.indexOf(card.id); pos.current = { x: r.left - b.left, y: r.top - b.top }; setDrag({ id: card.id, from: card.column, w: r.width, h: r.height, ox: e.clientX - r.left, oy: e.clientY - r.top, target: { col: card.column, index }, geo, }); }; // Columns sit left to right: find the one under the pointer (or the nearest) by binary search. const columnAt = (geo: ColGeo[], px: number) => { let lo = 0; let hi = geo.length - 1; while (lo < hi) { const mid = (lo + hi) >> 1; if (geo[mid].right < px) lo = mid + 1; else hi = mid; } const g = geo[lo]; if (px >= g.left || lo === 0) return g; const p = geo[lo - 1]; return Math.abs((p.left + p.right) / 2 - px) < Math.abs((g.left + g.right) / 2 - px) ? p : g; }; // Per move: one rAF write for the floating card, and a re-render only when the drop target changes. const move = (e: PointerEvent, d: Drag) => { const x = e.clientX - board.current.left - d.ox; const y = e.clientY - board.current.top - d.oy; pos.current = { x, y }; if (!frame.current) frame.current = requestAnimationFrame(paint); const g = columnAt(d.geo, e.clientX - board.current.left); // Compare the card's centre with the midpoints of the cards left in that column. const index = upperBound(g.mids, y + d.h / 2 - g.top); if (g.id === d.target.col && index === d.target.index) return; setDrag((cur) => (cur && cur.id === d.id && !cur.dropping ? { ...cur, target: { col: g.id, index } } : cur)); }; const commit = (d: Drag) => { const card = cards.find((c) => c.id === d.id)!; const next = place(cards, card, d.target.col, d.target.index); setCards(next); setDrag(null); setMsg(`Dropped ${card.title} in ${where(next, card.id)}.`); onChange?.(next); }; const drop = (d: Drag) => { if (reduced()) return commit(d); const g = d.geo.find((c) => c.id === d.target.col)!; cancelAnimationFrame(frame.current); frame.current = 0; pos.current = { x: g.left, y: g.top + gapTop(d, g) }; setDrag({ ...d, dropping: true }); clearTimeout(landing.current); landing.current = setTimeout(() => commit(d), 260); }; // Put a keyboard pick-up back where it started, like Escape. const cancelPick = (focus: boolean) => { const p = pickedRef.current; if (!p) return; pickedRef.current = null; const card = p.origin.find((c) => c.id === p.id)!; flip.current = new Map([...els.current].map(([id, el]) => [id, el.getBoundingClientRect()])); if (focus) refocus.current = p.id; setCards(p.origin); setPicked(null); setMsg(`Cancelled. ${card.title} is back in ${where(p.origin, p.id)}.`); }; const pointer = { down: (e: PointerEvent<HTMLElement>, card: KanbanCard) => { if (picked) return cancelPick(false); if (e.button !== 0 || drag) return; press.current = { id: card.id, sx: e.clientX, sy: e.clientY }; e.currentTarget.setPointerCapture(e.pointerId); }, move: (e: PointerEvent<HTMLElement>, card: KanbanCard) => { const p = press.current; if (!p || p.id !== card.id) return; if (drag) { if (!drag.dropping) move(e, drag); } else if (Math.hypot(e.clientX - p.sx, e.clientY - p.sy) > 4) start(e, card); }, up: () => { press.current = null; if (drag && !drag.dropping) drop(drag); }, cancel: () => { press.current = null; if (drag && !drag.dropping) setDrag(null); }, }; /* ---------- keyboard ---------- */ const keyMove = (card: KanbanCard, dx: number, dy: number) => { const ci = columns.findIndex((c) => c.id === card.column); const nci = Math.min(columns.length - 1, Math.max(0, ci + dx)); const col = columns[nci].id; const here = inCol(cards, card.column).indexOf(card); const others = inCol(cards, col).filter((c) => c.id !== card.id); const index = dx ? Math.min(here, others.length) : Math.min(others.length, Math.max(0, here + dy)); if (col === card.column && index === here) return; flip.current = new Map([...els.current].map(([id, el]) => [id, el.getBoundingClientRect()])); const next = place(cards, card, col, index); setCards(next); setMsg(`${card.title}: ${where(next, card.id)}.`); }; const onKey = (e: KeyboardEvent, card: KanbanCard) => { const held = picked?.id === card.id; if (e.key === " " || e.key === "Enter") { e.preventDefault(); if (held) { setPicked(null); setMsg(`Dropped ${card.title} in ${where(cards, card.id)}.`); onChange?.(cards); } else if (!picked) { setPicked({ id: card.id, origin: cards }); setMsg(`Picked up ${card.title}. Use the arrow keys to move it, Space to drop, Escape to cancel.`); } return; } if (!held) return; const dir = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[e.key]; if (dir) { e.preventDefault(); keyMove(card, dir[0], dir[1]); } else if (e.key === "Escape") { e.preventDefault(); cancelPick(true); } }; // Focus leaving the held card cancels the pick-up. Moves re-mount or reorder the card and focus // comes back in the layout effect, so check after that has run. const onBlur = (id: string) => { if (pickedRef.current?.id !== id) return; setTimeout(() => { if (pickedRef.current?.id === id && document.activeElement !== els.current.get(id)) cancelPick(false); }); }; const dragged = drag ? cards.find((c) => c.id === drag.id) : undefined; return ( <div className={cx("w-full overflow-x-auto", className)}> <style href="asta-kanban" precedence="asta">{` @keyframes kit-kb-lift { to { transform: rotate(1.5deg) scale(1.03); } } @keyframes kit-kb-land { from { transform: rotate(1.5deg) scale(1.03); } } @keyframes kit-kb-fade { from { opacity: 0; } } @keyframes kit-kb-out { to { opacity: 0; } } @keyframes kit-kb-count { from { opacity: 0; transform: translateY(4px); } } .kit-kb-float { position: relative; animation: kit-kb-lift .22s ${CURVE} both; } .kit-kb-float::after { content: ""; position: absolute; inset: 0; border-radius: inherit; pointer-events: none; box-shadow: 0 18px 36px -14px rgb(0 0 0 / .28); animation: kit-kb-fade .22s ${CURVE} both; } .kit-kb-float[data-dropping] { animation: kit-kb-land .26s ${CURVE} both; } .kit-kb-float[data-dropping]::after { animation: kit-kb-out .26s ${CURVE} both; } @media (prefers-reduced-motion: reduce) { .kit-kb, .kit-kb * { animation: none !important; transition-duration: 0s !important; } .kit-kb-float::after { opacity: 0; } } `}</style> <p id={hintId} className="sr-only"> Press Space to pick up a card. Use the arrow keys to move it, Space to drop, Escape to cancel. </p> <p className="sr-only" aria-live="polite"> {msg} </p> <div ref={root} className="kit-kb relative grid min-w-[620px] gap-3" style={{ gridTemplateColumns: `repeat(${columns.length}, minmax(0, 1fr))` }}> {columns.map((col) => { const list = inCol(cards, col.id); const g = drag?.geo.find((c) => c.id === col.id); const count = list.length - (drag?.from === col.id ? 1 : 0) + (drag?.target.col === col.id ? 1 : 0); return ( <section key={col.id} aria-label={col.title} className="flex min-h-[340px] flex-col rounded-xl bg-paper-2 p-2"> <header className="flex items-center gap-2 px-1.5 pb-2.5 pt-1"> <h4 className="text-[13px] font-medium text-ink">{col.title}</h4> <span key={count} className="text-[12px] tabular-nums text-mute" style={{ animation: `kit-kb-count .4s ${CURVE}` }}> {count} </span> </header> <ul ref={(el) => { if (el) lists.current.set(col.id, el); }} className="relative flex flex-1 flex-col gap-2" > {drag && g && drag.target.col === col.id && ( <li key={`gap-${col.id}`} aria-hidden className={cx( "pointer-events-none absolute inset-x-0 top-0 rounded-[10px] bg-[color-mix(in_srgb,var(--color-brand)_5%,transparent)] shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-brand)_28%,transparent)] transition-transform duration-300", EASE, )} style={{ height: drag.h, transform: `translateY(${gapTop(drag, g)}px)`, animation: `kit-kb-fade .25s ${CURVE}` }} /> )} {list.map((card) => { const held = picked?.id === card.id; const hidden = drag?.id === card.id; const dy = drag && g ? shiftOf(drag, g, card.id) : 0; return ( <li key={card.id} ref={(el) => { if (!el) return; els.current.set(card.id, el); return () => { if (els.current.get(card.id) === el) els.current.delete(card.id); }; }} tabIndex={0} aria-roledescription="draggable card" aria-describedby={hintId} data-picked={held || undefined} onPointerDown={(e) => pointer.down(e, card)} onPointerMove={(e) => pointer.move(e, card)} onPointerUp={pointer.up} onPointerCancel={pointer.cancel} onKeyDown={(e) => onKey(e, card)} onBlur={() => onBlur(card.id)} className={cx( cardCls, "relative cursor-grab touch-none select-none outline-none focus-visible:ring-2 focus-visible:ring-brand/50", drag && "transition-transform duration-300", EASE, hidden && "opacity-0", held && "z-10 scale-[1.02] !shadow-[inset_0_0_0_1.5px_var(--color-brand),0_14px_30px_-14px_rgb(0_0_0/0.3)] transition-[scale,box-shadow] duration-300", )} style={dy ? { transform: `translateY(${dy}px)` } : undefined} > <CardBody card={card} /> </li> ); })} </ul> </section> ); })} {/* The card under the pointer. */} {drag && dragged && ( <div ref={floating} aria-hidden className="pointer-events-none absolute left-0 top-0 z-30" style={{ width: drag.w, transform: "translate3d(var(--kx, 0px), var(--ky, 0px), 0)", transition: drag.dropping ? `transform .26s ${CURVE}` : "none", }} > <div className={cx(cardCls, "kit-kb-float cursor-grabbing")} data-dropping={drag.dropping || undefined}> <CardBody card={dragged} /> </div> </div> )} </div> </div> ); } export default Kanban;Or ask your AI agent
Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.
Add the Astabyte UI Kanban board component to my project. Drag cards across columns, keys too. It includes: drag, keyboard, placeholder, counts, announcements. Install it (Radix build): ```sh pnpm dlx asta-ui@latest add kanban --radix ``` Or with the shadcn CLI: ```sh pnpm dlx shadcn@latest add https://ui.astabyte.com/r/kanban.json ``` If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4). Import it like this: ```tsx import { Kanban, type KanbanCard } from "@/components/astabyte/kanban"; ``` Usage example and props: https://ui.astabyte.com/kanban Full catalogue for context: https://ui.astabyte.com/llms.txt Rules: - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS. - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback. - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Radix primitives from the radix-ui package). - Stay on Radix: install other Astabyte UI components with `--radix` so the project uses one primitive library. - Use fake data and fake brand names in examples. Use it to: [describe where it goes and what it should do]Add the Astabyte UI Kanban board component to my project. Drag cards across columns, keys too. It includes: drag, keyboard, placeholder, counts, announcements. Install it (Base UI build): ```sh pnpm dlx asta-ui@latest add kanban ``` Or with the shadcn CLI: ```sh pnpm dlx shadcn@latest add https://ui.astabyte.com/r/base/kanban.json ``` If the project isn't set up yet, run `pnpm dlx asta-ui@latest init` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4). Import it like this: ```tsx import { Kanban, type KanbanCard } from "@/components/astabyte/kanban"; ``` Usage example and props: https://ui.astabyte.com/kanban Full catalogue for context: https://ui.astabyte.com/llms.txt Rules: - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS. - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback. - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Base UI primitives from the @base-ui/react package). - Stay on Base UI: install other Astabyte UI components without `--radix` so the project uses one primitive library. - Use fake data and fake brand names in examples. Use it to: [describe where it goes and what it should do]Or use plain HTML + CSS
Not on React? Use it from Django, Rails, Laravel, Go
html/template, htmx or a static page. Loadasta.cssandasta.jsonce (thehead.htmltab), then paste the markup. Theui.astabyte.com/cdnlink is temporary: pin a version from jsDelivr for production. More in HTML + CSS.<!-- Needs asta.js for drag and drop and keyboard moves. Saving a move needs a server endpoint (the form posts card, column, position). --> <form class="asta-kanban asta-kanban-root" data-asta-kanban id="board" aria-label="Sprint board"><input type="hidden" name="card" value="" data-asta-kanban-field="card"><input type="hidden" name="column" value="" data-asta-kanban-field="column"><input type="hidden" name="position" value="" data-asta-kanban-field="position"><p class="asta-sr-only" id="board-hint">Press Space to pick up a card. Use the arrow keys to move it, Space to drop, Escape to cancel.</p><p class="asta-sr-only" aria-live="polite" data-asta-kanban-status></p><div class="asta-kanban-grid" style="--cols:3"> <section class="asta-kanban-col" aria-label="To do" data-asta-kanban-col="todo"><header class="asta-kanban-head"><h4 class="asta-kanban-title">To do</h4><span class="asta-kanban-count" data-asta-kanban-count>3</span></header><ul class="asta-kanban-list" data-asta-kanban-list> <li class="asta-kanban-card" data-asta-kanban-card="k1" data-title="Write the pricing page copy" draggable="true" tabindex="0" aria-roledescription="draggable card" aria-describedby="board-hint"><p class="asta-kanban-card-title">Write the pricing page copy</p><div class="asta-kanban-meta"><span class="asta-kanban-tag">Copy</span><span class="asta-kanban-due">Nov 24</span><span class="asta-avatar asta-avatar-xs asta-kanban-assignee" role="img" aria-label="Maya Chen"><span class="asta-avatar-face asta-avatar-soft">MC</span></span></div></li> <li class="asta-kanban-card" data-asta-kanban-card="k2" data-title="Audit image sizes" draggable="true" tabindex="0" aria-roledescription="draggable card" aria-describedby="board-hint"><p class="asta-kanban-card-title">Audit image sizes</p><div class="asta-kanban-meta"><span class="asta-kanban-tag">Perf</span><span class="asta-avatar asta-avatar-xs asta-kanban-assignee" role="img" aria-label="Leo Park"><span class="asta-avatar-face asta-avatar-soft">LP</span></span></div></li> <li class="asta-kanban-card" data-asta-kanban-card="k3" data-title="Dark mode for charts" draggable="true" tabindex="0" aria-roledescription="draggable card" aria-describedby="board-hint"><p class="asta-kanban-card-title">Dark mode for charts</p><div class="asta-kanban-meta"><span class="asta-kanban-tag">Design</span><span class="asta-kanban-due">Nov 28</span><span class="asta-avatar asta-avatar-xs asta-kanban-assignee" role="img" aria-label="Ana Ruiz"><span class="asta-avatar-face asta-avatar-soft">AR</span></span></div></li> </ul></section> <section class="asta-kanban-col" aria-label="In progress" data-asta-kanban-col="doing"><header class="asta-kanban-head"><h4 class="asta-kanban-title">In progress</h4><span class="asta-kanban-count" data-asta-kanban-count>2</span></header><ul class="asta-kanban-list" data-asta-kanban-list> <li class="asta-kanban-card" data-asta-kanban-card="k4" data-title="Checkout flow in htmx" draggable="true" tabindex="0" aria-roledescription="draggable card" aria-describedby="board-hint"><p class="asta-kanban-card-title">Checkout flow in htmx</p><div class="asta-kanban-meta"><span class="asta-kanban-tag">Build</span><span class="asta-kanban-due">Nov 21</span><span class="asta-avatar asta-avatar-xs asta-kanban-assignee" role="img" aria-label="Sam Lee"><span class="asta-avatar-face asta-avatar-soft">SL</span></span></div></li> <li class="asta-kanban-card" data-asta-kanban-card="k5" data-title="Onboarding emails" draggable="true" tabindex="0" aria-roledescription="draggable card" aria-describedby="board-hint"><p class="asta-kanban-card-title">Onboarding emails</p><div class="asta-kanban-meta"><span class="asta-kanban-tag">Copy</span><span class="asta-avatar asta-avatar-xs asta-kanban-assignee" role="img" aria-label="Maya Chen"><span class="asta-avatar-face asta-avatar-soft">MC</span></span></div></li> </ul></section> <section class="asta-kanban-col" aria-label="Done" data-asta-kanban-col="done"><header class="asta-kanban-head"><h4 class="asta-kanban-title">Done</h4><span class="asta-kanban-count" data-asta-kanban-count>2</span></header><ul class="asta-kanban-list" data-asta-kanban-list> <li class="asta-kanban-card" data-asta-kanban-card="k6" data-title="Set up the design tokens" draggable="true" tabindex="0" aria-roledescription="draggable card" aria-describedby="board-hint"><p class="asta-kanban-card-title">Set up the design tokens</p><div class="asta-kanban-meta"><span class="asta-kanban-tag">Design</span><span class="asta-avatar asta-avatar-xs asta-kanban-assignee" role="img" aria-label="Ana Ruiz"><span class="asta-avatar-face asta-avatar-soft">AR</span></span></div></li> <li class="asta-kanban-card" data-asta-kanban-card="k7" data-title="Deploy preview builds" draggable="true" tabindex="0" aria-roledescription="draggable card" aria-describedby="board-hint"><p class="asta-kanban-card-title">Deploy preview builds</p><div class="asta-kanban-meta"><span class="asta-kanban-tag">Ops</span><span class="asta-avatar asta-avatar-xs asta-kanban-assignee" role="img" aria-label="Leo Park"><span class="asta-avatar-face asta-avatar-soft">LP</span></span></div></li> </ul></section> </div></form>
Usage
The demo above, as code.
"use client";
import { Kanban, type KanbanCard } from "@/components/astabyte/kanban";
const COLUMNS = [
{ id: "todo", title: "To do" },
{ id: "doing", title: "In progress" },
{ id: "done", title: "Done" },
];
const CARDS: KanbanCard[] = [
{ id: "c1", column: "todo", title: "Write the onboarding email", tag: "Growth", assignee: "Rani Pratama", due: "Nov 21" },
{ id: "c2", column: "todo", title: "Audit empty states", tag: "Design", assignee: "Dimas Arya" },
{ id: "c3", column: "todo", title: "Rate limit the export endpoint", tag: "API", due: "Nov 24" },
{ id: "c4", column: "doing", title: "New pricing page", tag: "Web", assignee: "Sekar Ayu", due: "Nov 20" },
{ id: "c5", column: "doing", title: "Invoice PDF layout", tag: "Billing", assignee: "Rani Pratama" },
{ id: "c6", column: "done", title: "Move search to the command palette", tag: "Web", assignee: "Dimas Arya" },
];
export default function KanbanDemo() {
return (
<div className="flex min-h-[420px] w-full flex-col items-center justify-center gap-3 p-4 sm:p-8">
<div className="w-full max-w-[860px]">
<Kanban columns={COLUMNS} defaultCards={CARDS} />
</div>
<p className="text-[12.5px] text-mute">Drag a card, or focus one and press Space, then the arrow keys.</p>
</div>
);
}