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

TodoBoards.tsx

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