import { useEffect, useRef, useState } from "react" import { pb } from "../pb" import type { PbFile } from "../types" import "./FilePicker.css" export type FilePickerProps = { onSelect: (fileId: string) => void onClose: () => void } export function FilePicker({ onSelect, onClose }: FilePickerProps) { const [files, setFiles] = useState([]) const [page, setPage] = useState(1) const [totalPages, setTotalPages] = useState(1) const [loading, setLoading] = useState(false) const [uploading, setUploading] = useState(false) const [tab, setTab] = useState<"browse" | "upload">("browse") const fileRef = useRef(null) useEffect(() => { let cancelled = false setLoading(true) pb.collection("files") .getList(page, 20, { sort: "-created" }) .then(result => { if (cancelled) return setFiles(result.items) setTotalPages(result.totalPages) }) .catch(err => { if (!cancelled) console.error("Failed to load files:", err) }) .finally(() => { if (!cancelled) setLoading(false) }) return () => { cancelled = true } }, [page]) async function handleUpload() { const file = fileRef.current?.files?.[0] if (!file) return setUploading(true) try { const record = await pb.collection("files").create({ file, filename: file.name, }) onSelect(record.id) } catch (err) { console.error("Upload failed:", err) alert("Upload failed. Check console.") } finally { setUploading(false) } } return (
{ if (e.key === "Escape") onClose() }} >
e.stopPropagation()} onKeyDown={e => { e.stopPropagation() }} >
{tab === "browse" && (
{loading ? (
Loading...
) : (
{files.map(f => ( ))}
)}
{page} / {totalPages}
)} {tab === "upload" && (
)}
) }