From b0a2a834ef3ffe47367b516982104444942b17aa Mon Sep 17 00:00:00 2001 From: Jared Schoeny Date: Sun, 22 Nov 2026 20:23:47 -0700 Subject: [PATCH] Allow uncurated hacks to be searchable (#129) --- src/app/discover/actions.ts | 20 ++-- src/app/discover/page.tsx | 3 +- src/app/faq/entries.md | 9 +- src/components/Discover/DiscoverBrowser.tsx | 117 +++++++++++++------- src/types/discover.ts | 5 + src/utils/hackNameSearch.test.ts | 52 +++++++++ src/utils/hackNameSearch.ts | 22 ++++ 7 files changed, 180 insertions(+), 48 deletions(-) create mode 100644 src/utils/hackNameSearch.test.ts create mode 100644 src/utils/hackNameSearch.ts diff --git a/src/app/discover/actions.ts b/src/app/discover/actions.ts index 2476b08..aa3d408 100644 --- a/src/app/discover/actions.ts +++ b/src/app/discover/actions.ts @@ -3,7 +3,7 @@ import { createServiceClient } from "@/utils/supabase/server"; import { sortOrderedTags, type OrderedTag, getCoverUrls } from "@/utils/format"; import { fetchInChunks } from "@/utils/array"; import type { Tables } from "@/types/db"; -import type { DiscoverData } from "@/types/discover"; +import type { DiscoverData, DiscoverHack } from "@/types/discover"; import { resolveHackDisplayVersion } from "@/utils/patches/hack-display-version"; import { AI_SELECT, aiDisclosureFromRow } from "@/utils/aiDisclosure"; @@ -45,10 +45,9 @@ async function generateDiscoverData(): Promise { const { data: rows, error: hacksError } = await supabase .from("hacks") .select( - `slug,title,summary,base_rom,downloads,created_by,current_patch,custom_version_name,original_author,curated_at,is_archive,completion_status,${AI_SELECT}`, + `slug,title,summary,base_rom,downloads,created_by,current_patch,custom_version_name,original_author,curated,curated_at,approved_at,is_archive,completion_status,${AI_SELECT}`, ) .eq("approved", true) - .eq("curated", true) .eq("is_archive", false) .is("deleted_at", null); if (hacksError) throw hacksError; @@ -216,7 +215,9 @@ async function generateDiscoverData(): Promise { ]), ); - const hacks = rows.map((row) => { + const hacks: DiscoverHack[] = []; + const searchOnly: DiscoverHack[] = []; + for (const row of rows) { const currentPatch = row.current_patch ? patchesById.get(row.current_patch) : undefined; @@ -224,7 +225,7 @@ async function generateDiscoverData(): Promise { const downloads = row.downloads ?? 0; const recentDownloads = recentDownloadsBySlug.get(row.slug) ?? 0; - return { + (row.curated ? hacks : searchOnly).push({ slug: row.slug, title: row.title, author: row.original_author || usernameById.get(row.created_by) || "Unknown", @@ -243,14 +244,17 @@ async function generateDiscoverData(): Promise { is_archive: false, completion_status: row.completion_status, curatedAt: row.curated_at, + // approved_at holds UTC but has no time zone, which Date.parse would read as local time. + approvedAt: row.approved_at && `${row.approved_at}Z`, publishedAt: currentPatch?.published_at ?? null, trendingScore: recentDownloads + 8 * Math.log(downloads + 1), ai: aiDisclosureFromRow(row)?.levels ?? null, - }; - }); + }); + } return { hacks, + searchOnly, generatedAt, tagGroups, ungroupedTags, @@ -260,7 +264,7 @@ async function generateDiscoverData(): Promise { const getCachedDiscoverData = cache( generateDiscoverData, // Bump the version when DiscoverHack's shape changes, so a deploy never reads the old shape. - ["discover-data", "v3"], + ["discover-data", "v4"], { revalidate: DISCOVER_REVALIDATE_SECONDS, tags: ["discover"], diff --git a/src/app/discover/page.tsx b/src/app/discover/page.tsx index 2f71384..70a6084 100644 --- a/src/app/discover/page.tsx +++ b/src/app/discover/page.tsx @@ -14,7 +14,7 @@ export const metadata: Metadata = { }; export default async function DiscoverPage() { - const { hacks, generatedAt, tagGroups, ungroupedTags } = await getDiscoverData(); + const { hacks, searchOnly, generatedAt, tagGroups, ungroupedTags } = await getDiscoverData(); return (
@@ -26,6 +26,7 @@ export default async function DiscoverPage() {
; @@ -56,26 +60,50 @@ interface DiscoverBrowserProps { } /** - * One predicate for the results and the phone sheet's "Show N hacks", so they can't disagree. + * One set of predicates for the results and the phone sheet's "Show N hacks", so they can't disagree. + * Curated hacks match the query anywhere; search-only hacks need a name lookup. Both take every filter. * Tags are OR within a category and AND across them; "Complete" also matches hacks without a status. */ function hackMatcher(f: FilterState, query: string, groups: TagGroup[], readyBaseRomIds: Set) { const q = query.toLowerCase(); const wanted = groups.map((g) => g.tags.filter((t) => f.tags.includes(t))).filter((picked) => picked.length > 0); - return (h: DiscoverHack) => - (!q || - h.title.toLowerCase().includes(q) || - h.author.toLowerCase().includes(q) || - !!h.summary?.toLowerCase().includes(q) || - h.tags.some((t) => t.name.toLowerCase().includes(q))) && + const passesFilters = (h: DiscoverHack) => wanted.every((picked) => picked.some((t) => h.tags.some((tag) => tag.name === t))) && (f.baseRoms.length === 0 || (!!h.baseRomId && f.baseRoms.includes(h.baseRomId))) && (f.completionStatuses.length === 0 || f.completionStatuses.includes(h.completion_status ?? "Complete")) && (!f.onlyReady || (!h.is_archive && !!h.baseRomId && readyBaseRomIds.has(h.baseRomId))) && matchesAiFilter(h.ai, f.ai); + return { + curated: (h: DiscoverHack) => + (!q || + h.title.toLowerCase().includes(q) || + h.author.toLowerCase().includes(q) || + !!h.summary?.toLowerCase().includes(q) || + h.tags.some((t) => t.name.toLowerCase().includes(q))) && + passesFilters(h), + searchOnly: (h: DiscoverHack) => matchesHackName(query, h) && passesFilters(h), + }; } -export default function DiscoverBrowser({ catalog, generatedAt, initialState, tagGroups, ungroupedTags }: DiscoverBrowserProps) { +/** Newest first by curation date. Uncurated hacks have none, so they use their approval date. */ +const listedAt = (h: DiscoverHack) => Date.parse(h.curatedAt ?? h.approvedAt ?? "") || 0; + +function compareHacks(sort: DiscoverSortOption) { + return (a: DiscoverHack, b: DiscoverHack) => { + if (sort === "popular") return b.downloads - a.downloads; + if (sort === "new") return listedAt(b) - listedAt(a); + if (sort === "updated") { + if (!a.publishedAt && !b.publishedAt) return 0; + if (!a.publishedAt) return 1; + if (!b.publishedAt) return -1; + return Date.parse(b.publishedAt) - Date.parse(a.publishedAt); + } + if (sort === "alpha") return a.title.localeCompare(b.title); + return b.trendingScore - a.trendingScore; + }; +} + +export default function DiscoverBrowser({ catalog, searchOnly, generatedAt, initialState, tagGroups, ungroupedTags }: DiscoverBrowserProps) { const [query, setQuery] = React.useState(initialState.query); const [selectedTags, setSelectedTags] = React.useState(() => [...initialState.tags]); const [selectedBaseRoms, setSelectedBaseRoms] = React.useState(() => [...initialState.baseRoms]); @@ -160,21 +188,13 @@ export default function DiscoverBrowser({ catalog, generatedAt, initialState, ta syncUrl({ ...nextState, page: 1 }, "replace"); }, [currentUrlState, initialUrlStateApplied, selectedTags.length, syncUrl, validTagNames]); - const filtered = React.useMemo(() => { + // One list that pages as a whole: curated matches, then the search-only group from `curatedCount` on. + const { filtered, curatedCount } = React.useMemo(() => { const matches = hackMatcher({ tags: selectedTags, baseRoms: selectedBaseRoms, completionStatuses: selectedCompletionStatuses, onlyReady, ai }, query, groups, readyBaseRomIds); - return catalog.filter(matches).sort((a, b) => { - if (sort === "popular") return b.downloads - a.downloads; - if (sort === "new") return (b.curatedAt ? Date.parse(b.curatedAt) : 0) - (a.curatedAt ? Date.parse(a.curatedAt) : 0); - if (sort === "updated") { - if (!a.publishedAt && !b.publishedAt) return 0; - if (!a.publishedAt) return 1; - if (!b.publishedAt) return -1; - return Date.parse(b.publishedAt) - Date.parse(a.publishedAt); - } - if (sort === "alpha") return a.title.localeCompare(b.title); - return b.trendingScore - a.trendingScore; - }); - }, [ai, catalog, groups, onlyReady, query, readyBaseRomIds, selectedBaseRoms, selectedCompletionStatuses, selectedTags, sort]); + const compare = compareHacks(sort); + const curated = catalog.filter(matches.curated).sort(compare); + return { filtered: [...curated, ...searchOnly.filter(matches.searchOnly).sort(compare)], curatedCount: curated.length }; + }, [ai, catalog, groups, onlyReady, query, readyBaseRomIds, searchOnly, selectedBaseRoms, selectedCompletionStatuses, selectedTags, sort]); const showSkeleton = !initialUrlStateApplied || !aiLoaded || (onlyReady && baseRomsLoading); const totalPages = Math.max(1, Math.ceil(filtered.length / HACKS_PER_PAGE)); @@ -189,6 +209,9 @@ export default function DiscoverBrowser({ catalog, generatedAt, initialState, ta const startIndex = (currentPage - 1) * HACKS_PER_PAGE; const endIndex = Math.min(filtered.length, startIndex + HACKS_PER_PAGE); const paginated = React.useMemo(() => filtered.slice(startIndex, endIndex), [filtered, startIndex, endIndex]); + const pageSplit = Math.min(Math.max(curatedCount - startIndex, 0), paginated.length); + const pageCurated = paginated.slice(0, pageSplit); + const pageSearchOnly = paginated.slice(pageSplit); const scrollToResults = React.useCallback(() => { requestAnimationFrame(() => listRef.current?.scrollIntoView({ block: "start" })); @@ -253,10 +276,11 @@ export default function DiscoverBrowser({ catalog, generatedAt, initialState, ta const [sheet, setSheet] = React.useState(false); const [draft, setDraft] = React.useState(filterState); const filterBtnRef = React.useRef(null); - const draftTotal = React.useMemo( - () => (sheet ? catalog.filter(hackMatcher(draft, query, groups, readyBaseRomIds)).length : 0), - [catalog, draft, groups, query, readyBaseRomIds, sheet] - ); + const draftTotal = React.useMemo(() => { + if (!sheet) return 0; + const matches = hackMatcher(draft, query, groups, readyBaseRomIds); + return catalog.filter(matches.curated).length + searchOnly.filter(matches.searchOnly).length; + }, [catalog, draft, groups, query, readyBaseRomIds, searchOnly, sheet]); const openSheet = (focusAi = false) => { setDraft(filterState); @@ -361,6 +385,20 @@ export default function DiscoverBrowser({ catalog, generatedAt, initialState, ta ); const pager = totalPages > 1; + const hackList = (hacks: DiscoverHack[], label: string) => + view === "grid" ? ( +
+ {hacks.map((hack) => ( + + ))} +
+ ) : ( +
+ {hacks.map((hack) => ( + + ))} +
+ ); return (
@@ -545,18 +583,21 @@ export default function DiscoverBrowser({ catalog, generatedAt, initialState, ta

{pager && }
- {view === "grid" ? ( -
- {paginated.map((hack) => ( - - ))} -
- ) : ( -
- {paginated.map((hack) => ( - - ))} -
+ {pageCurated.length > 0 && hackList(pageCurated, "Hacks")} + {pageSearchOnly.length > 0 && ( + // The rule only separates it from curated cards above; a page that opens with the group skips it. +
0 ? "mt-10 border-t border-line pt-5" : "mt-5"}> +

+ Outside the curated collection +

+

+ These hacks have public pages and show up here when you search by title or creator.{" "} + + What does curated mean? + +

+ {hackList(pageSearchOnly, "Hacks outside the curated collection")} +
)} {pager && (
diff --git a/src/types/discover.ts b/src/types/discover.ts index c44cf67..bab7b94 100644 --- a/src/types/discover.ts +++ b/src/types/discover.ts @@ -5,6 +5,8 @@ export type DiscoverSortOption = "trending" | "popular" | "new" | "updated" | "a export interface DiscoverHack extends HackCardAttributes { curatedAt: string | null; + /** Sorts uncurated hacks under "Newest", which have no curation date. */ + approvedAt: string | null; publishedAt: string | null; trendingScore: number; /** The AI label's level per area, for the AI filter; null until the creator fills it in. */ @@ -12,7 +14,10 @@ export interface DiscoverHack extends HackCardAttributes { } export interface DiscoverData { + /** Curated hacks: everything Discover and the homepage list. */ hacks: DiscoverHack[]; + /** Approved hacks outside the curated collection. Discover shows them only when a search looks one up by name. */ + searchOnly: DiscoverHack[]; generatedAt: string; tagGroups: Record; ungroupedTags: string[]; diff --git a/src/utils/hackNameSearch.test.ts b/src/utils/hackNameSearch.test.ts new file mode 100644 index 0000000..3eba83b --- /dev/null +++ b/src/utils/hackNameSearch.test.ts @@ -0,0 +1,52 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { matchesHackName } from "./hackNameSearch.ts"; + +const crest = { title: "Emerald Crest", author: "@mossfern" }; + +test("matches part of the title once the query has 5 characters", () => { + assert.equal(matchesHackName("emera", crest), true); + assert.equal(matchesHackName("ld cr", crest), true); +}); + +test("ignores part of the title under 5 characters", () => { + assert.equal(matchesHackName("emer", crest), false); + assert.equal(matchesHackName("rest", crest), false); +}); + +test("matches the exact title at any length", () => { + assert.equal(matchesHackName("gaia", { title: "Gaia", author: "@someone" }), true); + assert.equal(matchesHackName("@", { title: "@", author: "@someone" }), true); +}); + +test("counts the minimum in characters, not UTF-16 units", () => { + assert.equal(matchesHackName("🔥🔥a", { title: "🔥🔥alpha", author: "@someone" }), false); + assert.equal(matchesHackName("🔥🔥alp", { title: "🔥🔥alpha", author: "@someone" }), true); +}); + +test("counts the minimum before lowercasing", () => { + // "İ" lowercases to two code points, which would make this 4-letter query look like 5. + assert.equal(matchesHackName("MİST", { title: "MİST Valley", author: "@someone" }), false); +}); + +test("matches the exact author with or without the @", () => { + assert.equal(matchesHackName("mossfern", crest), true); + assert.equal(matchesHackName("@mossfern", crest), true); + assert.equal(matchesHackName("@ax", { title: "Emerald Crest", author: "@ax" }), true); +}); + +test("ignores part of the author", () => { + assert.equal(matchesHackName("mossf", crest), false); + assert.equal(matchesHackName("@moss", crest), false); +}); + +test("ignores case and surrounding spaces", () => { + assert.equal(matchesHackName(" EMERALD crest ", crest), true); + assert.equal(matchesHackName(" @MossFern", crest), true); +}); + +test("an empty or blank query matches nothing", () => { + assert.equal(matchesHackName("", crest), false); + assert.equal(matchesHackName(" ", crest), false); + assert.equal(matchesHackName("@", { title: "Emerald Crest", author: "" }), false); +}); diff --git a/src/utils/hackNameSearch.ts b/src/utils/hackNameSearch.ts new file mode 100644 index 0000000..23bf6de --- /dev/null +++ b/src/utils/hackNameSearch.ts @@ -0,0 +1,22 @@ +/** The shortest query that can match part of a title. Shorter queries need the exact title or author. */ +export const MIN_PARTIAL_TITLE_QUERY = 5; + +const normalize = (text: string) => text.trim().toLowerCase(); +const withoutAt = (name: string) => name.replace(/^@/, ""); + +/** + * Whether a Discover search is looking up this hack by name. Uncurated hacks only show up for + * these lookups, never for browsing searches like a tag or a word from the summary. + * Matches part of the title once the query is long enough, or the exact title or author at any + * length. Case never matters, and the author's leading `@` is optional. + */ +export function matchesHackName(query: string, hack: { title: string; author: string }) { + const q = normalize(query); + if (!q) return false; + const title = normalize(hack.title); + if (title === q) return true; + const name = withoutAt(q); + if (name && withoutAt(normalize(hack.author)) === name) return true; + // Counted by character before lowercasing, so emoji and letters like "İ" don't pass the minimum early. + return [...query.trim()].length >= MIN_PARTIAL_TITLE_QUERY && title.includes(q); +}