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

TodoBoards.tsx

542 lines15.4 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";
52​
53enum BoardName {
54 Todo = "Todo",
55 InProgress = "In Progress",
56 Done = "Done",
58​
59const TASK_ITEM_HEIGHT = 180;
60​
61function DropIndicator() {
62 return <div className="h-0.5 bg-primary mx-2 mb-[0.4375rem] rounded-full" />;
64​
65function ScrollShadow({
66 position,
67 visible,
68}: {
69 position: "top" | "bottom";
70 visible: boolean;
71}) {
72 return (
73 <div
74 className={cn(
75 "absolute left-0 right-0 h-10 pointer-events-none z-10 transition-opacity duration-300 ease-in-out",
76 position === "top"
77 ? "top-0 bg-linear-to-b from-background to-transparent"
78 : "bottom-0 bg-linear-to-t from-background to-transparent",
79 visible ? "opacity-100" : "opacity-0",
80 )}
81 />
82 );
84​
85function findPrevItem<
86 T extends { boardId: string; todoItemId: string },
87 U extends T,
88>({
89 todoItems,
90 target,
91}: {
92 /**
93 The todo items must be sorted by position ascending
94 */
95 todoItems: U[];
96 target: T;
97}) {
98 const targetIndex = todoItems.findIndex(
99 (t) => t.todoItemId === target.todoItemId,
100 );
101​
102 const prev = todoItems[targetIndex - 1];
103​
104 return prev?.boardId === target.boardId ? prev : null;
106​
107function handlePriorityPointerDown(e: React.PointerEvent) {
108 e.stopPropagation();
109 e.preventDefault();
111​
112const TaskBase = forwardRef<
113 HTMLDivElement,
114 {
115 task: TodoItemRecord;
116 } & React.HTMLAttributes<HTMLDivElement>
117>(({ task, className, ...props }, ref) => {
118 // Prevent drag when clicking on PriorityRatingPopup
119​
120 return (
121 <Card
122 {...props}
123 ref={ref}
124 className={cn("select-none mb-2 relative overflow-hidden", className)}
125 >
126 <div className="absolute top-0 left-0 w-full flex justify-center bg-muted select-none">
127 {/* <GripHorizontalIcon className=" h-4" /> */}
128 <div className="text-muted-foreground">≡</div>
129 </div>
130 <CardHeader>
131 <CardTitle className="flex items-center justify-between mt-2">
132 <span className="block grow text-balance">{task.title}</span>
133 <PriorityRatingPopup priority={task.priority} todoItemId={task.id} />
134 </CardTitle>
135 <CardDescription>{task.description}</CardDescription>
136 </CardHeader>
137 <CardFooter className="flex justify-center">
138 {
139 <CreateOrEditTodoItems todoItem={task}>
140 <Button
141 onPointerDown={handlePriorityPointerDown}
142 onKeyDownCapture={(e) => {
143 e.stopPropagation();
144 e.preventDefault();
145 }}
146 variant="ghost"
147 size="sm"
148 className="cursor-pointer text-muted-foreground hover:text-foreground"
149 >
150 <SquarePenIcon className="text-primary" /> Edit
151 </Button>
152 </CreateOrEditTodoItems>
153 }
154 </CardFooter>
155 </Card>
156 );
157});
158​
159function DraggableTask({ task }: { task: TodoItemRecord }) {
160 const taskRef = useRef<HTMLDivElement>(null);
161 const [measuredHeight, setMeasuredHeight] = useState<number | null>(null);
162 const { attributes, listeners, setNodeRef, isDragging } = useSortable({
163 id: task.id,
164 });
165​
166 // Measure height after the element is rendered
167 useEffect(
168 () => {
169 if (taskRef.current) {
170 setMeasuredHeight(taskRef.current.offsetHeight);
171 }
172 },
173 /*
174 No dependency array: remeasures on every render
175 to capture dynamic content changes (edits, etc.)
176 */
177 );
178​
179 if (isDragging) {
180 return (
181 <div
182 ref={setNodeRef}
183 style={{ height: measuredHeight ?? TASK_ITEM_HEIGHT }}
184 className="bg-skeleton rounded-lg mb-2 animate-skeleton-pulse"
185 />
186 );
187 }
188​
189 return (
190 <TaskBase
191 task={task}
192 ref={(node) => {
193 setNodeRef(node);
194 taskRef.current = node;
195 }}
196 {...attributes}
197 {...listeners}
198 className="cursor-grab"
199 />
200 );
202​
203function Board({ board }: { board: BoardRecord }) {
204 const { data: todoItems } = useLiveQuery((q) =>
205 q
206 .from({ todoItem: todoItemsCollection })
207 .where(({ todoItem }) => eq(todoItem.boardId, board.id))
208 .orderBy(({ todoItem }) => todoItem.position, {
209 direction: "asc",
210 /*
211 We use fractional indexes, so we need lexical sorting to get the correct order.
212​
213 Ascending order of ["Zz", "a0"] is:
214 - lexical string sort: ["Zz", "a0"]
215 - default result (uses "locale"): ["a0", "Zz"]
216 */
217 stringSort: "lexical",
218 }),
219 );
220​
221 const { active, over } = useDndContext();
222 const { scrollRef, canScrollUp, canScrollDown } = useScrollShadow();
223​
224 const dropIndex = useMemo(() => {
225 // Calculate drop index for indicator
226 let dropIndex = -1;
227 if (active && over && active.id !== over.id) {
228 const overTaskIndex = todoItems.findIndex((item) => item.id === over.id);
229 if (overTaskIndex !== -1) {
230 // Show indicator before the over item
231 const activeTaskIndex = todoItems.findIndex(
232 (item) => item.id === active.id,
233 );
234 // Only hide the indicator if the active item is in this column and would be in the same position
235 if (activeTaskIndex === -1 || activeTaskIndex !== overTaskIndex - 1) {
236 dropIndex = overTaskIndex;
237 }
238 } else if (over.id === board.id) {
239 // Dropping on this column (empty or at the end)
240 const activeTaskIndex = todoItems.findIndex(
241 (item) => item.id === active.id,
242 );
243 // Only hide the indicator if the active item is in this column and would be at the end
244 if (
245 activeTaskIndex === -1 ||
246 activeTaskIndex !== todoItems.length - 1
247 ) {
248 dropIndex = todoItems.length;
249 }
250 }
251 }
252​
253 return dropIndex;
254 }, [todoItems, active, over, board.id]);
255​
256 const { setNodeRef } = useDroppable({ id: board.id });
257​
258 return (
259 <div className="flex flex-col flex-1 min-h-0">
260 <div className="mb-4">
261 <div className="flex items-center gap-2 mb-2">
262 <div>
263 {board.name === BoardName.Done ? (
264 <CircleCheckBigIcon />
265 ) : board.name === BoardName.InProgress ? (
266 <LoaderIcon />
267 ) : (
268 <LayoutListIcon />
269 )}
270 </div>
271 <h2 className="text-lg font-semibold">{board.name}</h2>
272 <Badge variant={"secondary"}>{todoItems.length} tasks</Badge>
273 </div>
274 <p className="text-sm text-muted-foreground mb-3">
275 {board.description}
276 </p>
277 <CreateOrEditTodoItems todoItem={{ boardId: board.id }}>
278 <Button className="w-full" variant={"outline"}>
279 <PlusIcon /> Add Task
280 </Button>
281 </CreateOrEditTodoItems>
282 </div>
283 <div className="relative flex-1 min-h-0">
284 <ScrollShadow position="top" visible={canScrollUp} />
285​
286 <div
287 ref={(node) => {
288 setNodeRef(node);
289 scrollRef.current = node;
290 }}
291 className="h-full overflow-auto"
292 >
293 <SortableContext
294 strategy={verticalListSortingStrategy}
295 items={todoItems.map((task) => task.id)}
296 >
297 {
298 /*
299 Empty columns do not have any todo items in them, so we can't
300 render the drop indicator when we iterate through the todo items.
301​
302 In that case, we need to render the drop indicator here.
303 */
304 active && dropIndex === 0 && todoItems.length === 0 && (
305 <DropIndicator />
306 )
307 }
308 <Virtualizer data={todoItems}>
309 {(todoItem, index) => {
310 const showDropIndicator = active && dropIndex === index;
311 return (
312 <div key={`${todoItem.id}-wrapper`}>
313 {showDropIndicator && <DropIndicator />}
314 <DraggableTask task={todoItem} />
315 {active &&
316 dropIndex === todoItems.length &&
317 index === todoItems.length - 1 && <DropIndicator />}
318 </div>
319 );
320 }}
321 </Virtualizer>
322 </SortableContext>
323 </div>
324​
325 <ScrollShadow position="bottom" visible={canScrollDown} />
326 </div>
327 </div>
328 );
330​
331export function TodoBoards({ projectId }: { projectId: string }) {
332 const [activeId, setActiveId] = useState<UniqueIdentifier | null>(null);
333​
334 // Create paced mutation with 3 second debounce for updating todo positions
335 const updateTodoPosition = usePacedMutations<
336 {
337 itemId: string;
338 boardId?: string;
339 newPosition: string;
340 },
341 TodoItemRecord
342 >({
343 onMutate: ({ itemId, boardId, newPosition }) => {
344 // Apply optimistic update immediately
345 todoItemsCollection.update(itemId, (item) => {
346 if (boardId) {
347 item.boardId = boardId;
348 }
349 item.position = newPosition;
350 });
351 },
352 mutationFn: async ({ transaction }) => {
353 // Persist all position updates to the backend after debounce
354 const mutations = transaction.mutations;
355​
356 const updates = mutations.reduce(
357 (acc, mutation) => {
358 const { modified, changes } = mutation;
359 acc.push({
360 id: modified.id,
361 ...changes,
362 });
363 return acc;
364 },
365 [] as (Partial<TodoItemRecord> & { id: string })[],
366 );
367​
368 await batchUpdateTodoItem({
369 data: updates,
370 });
371​
372 // Refetch to ensure consistency with backend
373 await todoItemsCollection.utils.refetch();
374 },
375 strategy: debounceStrategy({ wait: 1_000 }),
376 });
377​
378 const { data: boards, isLoading: isLoadingBoards } = useLiveQuery(
379 (q) =>
380 q
381 .from({ board: boardCollection })
382 .where(({ board }) => eq(board.projectId, projectId)),
383 [projectId],
384 );
385​
386 const {
387 data: [activeTodoItem],
388 } = useLiveQuery(
389 (q) =>
390 q
391 .from({ todoItem: todoItemsCollection })
392 .where(({ todoItem }) => eq(todoItem.id, activeId)),
393 [activeId, projectId],
394 );
395​
396 const { data: orderedTodoItems } = useLiveQuery(
397 (q) =>
398 q
399 .from({
400 todoItem: todoItemsCollection,
401 })
402 .innerJoin({ board: boardCollection }, ({ todoItem, board }) =>
403 eq(todoItem.boardId, board.id),
404 )
405 .innerJoin({ project: projectsCollection }, ({ board, project }) =>
406 eq(board.projectId, project.id),
407 )
408 .where(({ project }) => eq(project.id, projectId))
409 .select(({ todoItem, board }) => ({
410 boardId: todoItem.boardId,
411 boardName: board.name,
412 todoTitle: todoItem.title,
413 projectId: projectId,
414 position: todoItem.position,
415 todoItemId: todoItem.id,
416 }))
417 .orderBy(({ todoItem }) => [todoItem.boardId, todoItem.position], {
418 direction: "asc",
419 /*
420 We use fractional indexes, so we need lexical sorting to get the correct order.
421​
422 Ascending order of ["Zz", "a0"] is:
423 - lexical string sort: ["Zz", "a0"]
424 - default result (uses "locale"): ["a0", "Zz"]
425 */
426 stringSort: "lexical",
427 }),
428 [projectId],
429 );
430​
431 const handleDragStart = (event: DragStartEvent) => {
432 setActiveId(event.active.id);
433 };
434​
435 const handleDragEnd = async (event: DragEndEvent) => {
436 const { active, over } = event;
437 setActiveId(null);
438​
439 if (!over) return;
440​
441 // Find which column the dragged task is in
442​
443 if (boards.some((board) => board.id === over.id)) {
444 // This is either an empty column or the last place of a column
445 const newBoardId = over.id;
446 const lastPositionInNewColumn = orderedTodoItems.findLast(
447 (t) => t.boardId === newBoardId,
448 )?.position;
449​
450 const newPosition = lastPositionInNewColumn
451 ? generateKeyBetween(lastPositionInNewColumn, null)
452 : generateKeyBetween(null, null);
453​
454 updateTodoPosition({
455 itemId: active.id as string,
456 boardId: newBoardId as string,
457 newPosition,
458 });
459 } else {
460 const overTodoItem = todoItemsCollection.toArray.find(
461 (item) => item.id === over.id,
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 todoItemId: 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 if (overTodoItem) {
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 todoItemId: 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 } else {
509 console.error("overTodoId not found");
510 }
511 }
512 };
513​
514 const sortedBoards = useMemo(
515 () =>
516 boards.sort((a) =>
517 a.name === "Todo" ? -1 : a.name === "In Progress" ? -1 : 1,
518 ),
519 [boards],
520 );
521​
522 return (
523 <div className="flex-1 min-h-0">
524 <DndContext onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
525 {isLoadingBoards ? (
526 <TodoBoardsLoading />
527 ) : (
528 <div className="grid grid-cols-3 gap-4 h-full min-h-0">
529 {sortedBoards.map((board) => (
530 <Board board={board} key={board.id} />
531 ))}
532 </div>
533 )}
534 <DragOverlay>
535 {activeTodoItem ? (
536 <TaskBase task={activeTodoItem} className="animate-wiggle" />
537 ) : null}
538 </DragOverlay>
539 </DndContext>
540 </div>
541 );