import React, {useEffect, useState, useRef, useContext} from "react"; import {useCreatePath, usePaths} from "../utils/queries/path-queries"; import { useQueryClient } from "@tanstack/react-query"; import { Plus } from "lucide-react"; import "./PathManager.css"; import {fetch_} from "../utils/request-utils"; import {ConfigContext} from "../ConfigProvider"; import { Input } from "./ui/input"; import { Button } from "./ui/button"; import { Spinner } from "./ui/misc"; const PathManager = ({ currentPathId = 1, onPathChange }) => { const [currentFullPath, setCurrentFullPath] = useState([{ name: "Root", id: 1 }]); const [searchTerm, setSearchTerm] = useState(""); const [dropdownActive, setDropdownActive] = useState(false); const inputRef = useRef(); const queryClient = useQueryClient(); const { data: subPaths, isLoading: isSubPathsLoading, error: subPathsError } = usePaths(currentPathId); const createPath = useCreatePath(); const config = useContext(ConfigContext).config; const buildFullPath = async (pathId) => { const path = []; let current_id = pathId; while (current_id) { try { const pathData = await queryClient.fetchQuery({ queryKey: ["path", current_id], queryFn: () => fetch_(`${config.BACKEND_HOST}/api/path/${current_id}`) }); if (!pathData) break; path.unshift({ name: pathData.name, id: pathData.id }); current_id = pathData.parent_id; } catch (error) { console.error(`Failed to fetch path with id ${current_id}:`, error); break; } } return path; }; useEffect(() => { const init = async () => { const path = await buildFullPath(currentPathId); setCurrentFullPath(path); }; init(); }, [currentPathId, queryClient]); const handlePathClick = (pathId, pathIndex) => { const newPath = currentFullPath.slice(0, pathIndex + 1); setCurrentFullPath(newPath); onPathChange(pathId); }; const handleSubPathSelect = (subPath) => { const updatedPath = [...currentFullPath, { name: subPath.name, id: subPath.id }]; setCurrentFullPath(updatedPath); onPathChange(subPath.id); setSearchTerm(""); setDropdownActive(false); }; const handleAddDirectory = () => { if (!searchTerm.trim()) { alert("Directory name cannot be empty."); return; } createPath.mutate( { name: searchTerm.trim(), parent_id: currentPathId }, { onSuccess: (newDir) => { queryClient.setQueryData({queryKey: ["path", newDir.id]}, newDir); queryClient.invalidateQueries({queryKey: ["paths", currentPathId]}); setSearchTerm(""); alert("Directory created successfully."); }, onError: (error) => { console.error("Failed to create directory:", error); alert("Failed to create directory."); }, } ); }; const handleInputFocus = () => setDropdownActive(true); const handleInputBlur = () => { setTimeout(() => setDropdownActive(false), 150); }; const filteredSubPaths = subPaths ? subPaths.filter((path) => path.name.toLowerCase().includes(searchTerm.toLowerCase()) ) : []; const handleKeyDown = (e) => { if (e.key === "Enter") { e.preventDefault(); handleAddDirectory(); } }; return (
Error loading subdirectories.
)}