import React, { useCallback, useMemo, useRef, useState } from 'react'; import { GripVertical } from 'lucide-react'; import { cn } from '../../shared/utils'; import { useTokenColors } from '../../shared/token-color'; import type { ColorToken } from '../../shared/color-token'; import { Badge } from '../badge'; import { Avatar, AvatarFallback, AvatarImage } from '../avatar'; import { isAtLimit, isOverLimit } from './kanban-model'; import { useKanbanDnd, type DragState } from './use-kanban-dnd'; import type { KanbanCard, KanbanColumn, KanbanMove, WipLimitBehavior } from './kanban.types'; export interface KanbanProps extends Omit, 'onSelect'> { columns: KanbanColumn[]; /** * Fires with the requested move. The board is controlled: apply it with * `applyMove` and hand the new columns back. */ onMove?: (move: KanbanMove) => void; /** Fires when a card is opened — click without a drag, or Enter on a resting card. */ onCardActivate?: (cardId: string, card: KanbanCard) => void; /** Highlights a card, for pairing with a detail panel. */ selectedCardId?: string | null; onSelect?: (cardId: string | null) => void; /** Replaces the whole card body. */ renderCard?: (card: KanbanCard, column: KanbanColumn) => React.ReactNode; renderColumnHeader?: (column: KanbanColumn) => React.ReactNode; /** * What a drop past a column's WIP limit does. * `'warn'` marks the column and lets it through; `'block'` refuses. * @default 'warn' */ wipLimitBehavior?: WipLimitBehavior; /** @default '20rem' */ columnWidth?: string; /** @default '32rem' */ height?: string; /** Turns off dragging entirely, leaving a readable board. */ readOnly?: boolean; /** @default "Board" */ ariaLabel?: string; /** @default "No cards" */ emptyColumnLabel?: string; /** Accessible strings, in English by library convention. */ labels?: Partial; } export interface KanbanLabels { grabbed: (title: string, column: string, position: number, total: number) => string; moved: (title: string, column: string, position: number, total: number) => string; dropped: (title: string, column: string, position: number) => string; cancelled: (title: string) => string; blocked: (reason: 'locked-card' | 'locked-column' | 'wip-limit') => string; dragHandle: (title: string) => string; wipLimit: (count: number, limit: number) => string; } const DEFAULT_LABELS: KanbanLabels = { grabbed: (title, column, position, total) => `${title} grabbed. Position ${position} of ${total} in ${column}. Use the arrow keys to move, Space to drop, Escape to cancel.`, moved: (title, column, position, total) => `${title} moved to position ${position} of ${total} in ${column}.`, dropped: (title, column, position) => `${title} dropped in ${column} at position ${position}.`, cancelled: title => `${title} returned to its original position.`, blocked: reason => reason === 'wip-limit' ? 'Cannot drop here: the column is at its work-in-progress limit.' : reason === 'locked-column' ? 'Cannot drop here: the column is locked.' : 'This card cannot be moved.', dragHandle: title => `Move ${title}`, wipLimit: (count, limit) => `${count} of ${limit} cards, work-in-progress limit`, }; const COLUMN_TOKENS: ColorToken[] = [ '--chart-1', '--chart-2', '--chart-3', '--chart-4', '--chart-5', ]; const BADGE_TOKENS: ColorToken[] = [...COLUMN_TOKENS, '--primary', '--destructive']; /** * Board with columns of draggable cards. * * @description * Controlled: the board reports a move and the consumer applies it, so ordering * lives with the data rather than inside a widget. `applyMove` is exported for * exactly that, and is pure. * * Dragging works by pointer **and** by keyboard, through one state machine. * That is why it does not use HTML5 drag-and-drop, which cannot be driven from * the keyboard at all — the accessible half would have had to be a separate, * lesser imitation. * * Work-in-progress limits are first-class, because capping work in progress is * what Kanban is for. * * @ai-rules * 1. Apply the move yourself: `onMove={m => setColumns(applyMove(columns, m))}`. Nothing happens otherwise. * 2. Set `limit` on columns that have one. A board with no WIP limits is a list of lists. * 3. Keep card ids stable — drag, selection and announcements all key off them. * 4. Never wrap the card in your own drag handlers; use `renderCard` for content only. */ export const Kanban = React.forwardRef( ( { columns, onMove, onCardActivate, selectedCardId, onSelect, renderCard, renderColumnHeader, wipLimitBehavior = 'warn', columnWidth = '20rem', height = '32rem', readOnly = false, ariaLabel = 'Board', emptyColumnLabel = 'No cards', labels, className, ...divProps }, ref ) => { const resolvedLabels = useMemo(() => ({ ...DEFAULT_LABELS, ...labels }), [labels]); const [announcement, setAnnouncement] = useState(''); const announce = useCallback((message: string) => setAnnouncement(message), []); const handleMove = useCallback((move: KanbanMove) => onMove?.(move), [onMove]); const { drag, registerColumn, registerCard, startPointerDrag, grabWithKeyboard, moveWithKeyboard, commit, cancel, } = useKanbanDnd({ columns, wipLimitBehavior, onMove: handleMove, announce, labels: resolvedLabels, }); const tokens = useMemo(() => { const set = new Set([...COLUMN_TOKENS, ...BADGE_TOKENS]); columns.forEach(column => { if (column.colorToken) set.add(column.colorToken); column.cards.forEach(card => card.badges?.forEach(badge => badge.colorToken && set.add(badge.colorToken)) ); }); return Array.from(set); }, [columns]); const colors = useTokenColors(tokens); /** Pointer-down position, to tell a click apart from a drag. */ const pressRef = useRef<{ x: number; y: number; cardId: string } | null>(null); const handleCardPointerDown = (card: KanbanCard, event: React.PointerEvent) => { // Only the primary button starts a drag; right-click belongs to the menu. if (event.button !== 0) return; pressRef.current = { x: event.clientX, y: event.clientY, cardId: card.id }; }; const handleCardPointerMove = (card: KanbanCard, event: React.PointerEvent) => { const press = pressRef.current; if (!press || press.cardId !== card.id || drag) return; if (readOnly || card.locked) return; // A few pixels of slop, so a click with a shaky hand stays a click. if (Math.abs(event.clientX - press.x) + Math.abs(event.clientY - press.y) < 4) return; pressRef.current = null; startPointerDrag(card.id, event); }; const handleCardPointerUp = (card: KanbanCard) => { const press = pressRef.current; pressRef.current = null; if (!press || press.cardId !== card.id || drag) return; onSelect?.(card.id); onCardActivate?.(card.id, card); }; const handleCardKeyDown = (card: KanbanCard, event: React.KeyboardEvent) => { const holding = drag?.mode === 'keyboard' && drag.cardId === card.id; if (holding) { switch (event.key) { case 'ArrowLeft': case 'ArrowRight': case 'ArrowUp': case 'ArrowDown': event.preventDefault(); moveWithKeyboard( event.key === 'ArrowLeft' ? 'left' : event.key === 'ArrowRight' ? 'right' : event.key === 'ArrowUp' ? 'up' : 'down' ); break; case ' ': case 'Enter': event.preventDefault(); commit(); break; case 'Escape': event.preventDefault(); cancel(); break; default: break; } return; } if (event.key === ' ' && !readOnly && !card.locked) { event.preventDefault(); grabWithKeyboard(card.id); return; } if (event.key === 'Enter') { event.preventDefault(); onSelect?.(card.id); onCardActivate?.(card.id, card); } }; const isHeld = (cardId: string) => drag?.cardId === cardId; return (
{/* Every drag step is narrated here; without it a keyboard drag is invisible. */}
{announcement}
{columns.map(column => { const overThis = drag?.over.columnId === column.id; const atLimit = isAtLimit(column); const overLimit = isOverLimit(column); const accent = colors[column.colorToken ?? COLUMN_TOKENS[0]]; const visibleCards = column.cards.filter( card => !isHeld(card.id) || drag?.mode !== 'pointer' ); return (
registerColumn(column.id, element)} aria-label={`${column.title}, ${column.cards.length} cards`} className={cn( 'flex h-full min-h-0 shrink-0 flex-col rounded-[var(--radius-card)] border bg-muted/40', overThis && !column.locked ? 'border-ring' : 'border-border' )} style={{ width: columnWidth }} >
{renderColumnHeader ? ( renderColumnHeader(column) ) : ( <>
{column.description ? (

{column.description}

) : null}
    {visibleCards.length === 0 && !overThis ? (
  1. {emptyColumnLabel}
  2. ) : null} {visibleCards.map((card, index) => ( {overThis && drag && drag.over.index === index ? : null}
  3. registerCard(card.id, element)} role="button" tabIndex={0} aria-roledescription="Draggable card" aria-grabbed={ drag?.mode === 'keyboard' && isHeld(card.id) ? true : undefined } aria-label={card.title} aria-pressed={selectedCardId === card.id} onPointerDown={event => handleCardPointerDown(card, event)} onPointerMove={event => handleCardPointerMove(card, event)} onPointerUp={() => handleCardPointerUp(card)} onKeyDown={event => handleCardKeyDown(card, event)} className={cn( 'group rounded-[var(--radius-card)] border bg-card p-3 text-left outline-none', 'focus-visible:ring-[3px] focus-visible:ring-ring/50', 'transition-shadow duration-150 motion-reduce:transition-none', selectedCardId === card.id ? 'border-ring shadow-sm' : 'border-border', drag?.mode === 'keyboard' && isHeld(card.id) && 'ring-[3px] ring-ring/70', !readOnly && !card.locked ? 'cursor-grab' : 'cursor-default' )} > {renderCard ? ( renderCard(card, column) ) : ( )}
  4. ))} {overThis && drag && drag.over.index >= visibleCards.length ? : null}
); })}
{drag?.mode === 'pointer' && drag.pointer ? ( ) : null}
); } ); Kanban.displayName = 'Kanban'; /** The gap that opens where the card would land. */ function DropSlot() { return