1"use client";
2
3import type {
4 Announcements,
5 DndContextProps,
6 DragEndEvent,
7 DragOverEvent,
8 DragStartEvent,
9} from "@dnd-kit/core";
10import {
11 closestCenter,
12 DndContext,
13 DragOverlay,
14 KeyboardSensor,
15 MouseSensor,
16 TouchSensor,
17 useDroppable,
18 useSensor,
19 useSensors,
20} from "@dnd-kit/core";
21import { arrayMove, SortableContext, useSortable } from "@dnd-kit/sortable";
22import { CSS } from "@dnd-kit/utilities";
23import {
24 createContext,
25 type HTMLAttributes,
26 type ReactNode,
27 useContext,
28 useState,
29} from "react";
30import { createPortal } from "react-dom";
31import tunnel from "tunnel-rat";
32import { Card } from "@/components/ui/card";
33import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
34import { cn } from "@/lib/utils";
35
36const t = tunnel();
37
38export type { DragEndEvent } from "@dnd-kit/core";
39
40type KanbanItemProps = {
41 id: string;
42 name: string;
43 column: string;
44} & Record<string, unknown>;
45
46type KanbanColumnProps = {
47 id: string;
48 name: string;
49} & Record<string, unknown>;
50
51type KanbanContextProps<
52 T extends KanbanItemProps = KanbanItemProps,
53 C extends KanbanColumnProps = KanbanColumnProps,
54> = {
55 columns: C[];
56 data: T[];
57 activeCardId: string | null;
58};
59
60const KanbanContext = createContext<KanbanContextProps>({
61 columns: [],
62 data: [],
63 activeCardId: null,
64});
65
66export type KanbanBoardProps = {
67 id: string;
68 children: ReactNode;
69 className?: string;
70};
71
72export const KanbanBoard = ({ id, children, className }: KanbanBoardProps) => {
73 const { isOver, setNodeRef } = useDroppable({
74 id,
75 });
76
77 return (
78 <div
79 className={cn(
80 "flex size-full min-h-40 flex-col divide-y overflow-hidden rounded-md border bg-secondary text-xs shadow-sm ring-2 transition-all",
81 isOver ? "ring-primary" : "ring-transparent",
82 className
83 )}
84 ref={setNodeRef}
85 >
86 {children}
87 </div>
88 );
89};
90
91export type KanbanCardProps<T extends KanbanItemProps = KanbanItemProps> = T & {
92 children?: ReactNode;
93 className?: string;
94};
95
96export const KanbanCard = <T extends KanbanItemProps = KanbanItemProps>({
97 id,
98 name,
99 children,
100 className,
101}: KanbanCardProps<T>) => {
102 const {
103 attributes,
104 listeners,
105 setNodeRef,
106 transition,
107 transform,
108 isDragging,
109 } = useSortable({
110 id,
111 });
112 const { activeCardId } = useContext(KanbanContext) as KanbanContextProps;
113
114 const style = {
115 transition,
116 transform: CSS.Transform.toString(transform),
117 };
118
119 return (
120 <>
121 <div style={style} {...listeners} {...attributes} ref={setNodeRef}>
122 <Card
123 className={cn(
124 "cursor-grab gap-4 rounded-md p-3 shadow-sm",
125 isDragging && "pointer-events-none cursor-grabbing opacity-30",
126 className
127 )}
128 >
129 {children ?? <p className="m-0 font-medium text-sm">{name}</p>}
130 </Card>
131 </div>
132 {activeCardId === id && (
133 <t.In>
134 <Card
135 className={cn(
136 "cursor-grab gap-4 rounded-md p-3 shadow-sm ring-2 ring-primary",
137 isDragging && "cursor-grabbing",
138 className
139 )}
140 >
141 {children ?? <p className="m-0 font-medium text-sm">{name}</p>}
142 </Card>
143 </t.In>
144 )}
145 </>
146 );
147};
148
149export type KanbanCardsProps<T extends KanbanItemProps = KanbanItemProps> =
150 Omit<HTMLAttributes<HTMLDivElement>, "children" | "id"> & {
151 children: (item: T) => ReactNode;
152 id: string;
153 };
154
155export const KanbanCards = <T extends KanbanItemProps = KanbanItemProps>({
156 children,
157 className,
158 ...props
159}: KanbanCardsProps<T>) => {
160 const { data } = useContext(KanbanContext) as KanbanContextProps<T>;
161 const filteredData = data.filter((item) => item.column === props.id);
162 const items = filteredData.map((item) => item.id);
163
164 return (
165 <ScrollArea className="overflow-hidden">
166 <SortableContext items={items}>
167 <div
168 className={cn("flex flex-grow flex-col gap-2 p-2", className)}
169 {...props}
170 >
171 {filteredData.map(children)}
172 </div>
173 </SortableContext>
174 <ScrollBar orientation="vertical" />
175 </ScrollArea>
176 );
177};
178
179export type KanbanHeaderProps = HTMLAttributes<HTMLDivElement>;
180
181export const KanbanHeader = ({ className, ...props }: KanbanHeaderProps) => (
182 <div className={cn("m-0 p-2 font-semibold text-sm", className)} {...props} />
183);
184
185export type KanbanProviderProps<
186 T extends KanbanItemProps = KanbanItemProps,
187 C extends KanbanColumnProps = KanbanColumnProps,
188> = Omit<DndContextProps, "children"> & {
189 children: (column: C) => ReactNode;
190 className?: string;
191 columns: C[];
192 data: T[];
193 onDataChange?: (data: T[]) => void;
194 onDragStart?: (event: DragStartEvent) => void;
195 onDragEnd?: (event: DragEndEvent) => void;
196 onDragOver?: (event: DragOverEvent) => void;
197};
198
199export const KanbanProvider = <
200 T extends KanbanItemProps = KanbanItemProps,
201 C extends KanbanColumnProps = KanbanColumnProps,
202>({
203 children,
204 onDragStart,
205 onDragEnd,
206 onDragOver,
207 className,
208 columns,
209 data,
210 onDataChange,
211 ...props
212}: KanbanProviderProps<T, C>) => {
213 const [activeCardId, setActiveCardId] = useState<string | null>(null);
214
215 const sensors = useSensors(
216 useSensor(MouseSensor),
217 useSensor(TouchSensor),
218 useSensor(KeyboardSensor)
219 );
220
221 const handleDragStart = (event: DragStartEvent) => {
222 const card = data.find((item) => item.id === event.active.id);
223 if (card) {
224 setActiveCardId(event.active.id as string);
225 }
226 onDragStart?.(event);
227 };
228
229 const handleDragOver = (event: DragOverEvent) => {
230 const { active, over } = event;
231
232 if (!over) {
233 return;
234 }
235
236 const activeItem = data.find((item) => item.id === active.id);
237 const overItem = data.find((item) => item.id === over.id);
238
239 if (!activeItem) {
240 return;
241 }
242
243 const activeColumn = activeItem.column;
244 const overColumn =
245 overItem?.column ||
246 columns.find((col) => col.id === over.id)?.id ||
247 columns[0]?.id;
248
249 if (activeColumn !== overColumn) {
250 let newData = [...data];
251 const activeIndex = newData.findIndex((item) => item.id === active.id);
252 const overIndex = newData.findIndex((item) => item.id === over.id);
253
254 newData[activeIndex].column = overColumn;
255 newData = arrayMove(newData, activeIndex, overIndex);
256
257 onDataChange?.(newData);
258 }
259
260 onDragOver?.(event);
261 };
262
263 const handleDragEnd = (event: DragEndEvent) => {
264 setActiveCardId(null);
265
266 onDragEnd?.(event);
267
268 const { active, over } = event;
269
270 if (!over || active.id === over.id) {
271 return;
272 }
273
274 let newData = [...data];
275
276 const oldIndex = newData.findIndex((item) => item.id === active.id);
277 const newIndex = newData.findIndex((item) => item.id === over.id);
278
279 newData = arrayMove(newData, oldIndex, newIndex);
280
281 onDataChange?.(newData);
282 };
283
284 const announcements: Announcements = {
285 onDragStart({ active }) {
286 const { name, column } = data.find((item) => item.id === active.id) ?? {};
287
288 return `Picked up the card "${name}" from the "${column}" column`;
289 },
290 onDragOver({ active, over }) {
291 const { name } = data.find((item) => item.id === active.id) ?? {};
292 const newColumn = columns.find((column) => column.id === over?.id)?.name;
293
294 return `Dragged the card "${name}" over the "${newColumn}" column`;
295 },
296 onDragEnd({ active, over }) {
297 const { name } = data.find((item) => item.id === active.id) ?? {};
298 const newColumn = columns.find((column) => column.id === over?.id)?.name;
299
300 return `Dropped the card "${name}" into the "${newColumn}" column`;
301 },
302 onDragCancel({ active }) {
303 const { name } = data.find((item) => item.id === active.id) ?? {};
304
305 return `Cancelled dragging the card "${name}"`;
306 },
307 };
308
309 return (
310 <KanbanContext.Provider value={{ columns, data, activeCardId }}>
311 <DndContext
312 accessibility={{ announcements }}
313 collisionDetection={closestCenter}
314 onDragEnd={handleDragEnd}
315 onDragOver={handleDragOver}
316 onDragStart={handleDragStart}
317 sensors={sensors}
318 {...props}
319 >
320 <div
321 className={cn(
322 "grid size-full auto-cols-fr grid-flow-col gap-4",
323 className
324 )}
325 >
326 {columns.map((column) => children(column))}
327 </div>
328 {typeof window !== "undefined" &&
329 createPortal(
330 <DragOverlay>
331 <t.Out />
332 </DragOverlay>,
333 document.body
334 )}
335 </DndContext>
336 </KanbanContext.Provider>
337 );
338};
339