import { Icon, IconButton, PlainInput } from "@yaakapp-internal/ui"; import { useAtomValue, useSetAtom } from "jotai"; import { memo, useEffect, useRef, useState } from "react"; import { exportHar } from "../lib/flowActions"; import { searchTerms } from "../lib/search"; import { activeQueryAtom, searchTermsAtom } from "../lib/store"; import { useShowToast } from "../lib/toast"; /** How long typing settles before the search runs */ const SEARCH_DEBOUNCE_MS = 200; /** * Searches every flow in the database by URL, method, status and content type, within the * sidebar's selection. ⌘F focuses it and Escape clears it. */ export const SearchBar = memo(function SearchBar() { const [text, setText] = useState(""); const setTerms = useSetAtom(searchTermsAtom); const query = useAtomValue(activeQueryAtom); const showToast = useShowToast(); // PlainInput hands back its as the ref const inputRef = useRef(null); // Bumped to empty the field, which only takes a value from outside when this changes const [resetKey, setResetKey] = useState(0); useEffect(() => { const timer = setTimeout(() => setTerms(searchTerms(text)), SEARCH_DEBOUNCE_MS); return () => clearTimeout(timer); }, [text, setTerms]); useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { if ((e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey && e.key.toLowerCase() === "f") { e.preventDefault(); inputRef.current?.focus(); inputRef.current?.select(); } }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); }, []); // The field is replaced to empty it, so focus moves to the new one. const clear = () => { setText(""); setTerms(null); setResetKey((k) => k + 1); requestAnimationFrame(() => inputRef.current?.focus()); }; return (
{ if (e.key === "Escape" && text !== "") { e.stopPropagation(); clear(); } }} leftSlot={ } rightSlot={ text === "" ? ( ⌘F ) : ( ) } />
{ try { const written = await exportHar(query == null ? {} : { filter: query }, "flows.har"); if (written != null) { showToast({ message: written === 1 ? "Exported 1 flow as HAR" : `Exported ${written} flows as HAR`, }); } } catch (err) { showToast({ message: `Failed to export HAR: ${String(err)}`, color: "danger" }); } }} />
); });