Files
muse/web/components/search-bar.tsx
T
Aryan SinghandClaude Opus 5 205e0a44b8 Add review, discover, email; rebuild the design system
Three features and a typographic pass over everything.

REVIEW. Picking a file and trusting it are different questions, so they now
use different numbers. The existing rank decides which candidate to fetch and
is right to weigh peer upload slots and queue length -- but none of that says
anything about whether the file is the correct recording, and a fast peer must
not be able to raise the confidence of a wrong match. So confidence() scores
the filename alone: title 0.75, artist 0.25, album +0.05, and a variant tag
you did not ask for multiplies by 0.8 AND caps below the auto threshold.

Confidence gates the IMPORT, not the download. The transfer completes either
way and the file waits in downloads, so approving is instant and rejecting is
a delete. Holding the transfer instead would mean the peer is usually gone by
the time anyone looks.

The two cases it exists for: "02 Creep.flac" in an unsorted folder scores 0.75
-- title exactly right, artist simply absent, the commonest honest case there
is -- and must be reviewed rather than binned. And "Creep (Live at
Glastonbury)" scores 0.80 with BOTH artist and title perfect; the cap is what
stops a live recording auto-filing over the studio version. Ask for "Creep
(Acoustic)" and it auto-imports at 0.97, because then the variant is the
request.

DISCOVER. Related artists seeded from what you have actually imported, plus a
recap of top artists, genres and decades. Built on muse's own request history,
never on listening data: Navidrome owns play counts and history, and a second
source of truth for those would disagree with the one you listen through.

EMAIL. Optional, off unless MUSE_SMTP_HOST is set. Sends on import and on
review-needed. smtplib is blocking so it runs off the event loop, and every
failure is logged and swallowed -- a notification is never worth failing an
import over. Google accounts need no configuration, since the identity is an
address. Each user owns their own setting under Settings, deliberately not an
admin route: an address you cannot change yourself is someone else's chore.

DESIGN. A real type scale (display/title/headline/body/callout/caption) whose
tracking tightens as size grows, which is the single biggest tell of typography
nobody set. Specular top edges on glass surfaces -- blur alone reads as a grey
rectangle. A two-part elevation scale, contact shadow plus soft light. Semantic
colours are now per-theme: the amber tuned for the dark background failed
contrast outright on white, which was exactly the text a reviewer most needs to
read. The tab underline became a sliding pill so the eye tracks one object, and
Review only appears when something is actually waiting.

Add tests/test_matching.py: 13 assertions on the confidence bands rather than
the exact scores. 90 tests pass across the three suites.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-05 02:10:33 -05:00

234 lines
8.1 KiB
TypeScript

