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