import { useState, useEffect, useRef, useCallback } from "react"; import { Clock, Trash2, Download, Play, Star } from "lucide-react"; import { Tooltip } from "../ui/Tooltip"; import { useQueryStore } from "../../stores/queryStore"; interface QueryHistoryDropdownProps { connectionId: string; onRestore: (sql: string) => void; onRun: (sql: string) => void; } export function QueryHistoryDropdown({ connectionId, onRestore, onRun, }: QueryHistoryDropdownProps) { const [open, setOpen] = useState(false); const menuRef = useRef(null); const history = useQueryStore((s) => s.history); const loading = useQueryStore((s) => s.historyLoading); const historyError = useQueryStore((s) => s.historyError); const stale = useQueryStore((s) => s.historyStale); const loadHistory = useQueryStore((s) => s.loadHistory); const clearHistory = useQueryStore((s) => s.clearHistory); const toggleFavorite = useQueryStore((s) => s.toggleFavorite); // Lazy fetch on open const handleToggle = useCallback(() => { const willOpen = !open; setOpen(willOpen); if (willOpen && stale) { loadHistory(connectionId); } }, [open, stale, connectionId, loadHistory]); // Close on outside click / Escape useEffect(() => { if (!open) return; const onMouseDown = (e: MouseEvent) => { if (menuRef.current && !menuRef.current.contains(e.target as Node)) { setOpen(false); } }; const onKeyDown = (e: KeyboardEvent) => { if (e.key === "Escape") setOpen(false); }; document.addEventListener("mousedown", onMouseDown, true); document.addEventListener("keydown", onKeyDown); return () => { document.removeEventListener("mousedown", onMouseDown, true); document.removeEventListener("keydown", onKeyDown); }; }, [open]); return (
{open && (
{loading && history === null && (
)} {historyError && !loading && (
{historyError}
)} {!loading && !historyError && (!history || history.length === 0) && (
No queries yet
)} {!loading && !historyError && history && history.length > 0 && ( <> {history.slice(0, 50).map((entry) => (
{entry.query_text}
{entry.status === "error" ? ( Error ) : ( <> {entry.execution_time_ms != null && ( {entry.execution_time_ms}ms )} {entry.row_count != null && ( {entry.row_count} rows )} )}
))} {/* Clear History footer */} )}
)}
); }