Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

TodoBoards.tsx

538 lines15.6 KB

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