|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { useEffect, useMemo, useRef } from "react"; |
| 4 | +import { usePathname, useRouter, useSearchParams } from "next/navigation"; |
| 5 | +import { useModal } from "@/hooks/use-modal"; |
| 6 | +import { KanbanBoardType, KanbanColumnType } from "@/types/home/codev"; |
| 7 | + |
| 8 | +/** |
| 9 | + * Syncs the Kanban task modal with the URL ?taskId param. |
| 10 | + */ |
| 11 | +export function useKanbanTaskUrlModal( |
| 12 | + boardData: KanbanBoardType & { kanban_columns: KanbanColumnType[] } |
| 13 | +) { |
| 14 | + const { isOpen, type, onOpen } = useModal(); |
| 15 | + const router = useRouter(); |
| 16 | + const pathname = usePathname(); |
| 17 | + const searchParams = useSearchParams(); |
| 18 | + |
| 19 | + // Flatten all tasks once |
| 20 | + const tasks = useMemo( |
| 21 | + () => boardData.kanban_columns.flatMap((col) => col.tasks ?? []), |
| 22 | + [boardData.kanban_columns] |
| 23 | + ); |
| 24 | + |
| 25 | + // Track whether we've already opened the modal from the URL |
| 26 | + const openedFromUrlRef = useRef(false); |
| 27 | + |
| 28 | + useEffect(() => { |
| 29 | + const taskId = searchParams.get("taskId"); |
| 30 | + |
| 31 | + // Open modal only once from URL |
| 32 | + if (taskId && !openedFromUrlRef.current) { |
| 33 | + const task = tasks.find((t) => t.id === taskId); |
| 34 | + if (task) { |
| 35 | + onOpen("taskViewModal", task); |
| 36 | + openedFromUrlRef.current = true; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + // Clear URL if modal closed |
| 41 | + if (!isOpen && searchParams.has("taskId")) { |
| 42 | + router.replace(pathname, { scroll: false }); |
| 43 | + openedFromUrlRef.current = false; // reset so next URL param works |
| 44 | + } |
| 45 | + |
| 46 | + // If modal type changes away from taskViewModal, remove param |
| 47 | + if (isOpen && type !== "taskViewModal" && searchParams.has("taskId")) { |
| 48 | + router.replace(pathname, { scroll: false }); |
| 49 | + openedFromUrlRef.current = false; |
| 50 | + } |
| 51 | + }, [isOpen, type, tasks, onOpen, pathname, searchParams, router]); |
| 52 | +} |
0 commit comments