v3: search engine, responsive header with compact user menu
This commit is contained in:
75
src/components/SearchBar.tsx
Normal file
75
src/components/SearchBar.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
import { type FormEvent, useEffect, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
|
||||
interface SearchBarProps {
|
||||
collapsible?: boolean;
|
||||
}
|
||||
|
||||
export function SearchBar({ collapsible = false }: SearchBarProps) {
|
||||
const [value, setValue] = useState(
|
||||
() => new URLSearchParams(location.search).get("q") ?? "",
|
||||
);
|
||||
const [expanded, setExpanded] = useState(!collapsible);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (expanded) inputRef.current?.focus();
|
||||
}, [expanded]);
|
||||
|
||||
function handleIconClick() {
|
||||
if (!collapsible) return;
|
||||
if (expanded) {
|
||||
setExpanded(false);
|
||||
setValue("");
|
||||
} else {
|
||||
setExpanded(true);
|
||||
}
|
||||
}
|
||||
|
||||
function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
const q = value.trim();
|
||||
if (!q) return;
|
||||
navigate(`/search?q=${encodeURIComponent(q)}&tab=dumps`);
|
||||
if (collapsible) {
|
||||
setExpanded(false);
|
||||
setValue("");
|
||||
}
|
||||
}
|
||||
|
||||
function handleKeyDown(e: React.KeyboardEvent) {
|
||||
if (e.key === "Escape" && collapsible) {
|
||||
setExpanded(false);
|
||||
setValue("");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
className={`search-bar${collapsible ? " search-bar--collapsible" : ""}${expanded ? " search-bar--expanded" : ""}`}
|
||||
onSubmit={handleSubmit}
|
||||
role="search"
|
||||
>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="search"
|
||||
className="search-bar-input"
|
||||
placeholder="Search dumps, users, playlists…"
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
aria-label="Search"
|
||||
tabIndex={expanded ? 0 : -1}
|
||||
/>
|
||||
<button
|
||||
type={expanded && !collapsible ? "submit" : "button"}
|
||||
className="search-bar-btn"
|
||||
aria-label={expanded ? "Submit search" : "Open search"}
|
||||
onClick={collapsible ? handleIconClick : undefined}
|
||||
>
|
||||
🔍
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user