Open History to see the last commit
1import {
2 DndContext,
3 type DragEndEvent,
4 DragOverlay,
5 type DragStartEvent,
6 type UniqueIdentifier,
7 useDndContext,
8 useDroppable,
9} from "@dnd-kit/core";
10import {
11 SortableContext,
12 useSortable,
13 verticalListSortingStrategy,
14} from "@dnd-kit/sortable";
15import { eq, useLiveQuery } from "@tanstack/react-db";
16import { generateKeyBetween } from "fractional-indexing";
17import {
18 CircleCheckBigIcon,
19 LayoutListIcon,
20 LoaderIcon,
21 PlusIcon,
22 SquarePenIcon,
23} from "lucide-react";
24import { forwardRef, useEffect, useMemo, useRef, useState } from "react";
25import { Virtualizer } from "virtua";
26import { boardCollection } from "@/collections/boards";
27import { projectsCollection } from "@/collections/projects";
28import { todoItemsCollection } from "@/collections/todoItems";
29import type { BoardRecord, TodoItemRecord } from "@/db/schema";
30import { useScrollShadow } from "@/hooks/use-scroll-shadow";
31import { cn } from "@/lib/utils";
32import { CreateOrEditTodoItems } from "./CreateOrEditTodoItems";
33import { PriorityRatingPopup } from "./PriorityRating";
34import { TodoBoardsLoading } from "./TodoBoardsLoading";
35import { Badge } from "./ui/badge";
36import { Button } from "./ui/button";
37import {
38 Card,
39 CardDescription,
40 CardFooter,
41 CardHeader,
42 CardTitle,
43} from "./ui/card";
44import { ScrollShadow } from "./ui/scroll-shadow";
45
46enum BoardName {
47 Todo = "Todo",
48 InProgress = "In Progress",
49 Done = "Done",
50}
51
52const TASK_ITEM_HEIGHT = 180;
53
54function DropIndicator() {
55 return <div className="h-0.5 bg-primary mx-2 mb-[0.4375rem] rounded-full" />;
56}
57
58function findPrevItem<
59 T extends { boardId: string; todoItemId: string },
60 U extends T,
61>({
62 todoItems,
63 target,
64}: {
65 /**
66 The todo items must be sorted by position ascending
67 */
68 todoItems: U[];
69 target: T;
70}) {
71 const targetIndex = todoItems.findIndex(
72 (t) => t.todoItemId === target.todoItemId,
73 );
74
75 const prev = todoItems[targetIndex - 1];
76
77 return prev?.boardId === target.boardId ? prev : null;
78}
79
80function handlePriorityPointerDown(e: React.PointerEvent) {
81 e.stopPropagation();
82 e.preventDefault();
83}
84
85const TaskBase = forwardRef<
86 HTMLDivElement,
87 {
88 task: TodoItemRecord;
89 } & React.HTMLAttributes<HTMLDivElement>
90>(({ task, className, ...props }, ref) => {
91 // Prevent drag when clicking on PriorityRatingPopup
92
93 return (
94 <Card
95 {...props}
96 ref={ref}
97 className={cn("select-none mb-2 relative overflow-hidden", className)}
98 >
99 <div className="absolute top-0 left-0 w-full flex justify-center bg-muted select-none">
100 {/* <GripHorizontalIcon className=" h-4" /> */}
101 <div className="text-muted-foreground">≡</div>
102 </div>
103 <CardHeader>
104 <CardTitle className="flex items-center justify-between mt-2">
105 <span className="block grow text-balance">{task.title}</span>
106 <PriorityRatingPopup priority={task.priority} todoItemId={task.id} />
107 </CardTitle>
108 <CardDescription>{task.description}</CardDescription>
109 </CardHeader>
110 <CardFooter className="flex justify-center">
111 {
112 <CreateOrEditTodoItems todoItem={task}>
113 <Button
114 onPointerDown={handlePriorityPointerDown}
115 onKeyDownCapture={(e) => {
116 e.stopPropagation();
117 e.preventDefault();
118 }}
119 variant="ghost"
120 size="sm"
121 className="cursor-pointer text-muted-foreground hover:text-foreground"
122 >
123 <SquarePenIcon className="text-primary" /> Edit
124 </Button>
125 </CreateOrEditTodoItems>
126 }
127 </CardFooter>
128 </Card>
129 );
130});
131
132function DraggableTask({ task }: { task: TodoItemRecord }) {
133 const taskRef = useRef<HTMLDivElement>(null);
134 const [measuredHeight, setMeasuredHeight] = useState<number | null>(null);
135 const { attributes, listeners, setNodeRef, isDragging } = useSortable({
136 id: task.id,
137 });
138
139 // Measure height after the element is rendered
140 useEffect(
141 () => {
142 if (taskRef.current) {
143 setMeasuredHeight(taskRef.current.offsetHeight);
144 }
145 },
146 /*
147 No dependency array: remeasures on every render
148 to capture dynamic content changes (edits, etc.)
149 */
150 );
151
152 if (isDragging) {
153 return (
154 <div
155 ref={setNodeRef}
156 style={{ height: measuredHeight ?? TASK_ITEM_HEIGHT }}
157 className="bg-skeleton rounded-lg mb-2 animate-skeleton-pulse"
158 />
159 );
160 }
161
162 return (
163 <TaskBase
164 task={task}
165 ref={(node) => {
166 setNodeRef(node);
167 taskRef.current = node;
168 }}
169 {...attributes}
170 {...listeners}
171 className="cursor-grab"
172 />
173 );
174}
175
176function Board({ board }: { board: BoardRecord }) {
177 const { data: todoItems } = useLiveQuery((q) =>
178 q
179 .from({ todoItem: todoItemsCollection })
180 .where(({ todoItem }) => eq(todoItem.boardId, board.id))
181 .orderBy(({ todoItem }) => todoItem.position, {
182 direction: "asc",
183 /*
184 We use fractional indexes, so we need lexical sorting to get the correct order.
185
186 Ascending order of ["Zz", "a0"] is:
187 - lexical string sort: ["Zz", "a0"]
188 - default result (uses "locale"): ["a0", "Zz"]
189 */
190 stringSort: "lexical",
191 }),
192 );
193
194 const { active, over } = useDndContext();
195 const { scrollRef, canScrollUp, canScrollDown } = useScrollShadow();
196
197 const dropIndex = useMemo(() => {
198 // Calculate drop index for indicator
199 let dropIndex = -1;
200 if (active && over && active.id !== over.id) {
201 const overTaskIndex = todoItems.findIndex((item) => item.id === over.id);
202 if (overTaskIndex !== -1) {
203 // Show indicator before the over item
204 const activeTaskIndex = todoItems.findIndex(
205 (item) => item.id === active.id,
206 );
207 // Only hide the indicator if the active item is in this column and would be in the same position
208 if (activeTaskIndex === -1 || activeTaskIndex !== overTaskIndex - 1) {
209 dropIndex = overTaskIndex;
210 }
211 } else if (over.id === board.id) {
212 // Dropping on this column (empty or at the end)
213 const activeTaskIndex = todoItems.findIndex(
214 (item) => item.id === active.id,
215 );
216 // Only hide the indicator if the active item is in this column and would be at the end
217 if (
218 activeTaskIndex === -1 ||
219 activeTaskIndex !== todoItems.length - 1
220 ) {
221 dropIndex = todoItems.length;
222 }
223 }
224 }
225
226 return dropIndex;
227 }, [todoItems, active, over, board.id]);
228
229 const { setNodeRef } = useDroppable({ id: board.id });
230
231 return (
232 <div className="flex flex-col flex-1 min-h-0">
233 <div className="mb-4">
234 <div className="flex items-center gap-2 mb-2">
235 <div>
236 {board.name === BoardName.Done ? (
237 <CircleCheckBigIcon />
238 ) : board.name === BoardName.InProgress ? (
239 <LoaderIcon />
240 ) : (
241 <LayoutListIcon />
242 )}
243 </div>
244 <h2 className="text-lg font-semibold">{board.name}</h2>
245 <Badge variant={"secondary"}>{todoItems.length} tasks</Badge>
246 </div>
247 <p className="text-sm text-muted-foreground mb-3">
248 {board.description}
249 </p>
250 <CreateOrEditTodoItems todoItem={{ boardId: board.id }}>
251 <Button className="w-full" variant={"outline"}>
252 <PlusIcon /> Add Task
253 </Button>
254 </CreateOrEditTodoItems>
255 </div>
256 <div className="relative flex-1 min-h-0">
257 <ScrollShadow position="top" visible={canScrollUp} />
258
259 <div
260 ref={(node) => {
261 setNodeRef(node);
262 scrollRef.current = node;
263 }}
264 className="h-full overflow-auto"
265 >
266 <SortableContext
267 strategy={verticalListSortingStrategy}
268 items={todoItems.map((task) => task.id)}
269 >
270 {
271 /*
272 Empty columns do not have any todo items in them, so we can't
273 render the drop indicator when we iterate through the todo items.
274
275 In that case, we need to render the drop indicator here.
276 */
277 active && dropIndex === 0 && todoItems.length === 0 && (
278 <DropIndicator />
279 )
280 }
281 <Virtualizer data={todoItems}>
282 {(todoItem, index) => {
283 const showDropIndicator = active && dropIndex === index;
284 return (
285 <div key={`${todoItem.id}-wrapper`}>
286 {showDropIndicator && <DropIndicator />}
287 <DraggableTask task={todoItem} />
288 {active &&
289 dropIndex === todoItems.length &&
290 index === todoItems.length - 1 && <DropIndicator />}
291 </div>
292 );
293 }}
294 </Virtualizer>
295 </SortableContext>
296 </div>
297
298 <ScrollShadow position="bottom" visible={canScrollDown} />
299 </div>
300 </div>
301 );
302}
303
304export function TodoBoards({ projectId }: { projectId: string }) {
305 const [activeId, setActiveId] = useState<UniqueIdentifier | null>(null);
306
307 const updateTodoPosition = ({
308 itemId,
309 boardId,
310 newPosition,
311 }: {
312 itemId: string;
313 boardId?: string;
314 newPosition: string;
315 }) => {
316 todoItemsCollection.update(itemId, (item) => {
317 if (boardId) {
318 item.boardId = boardId;
319 }
320 item.position = newPosition;
321 });
322 };
323
324 const { data: boards, isLoading: isLoadingBoards } = useLiveQuery(
325 (q) =>
326 q
327 .from({ board: boardCollection })
328 .where(({ board }) => eq(board.projectId, projectId)),
329 [projectId],
330 );
331
332 const {
333 data: [activeTodoItem],
334 } = useLiveQuery(
335 (q) =>
336 q
337 .from({ todoItem: todoItemsCollection })
338 .where(({ todoItem }) => eq(todoItem.id, activeId)),
339 [activeId, projectId],
340 );
341
342 const { data: orderedTodoItems } = useLiveQuery(
343 (q) =>
344 q
345 .from({
346 todoItem: todoItemsCollection,
347 })
348 .innerJoin({ board: boardCollection }, ({ todoItem, board }) =>
349 eq(todoItem.boardId, board.id),
350 )
351 .innerJoin({ project: projectsCollection }, ({ board, project }) =>
352 eq(board.projectId, project.id),
353 )
354 .where(({ project }) => eq(project.id, projectId))
355 .select(({ todoItem, board }) => ({
356 boardId: todoItem.boardId,
357 boardName: board.name,
358 todoTitle: todoItem.title,
359 projectId: projectId,
360 position: todoItem.position,
361 todoItemId: todoItem.id,
362 }))
363 .orderBy(({ todoItem }) => [todoItem.boardId, todoItem.position], {
364 direction: "asc",
365 /*
366 We use fractional indexes, so we need lexical sorting to get the correct order.
367
368 Ascending order of ["Zz", "a0"] is:
369 - lexical string sort: ["Zz", "a0"]
370 - default result (uses "locale"): ["a0", "Zz"]
371 */
372 stringSort: "lexical",
373 }),
374 [projectId],
375 );
376
377 const handleDragStart = (event: DragStartEvent) => {
378 setActiveId(event.active.id);
379 };
380
381 const handleDragEnd = async (event: DragEndEvent) => {
382 const { active, over } = event;
383 setActiveId(null);
384
385 if (!over) return;
386
387 // Find which column the dragged task is in
388
389 if (boards.some((board) => board.id === over.id)) {
390 // This is either an empty column or the last place of a column
391 const newBoardId = over.id;
392 const lastPositionInNewColumn = orderedTodoItems.findLast(
393 (t) => t.boardId === newBoardId,
394 )?.position;
395
396 const newPosition = lastPositionInNewColumn
397 ? generateKeyBetween(lastPositionInNewColumn, null)
398 : generateKeyBetween(null, null);
399
400 updateTodoPosition({
401 itemId: active.id as string,
402 boardId: newBoardId as string,
403 newPosition,
404 });
405 } else {
406 const overTodoItem = todoItemsCollection.toArray.find(
407 (item) => item.id === over.id,
408 );
409
410 if (overTodoItem?.boardId === activeTodoItem.boardId) {
411 // Reorder within the same column
412
413 const prev = findPrevItem({
414 todoItems: orderedTodoItems,
415 target: {
416 boardId: overTodoItem.boardId,
417 todoItemId: overTodoItem.id as string,
418 },
419 });
420
421 // Generate position between the item before 'over' and 'over' itself
422 const newPosition = generateKeyBetween(
423 prev?.position ?? null,
424 overTodoItem.position,
425 );
426
427 updateTodoPosition({
428 itemId: active.id as string,
429 newPosition,
430 });
431 } else if (overTodoItem) {
432 // Move to another column and insert at the correct position
433 const newBoardId = overTodoItem.boardId;
434
435 const prev = findPrevItem({
436 todoItems: orderedTodoItems,
437 target: {
438 boardId: overTodoItem.boardId,
439 todoItemId: overTodoItem.id as string,
440 },
441 });
442
443 // Generate position between the item before 'over' and 'over' itself
444 const newPosition = generateKeyBetween(
445 prev?.position ?? null,
446 overTodoItem.position,
447 );
448
449 updateTodoPosition({
450 itemId: active.id as string,
451 boardId: newBoardId as string,
452 newPosition,
453 });
454 } else {
455 console.error("overTodoId not found");
456 }
457 }
458 };
459
460 const sortedBoards = useMemo(
461 () =>
462 boards.sort((a) =>
463 a.name === "Todo" ? -1 : a.name === "In Progress" ? -1 : 1,
464 ),
465 [boards],
466 );
467
468 return (
469 <div className="flex-1 min-h-0">
470 <DndContext onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
471 {isLoadingBoards ? (
472 <TodoBoardsLoading />
473 ) : (
474 <div className="grid grid-cols-3 gap-4 h-full min-h-0">
475 {sortedBoards.map((board) => (
476 <Board board={board} key={board.id} />
477 ))}
478 </div>
479 )}
480 <DragOverlay>
481 {activeTodoItem ? (
482 <TaskBase task={activeTodoItem} className="animate-wiggle" />
483 ) : null}
484 </DragOverlay>
485 </DndContext>
486 </div>
487 );
488}