search: real autocomplete previews + clearer placeholder

PLACEHOLDER: "Search broadcast news…" → "Search articles, gear,
vendors". Drops the weird ellipsis and the "we're a broadcast site
so 'broadcast news' is redundant" feel.

API (/api/search/suggest):
- Match expanded from {title, author_name} to
  {title, excerpt, content, author_name} — surfaces hits when the
  phrase lives deep in the article body.
- Returns a snippet object {text, matchStart, matchEnd} sliced
  from the first hit (HTML-stripped), with ~80 chars of context on
  either side and "…" markers when truncated.
- Returns matched_in: 'title' | 'excerpt' | 'content' | 'author' so
  the UI can show "match in article body" / "match in byline".
- Returns date + author_name on each result.

UI dropdown (Header.tsx):
- Each suggestion now renders three rows:
  1) Title (bold) + category chip
  2) Snippet with the matched substring wrapped in <mark>
  3) Author byline + date + (if match wasn't in title) a tag
     showing where the match occurred
- Vertical stacking with a colored left-border on hover so the
  active suggestion is visible.

CSS:
- Stack item layout, snippet with -webkit-line-clamp:2 so long
  matches don't overflow.
- <mark> background uses the accent blue at 28% so the highlight
  reads against the dark card.
This commit is contained in:
Ryan Salazar
2026-05-20 16:22:04 +00:00
parent c1705e1a4b
commit 418027b469
3 changed files with 201 additions and 27 deletions

View File

@@ -15,6 +15,37 @@ function client() {
});
}
// Extract a short snippet around the first match of `needle` inside the
// (HTML-stripped) `haystack`. Returns the substring + the absolute offset
// of the match within the snippet, so the caller can highlight it.
function buildSnippet(
haystack: string,
needle: string,
radius = 80,
): { text: string; matchStart: number; matchEnd: number } | null {
if (!haystack || !needle) return null;
const stripped = haystack
.replace(/<[^>]+>/g, " ")
.replace(/&nbsp;/g, " ")
.replace(/&amp;/g, "&")
.replace(/&#39;/g, "'")
.replace(/&quot;/g, '"')
.replace(/\s+/g, " ")
.trim();
const idx = stripped.toLowerCase().indexOf(needle.toLowerCase());
if (idx === -1) return null;
const start = Math.max(0, idx - radius);
const end = Math.min(stripped.length, idx + needle.length + radius);
const prefix = start > 0 ? "… " : "";
const suffix = end < stripped.length ? " …" : "";
const text = prefix + stripped.slice(start, end) + suffix;
return {
text,
matchStart: prefix.length + (idx - start),
matchEnd: prefix.length + (idx - start) + needle.length,
};
}
export async function GET(req: Request) {
const { searchParams } = new URL(req.url);
const q = (searchParams.get("q") || "").trim();
@@ -25,11 +56,21 @@ export async function GET(req: Request) {
const like = `%${q.replace(/[%_]/g, " ")}%`;
const sb = client();
// Match against title, excerpt, content, AND author name (was just
// title+author). Content match is what surfaces hits when the phrase
// lives deep in the article body.
const { data, error } = await sb
.from("wp_imported_posts")
.select("wp_slug, title, category")
.select("wp_slug, title, excerpt, content, category, wp_published_at, author_name")
.eq("status", "published")
.or(`title.ilike.${like},author_name.ilike.${like}`)
.or(
[
`title.ilike.${like}`,
`excerpt.ilike.${like}`,
`content.ilike.${like}`,
`author_name.ilike.${like}`,
].join(","),
)
.order("wp_published_at", { ascending: false, nullsFirst: false })
.limit(limit);
@@ -37,12 +78,53 @@ export async function GET(req: Request) {
return NextResponse.json({ items: [], error: error.message }, { status: 500 });
}
const items = (data || []).map((r: any) => ({
slug: r.wp_slug,
title: r.title,
category: r.category,
href: `/news/${r.wp_slug}`,
}));
// Build each item with title, category, date, and a snippet that
// shows WHERE the match happened. Snippet source priority:
// title → excerpt → content → author_name.
const items = (data || []).map((r: any) => {
let snippet: { text: string; matchStart: number; matchEnd: number } | null = null;
let matchedIn: "title" | "excerpt" | "content" | "author" | null = null;
const titleHit = buildSnippet(r.title || "", q, 30);
if (titleHit) {
snippet = titleHit;
matchedIn = "title";
} else {
const exHit = buildSnippet(r.excerpt || "", q, 70);
if (exHit) {
snippet = exHit;
matchedIn = "excerpt";
} else {
const ctHit = buildSnippet(r.content || "", q, 80);
if (ctHit) {
snippet = ctHit;
matchedIn = "content";
} else if ((r.author_name || "").toLowerCase().includes(q.toLowerCase())) {
const a = r.author_name || "";
const i = a.toLowerCase().indexOf(q.toLowerCase());
snippet = { text: a, matchStart: i, matchEnd: i + q.length };
matchedIn = "author";
}
}
}
return {
slug: r.wp_slug,
title: r.title,
category: r.category,
date: r.wp_published_at
? new Date(r.wp_published_at).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
})
: null,
author_name: r.author_name || null,
snippet,
matched_in: matchedIn,
href: `/news/${r.wp_slug}`,
};
});
return NextResponse.json(
{ items, query: q },

View File

@@ -37,7 +37,18 @@ export default function Header() {
const [mobileOpen, setMobileOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState("");
const [searchFocused, setSearchFocused] = useState(false);
const [suggestions, setSuggestions] = useState<Array<{ slug: string; title: string; category?: string; href: string }>>([]);
const [suggestions, setSuggestions] = useState<
Array<{
slug: string;
title: string;
category?: string;
date?: string | null;
author_name?: string | null;
snippet?: { text: string; matchStart: number; matchEnd: number } | null;
matched_in?: "title" | "excerpt" | "content" | "author" | null;
href: string;
}>
>([]);
const [suggestOpen, setSuggestOpen] = useState(false);
const submitSearch = () => {
@@ -512,7 +523,7 @@ export default function Header() {
<input
ref={searchRef}
type="search"
placeholder="Search broadcast news…"
placeholder="Search articles, gear, vendors"
value={searchQuery}
onChange={(e) => setSearchQuery(e?.target?.value)}
onFocus={() => { setSearchFocused(true); if (suggestions.length > 0) setSuggestOpen(true); }}
@@ -547,18 +558,42 @@ export default function Header() {
id="bb-search-suggest"
role="listbox"
className="bb-browse-search-suggest">
{suggestions.map((s) => (
<li key={s.slug} role="option">
<Link
href={s.href}
className="bb-browse-search-suggest-item"
onMouseDown={(e) => e.preventDefault()}
onClick={() => { setSuggestOpen(false); setSearchQuery(""); }}>
<span className="bb-browse-search-suggest-title">{s.title}</span>
{s.category && <span className="bb-browse-search-suggest-cat">{s.category}</span>}
</Link>
</li>
))}
{suggestions.map((s) => {
const snippet = s.snippet;
const beforeMatch = snippet?.text.slice(0, snippet.matchStart) || "";
const matchText = snippet?.text.slice(snippet.matchStart, snippet.matchEnd) || "";
const afterMatch = snippet?.text.slice(snippet.matchEnd) || "";
return (
<li key={s.slug} role="option">
<Link
href={s.href}
className="bb-browse-search-suggest-item"
onMouseDown={(e) => e.preventDefault()}
onClick={() => { setSuggestOpen(false); setSearchQuery(""); }}>
<div className="bb-browse-search-suggest-row1">
<span className="bb-browse-search-suggest-title">{s.title}</span>
{s.category && <span className="bb-browse-search-suggest-cat">{s.category}</span>}
</div>
{snippet && s.matched_in !== "title" && (
<div className="bb-browse-search-suggest-snippet">
{beforeMatch}
<mark className="bb-browse-search-suggest-mark">{matchText}</mark>
{afterMatch}
</div>
)}
{(s.date || s.author_name) && (
<div className="bb-browse-search-suggest-meta">
{s.author_name && <span>{s.author_name}</span>}
{s.author_name && s.date && <span className="bb-dot">·</span>}
{s.date && <time>{s.date}</time>}
{s.matched_in === "author" && <span className="bb-browse-search-suggest-mark-tag">match in byline</span>}
{s.matched_in === "content" && <span className="bb-browse-search-suggest-mark-tag">match in article body</span>}
</div>
)}
</Link>
</li>
);
})}
<li role="option" className="bb-browse-search-suggest-all">
<button
type="button"

View File

@@ -867,22 +867,31 @@ h1, h2, h3 {
.bb-browse-search-suggest-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 8px 14px;
flex-direction: column;
gap: 4px;
padding: 10px 14px;
font-family: var(--font-body);
font-size: 13px;
color: #d1d8e4;
text-decoration: none;
transition: background var(--transition-fast), color var(--transition-fast);
border-left: 2px solid transparent;
}
.bb-browse-search-suggest-item:hover,
.bb-browse-search-suggest-item:focus-visible {
background: rgba(59, 130, 246, 0.12);
background: rgba(59, 130, 246, 0.10);
color: #ffffff;
outline: none;
border-left-color: var(--color-accent);
}
.bb-browse-search-suggest-row1 {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
min-width: 0;
}
.bb-browse-search-suggest-title {
@@ -891,6 +900,8 @@ h1, h2, h3 {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-weight: 600;
color: #e6ecf3;
}
.bb-browse-search-suggest-cat {
@@ -904,6 +915,52 @@ h1, h2, h3 {
opacity: 0.75;
}
.bb-browse-search-suggest-snippet {
font-size: 12px;
color: #98a3b3;
line-height: 1.4;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.bb-browse-search-suggest-mark {
background: rgba(59, 130, 246, 0.28);
color: #ffffff;
padding: 0 2px;
border-radius: 2px;
font-weight: 600;
}
.bb-browse-search-suggest-meta {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
font-size: 11px;
color: #6b7585;
font-family: var(--font-mono);
letter-spacing: 0.02em;
}
.bb-browse-search-suggest-meta .bb-dot {
opacity: 0.5;
}
.bb-browse-search-suggest-mark-tag {
display: inline-block;
margin-left: 4px;
padding: 1px 6px;
background: rgba(59, 130, 246, 0.10);
color: var(--color-accent);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
border-radius: 2px;
}
.bb-browse-search-suggest-all {
border-top: 1px solid #1f2937;
margin-top: 2px;