"use client";
import * as React from "react";
import { AnimatePresence, motion } from "framer-motion";
import { Search, X, Loader2 } from "lucide-react";
import { api, type Suggestions } from "@/lib/api";
import { cn } from "@/lib/utils";
type Item = { kind: "track" | "album" | "artist"; label: string; sub: string; cover: string | null; meta?: string; run: () => void };
export function SearchBar({
busy,
onSearch,
onAlbum,
onArtist,
}: {
busy?: boolean;
onSearch: (q: string) => void;
onAlbum: (id: number) => void;
onArtist: (id: number) => void;
}) {
const [q, setQ] = React.useState("");
const [items, setItems] = React.useState<Item[]>([]);
const [open, setOpen] = React.useState(false);
const [sel, setSel] = React.useState(-1);
const inputRef = React.useRef<HTMLInputElement>(null);
// Debounced so a fast typist makes one upstream call, not eight. The
// AbortController matters more than the delay: without it a slow response
// to "rad" can land after "radiohead" and repopulate the stale list.
React.useEffect(() => {
const v = q.trim();
if (v.length < 2) {
setItems([]);
setOpen(false);
return;
}
const ac = new AbortController();
const t = setTimeout(async () => {
try {
const d: Suggestions = await api.suggest(v, ac.signal);
const next: Item[] = [
...d.tracks.map((t) => ({
kind: "track" as const,
label: t.title,
sub: t.artist,
cover: t.cover,
run: () => {
const nq = `${t.artist} ${t.title}`;
setQ(nq);
setOpen(false);
onSearch(nq);
},
})),
...d.albums.map((a) => ({
kind: "album" as const,
label: a.title,
sub: a.artist,
cover: a.cover,
meta: a.nb_tracks ? `${a.nb_tracks} tracks` : "",
run: () => {
setOpen(false);
onAlbum(a.album_id);
},
})),
...d.artists.map((a) => ({
kind: "artist" as const,
label: a.name,
sub: a.nb_album ? `${a.nb_album} releases` : "Artist",
cover: a.cover,
run: () => {
setOpen(false);
onArtist(a.artist_id);
},
})),
];
setItems(next);
setSel(-1);
setOpen(next.length > 0);
} catch {
/* aborted or offline — leave the previous list alone */
}
}, 180);
return () => {
clearTimeout(t);
ac.abort();
};
}, [q, onSearch, onAlbum, onArtist]);
// "/" focuses search, the way every music app does.
React.useEffect(() => {
const onKey = (e: KeyboardEvent) => {
const tag = (document.activeElement as HTMLElement)?.tagName;
if (e.key === "/" && !/^(INPUT|TEXTAREA)$/.test(tag)) {
e.preventDefault();
inputRef.current?.focus();
}
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, []);
const key = (e: React.KeyboardEvent) => {
if (e.key === "ArrowDown") {
e.preventDefault();
setSel((s) => (items.length ? (s + 1) % items.length : -1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setSel((s) => (items.length ? (s - 1 + items.length) % items.length : -1));
} else if (e.key === "Escape") {
setOpen(false);
} else if (e.key === "Enter") {
e.preventDefault();
if (sel >= 0 && items[sel]) items[sel].run();
else {
setOpen(false);
onSearch(q.trim());
}
}
};
const groups: { title: string; kind: Item["kind"] }[] = [
{ title: "Songs", kind: "track" },
{ title: "Albums", kind: "album" },
{ title: "Artists", kind: "artist" },
];
return (
<div className="relative z-50">
<div
className={cn(
"glass flex items-center gap-3 h-[50px] px-3.5 rounded-[20px]",
"transition-all duration-250 ease-glass",
"focus-within:border-accent-line focus-within:bg-glass-hi",
"focus-within:shadow-[0_0_0_4px_var(--color-accent-soft)]",
)}
>
<Search className="w-[18px] h-[18px] shrink-0 text-dim" />
<input
ref={inputRef}
type="search"
value={q}
onChange={(e) => setQ(e.target.value)}
onKeyDown={key}
onFocus={() => items.length && setOpen(true)}
onBlur={() => setTimeout(() => setOpen(false), 120)}
placeholder="Search songs, albums, artists…"
aria-label="Search"
autoComplete="off"
spellCheck={false}
className="flex-1 min-w-0 bg-transparent border-0 outline-none text-base
font-medium tracking-[-0.1px] text-ink placeholder:text-dim
placeholder:font-normal"
/>
{busy && <Loader2 className="w-4 h-4 shrink-0 text-accent animate-spin" />}
{q && !busy && (
<button
onClick={() => {
setQ("");
inputRef.current?.focus();
}}
aria-label="Clear search"
className="w-6.5 h-6.5 shrink-0 grid place-items-center rounded-full
glass-hi text-dim hover:text-ink cursor-pointer"
>
<X className="w-3.5 h-3.5" />
</button>
)}
</div>
<AnimatePresence>
{open && items.length > 0 && (
<motion.div
initial={{ opacity: 0, y: -8, scale: 0.985 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: -8, scale: 0.985 }}
transition={{ duration: 0.18, ease: [0.22, 0.9, 0.28, 1] }}
className="sheet absolute top-[calc(100%+8px)] left-0 right-0 z-60 p-1.5
rounded-[20px] max-h-[min(64vh,460px)] overflow-y-auto no-scrollbar"
>
{groups.map((g) => {
const rows = items.filter((i) => i.kind === g.kind);
if (!rows.length) return null;
return (
<div key={g.kind}>
<div className="px-2.5 pt-2 pb-1 text-caption font-bold uppercase tracking-[0.9px] text-dim">
{g.title}
</div>
{rows.map((it) => {
const idx = items.indexOf(it);
return (
<div
key={`${g.kind}-${idx}`}
role="option"
aria-selected={idx === sel}
onMouseDown={(e) => {
e.preventDefault();
it.run();
}}
onMouseEnter={() => setSel(idx)}
className={cn(
"flex items-center gap-3 px-2.5 py-2 rounded-xl cursor-pointer transition-colors",
idx === sel && "bg-accent-soft",
)}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={it.cover ?? ""}
alt=""
loading="lazy"
className={cn(
"w-[38px] h-[38px] shrink-0 object-cover bg-faint",
it.kind === "artist" ? "rounded-full" : "rounded-lg",
)}
onError={(e) => (e.currentTarget.style.visibility = "hidden")}
/>
<div className="flex-1 min-w-0">
<div className="text-sm font-medium clamp1">{it.label}</div>
<div className="text-xs text-dim clamp1">{it.sub}</div>
</div>
{it.meta && <div className="shrink-0 text-caption text-dim">{it.meta}</div>}
</div>
);
})}
</div>
);
})}
</motion.div>
)}
</AnimatePresence>
</div>
);
}