Jacksuyu commited on
Commit
af2571a
·
1 Parent(s): 5281f16

Add fuzzy idea search API and home UI

Browse files
app/api/ideas/route.ts CHANGED
@@ -9,6 +9,7 @@ import { auth } from "@/auth";
9
  import { findBlockedContent } from "@/lib/content-moderation";
10
  import { detectMergeTarget } from "@/lib/idea-dedup";
11
  import { buildMeaningfulTitle } from "@/lib/title";
 
12
 
13
  const createIdeaSchema = z.object({
14
  raw_input_text: z.string().min(20).max(3000),
@@ -71,14 +72,21 @@ async function applyMergeSupportVote(ideaId: string, userId: string | null, anon
71
  export async function GET(request: NextRequest) {
72
  const sortParam = request.nextUrl.searchParams.get("sort");
73
  const sort = sortParam === "new" ? "new" : "hot";
 
 
 
 
74
  const rawLimit = Number(request.nextUrl.searchParams.get("limit") || 20);
75
  const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 50) : 20;
76
  const cursor = request.nextUrl.searchParams.get("cursor");
77
  const cursorDate = cursor ? new Date(cursor) : null;
78
 
 
 
 
79
  const ideas = await prisma.idea.findMany({
80
- take: limit + 1,
81
- where: cursorDate && !Number.isNaN(cursorDate.getTime()) ? { createdAt: { lt: cursorDate } } : undefined,
82
  include: {
83
  createdByUser: {
84
  select: { name: true, developerProfile: { select: { displayName: true } } },
@@ -98,10 +106,7 @@ export async function GET(request: NextRequest) {
98
  orderBy: { createdAt: "desc" },
99
  });
100
 
101
- const hasMore = ideas.length > limit;
102
- const page = hasMore ? ideas.slice(0, limit) : ideas;
103
-
104
- const mapped = page.map((idea) => {
105
  const displayTitle = buildMeaningfulTitle({
106
  rawInputText: idea.rawInputText,
107
  title: idea.title,
@@ -135,10 +140,48 @@ export async function GET(request: NextRequest) {
135
  };
136
  });
137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  const items =
139
  sort === "new"
140
- ? mapped
141
- : [...mapped].sort((a, b) => scoreHot(b.upvotesCount, b.createdAt) - scoreHot(a.upvotesCount, a.createdAt));
142
 
143
  const nextCursor = hasMore ? page[page.length - 1]?.createdAt.toISOString() ?? null : null;
144
  return NextResponse.json({ items, nextCursor });
 
9
  import { findBlockedContent } from "@/lib/content-moderation";
10
  import { detectMergeTarget } from "@/lib/idea-dedup";
11
  import { buildMeaningfulTitle } from "@/lib/title";
12
+ import { computeIdeaSearchScore, createTrigrams, normalizeSearchText, tokenizeSearchTerms } from "@/lib/fuzzy-search";
13
 
14
  const createIdeaSchema = z.object({
15
  raw_input_text: z.string().min(20).max(3000),
 
72
  export async function GET(request: NextRequest) {
73
  const sortParam = request.nextUrl.searchParams.get("sort");
74
  const sort = sortParam === "new" ? "new" : "hot";
75
+ const rawQuery = request.nextUrl.searchParams.get("q") || "";
76
+ const query = rawQuery.trim().slice(0, 120);
77
+ const queryTokens = tokenizeSearchTerms(query);
78
+ const normalizedQuery = normalizeSearchText(query);
79
  const rawLimit = Number(request.nextUrl.searchParams.get("limit") || 20);
80
  const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 50) : 20;
81
  const cursor = request.nextUrl.searchParams.get("cursor");
82
  const cursorDate = cursor ? new Date(cursor) : null;
83
 
84
+ const where = cursorDate && !Number.isNaN(cursorDate.getTime()) ? { createdAt: { lt: cursorDate } } : undefined;
85
+ const isSearching = Boolean(normalizedQuery) && queryTokens.length > 0;
86
+
87
  const ideas = await prisma.idea.findMany({
88
+ take: isSearching ? Math.max(limit * 10, 250) : limit + 1,
89
+ where,
90
  include: {
91
  createdByUser: {
92
  select: { name: true, developerProfile: { select: { displayName: true } } },
 
106
  orderBy: { createdAt: "desc" },
107
  });
108
 
109
+ const mapped = ideas.map((idea) => {
 
 
 
110
  const displayTitle = buildMeaningfulTitle({
111
  rawInputText: idea.rawInputText,
112
  title: idea.title,
 
140
  };
141
  });
142
 
143
+ if (isSearching) {
144
+ const searchContext = {
145
+ normalizedQuery,
146
+ tokens: queryTokens,
147
+ trigrams: createTrigrams(normalizedQuery),
148
+ };
149
+
150
+ const scored = mapped
151
+ .map((idea) => ({
152
+ idea,
153
+ score: computeIdeaSearchScore(searchContext, {
154
+ title: idea.title,
155
+ problemStatement: idea.problemStatement,
156
+ rawInputText: idea.rawInputText,
157
+ tags: idea.tags,
158
+ }),
159
+ }))
160
+ .sort((a, b) => {
161
+ if (b.score !== a.score) return b.score - a.score;
162
+ if (sort === "new") return b.idea.createdAt.getTime() - a.idea.createdAt.getTime();
163
+ return scoreHot(b.idea.upvotesCount, b.idea.createdAt) - scoreHot(a.idea.upvotesCount, a.idea.createdAt);
164
+ });
165
+
166
+ const primaryThreshold = queryTokens.length >= 4 ? 0.3 : 0.36;
167
+ const fallbackThreshold = 0.24;
168
+ let filtered = scored.filter((entry) => entry.score >= primaryThreshold);
169
+
170
+ if (filtered.length === 0) {
171
+ filtered = scored.filter((entry) => entry.score >= fallbackThreshold);
172
+ }
173
+
174
+ const items = filtered.slice(0, limit).map((entry) => entry.idea);
175
+ return NextResponse.json({ items, nextCursor: null });
176
+ }
177
+
178
+ const hasMore = mapped.length > limit;
179
+ const page = hasMore ? mapped.slice(0, limit) : mapped;
180
+
181
  const items =
182
  sort === "new"
183
+ ? page
184
+ : [...page].sort((a, b) => scoreHot(b.upvotesCount, b.createdAt) - scoreHot(a.upvotesCount, a.createdAt));
185
 
186
  const nextCursor = hasMore ? page[page.length - 1]?.createdAt.toISOString() ?? null : null;
187
  return NextResponse.json({ items, nextCursor });
components/HomeList.tsx CHANGED
@@ -22,13 +22,28 @@ export function HomeList() {
22
  const [items, setItems] = useState<IdeaCard[]>([]);
23
  const [error, setError] = useState("");
24
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});
 
 
 
 
 
 
 
 
 
 
25
 
26
  useEffect(() => {
27
  let active = true;
28
  setLoading(true);
29
  setError("");
30
 
31
- fetch(`/api/ideas?sort=${sort}`)
 
 
 
 
 
32
  .then(async (response) => {
33
  const data = await response.json();
34
  if (!response.ok) {
@@ -52,7 +67,7 @@ export function HomeList() {
52
  return () => {
53
  active = false;
54
  };
55
- }, [sort]);
56
 
57
  const empty = useMemo(() => !loading && !error && items.length === 0, [loading, error, items.length]);
58
 
@@ -67,12 +82,40 @@ export function HomeList() {
67
  New
68
  </button>
69
  </div>
70
- <p className="subtle text-sm">{items.length} ideas</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  </div>
72
 
 
 
 
 
 
73
  {loading ? <p className="subtle text-sm">Loading ideas...</p> : null}
74
  {error ? <p className="text-sm text-red-700">{error}</p> : null}
75
- {empty ? <p className="subtle text-sm">No ideas yet. Be the first to submit one.</p> : null}
 
 
76
 
77
  <div className="grid gap-3">
78
  {items.map((idea, index) => {
 
22
  const [items, setItems] = useState<IdeaCard[]>([]);
23
  const [error, setError] = useState("");
24
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});
25
+ const [queryInput, setQueryInput] = useState("");
26
+ const [query, setQuery] = useState("");
27
+
28
+ useEffect(() => {
29
+ const timer = setTimeout(() => {
30
+ setQuery(queryInput.trim());
31
+ }, 250);
32
+
33
+ return () => clearTimeout(timer);
34
+ }, [queryInput]);
35
 
36
  useEffect(() => {
37
  let active = true;
38
  setLoading(true);
39
  setError("");
40
 
41
+ const params = new URLSearchParams({ sort });
42
+ if (query) {
43
+ params.set("q", query);
44
+ }
45
+
46
+ fetch(`/api/ideas?${params.toString()}`)
47
  .then(async (response) => {
48
  const data = await response.json();
49
  if (!response.ok) {
 
67
  return () => {
68
  active = false;
69
  };
70
+ }, [sort, query]);
71
 
72
  const empty = useMemo(() => !loading && !error && items.length === 0, [loading, error, items.length]);
73
 
 
82
  New
83
  </button>
84
  </div>
85
+
86
+ <div className="flex flex-col items-start gap-1">
87
+ <label className="subtle text-xs font-medium uppercase tracking-[0.12em]" htmlFor="idea-search-input">
88
+ Search (Fuzzy)
89
+ </label>
90
+ <div className="flex items-center gap-2">
91
+ <input
92
+ id="idea-search-input"
93
+ type="search"
94
+ className="min-w-[240px] rounded-full border border-zinc-300 bg-white/90 px-4 py-2 text-sm outline-none focus:border-zinc-500"
95
+ placeholder="Try approximate terms or typos"
96
+ value={queryInput}
97
+ onChange={(event) => setQueryInput(event.target.value)}
98
+ aria-label="Search ideas"
99
+ />
100
+ {queryInput ? (
101
+ <button type="button" className="btn rounded-full px-3" onClick={() => setQueryInput("")}>
102
+ Clear
103
+ </button>
104
+ ) : null}
105
+ </div>
106
+ </div>
107
  </div>
108
 
109
+ <p className="subtle text-sm">
110
+ {items.length} ideas
111
+ {query ? ` matching "${query}"` : ""}
112
+ </p>
113
+
114
  {loading ? <p className="subtle text-sm">Loading ideas...</p> : null}
115
  {error ? <p className="text-sm text-red-700">{error}</p> : null}
116
+ {empty ? (
117
+ <p className="subtle text-sm">{query ? `No ideas found for "${query}".` : "No ideas yet. Be the first to submit one."}</p>
118
+ ) : null}
119
 
120
  <div className="grid gap-3">
121
  {items.map((idea, index) => {
lib/fuzzy-search.ts ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const SEARCH_STOP_WORDS = new Set([
2
+ "a",
3
+ "an",
4
+ "and",
5
+ "are",
6
+ "as",
7
+ "at",
8
+ "be",
9
+ "by",
10
+ "for",
11
+ "from",
12
+ "how",
13
+ "i",
14
+ "if",
15
+ "in",
16
+ "is",
17
+ "it",
18
+ "me",
19
+ "my",
20
+ "of",
21
+ "on",
22
+ "or",
23
+ "that",
24
+ "the",
25
+ "this",
26
+ "to",
27
+ "we",
28
+ "with",
29
+ "you",
30
+ "your",
31
+ ]);
32
+
33
+ export type SearchContext = {
34
+ normalizedQuery: string;
35
+ tokens: string[];
36
+ trigrams: Set<string>;
37
+ };
38
+
39
+ export type SearchableIdea = {
40
+ title: string;
41
+ problemStatement: string;
42
+ rawInputText: string;
43
+ tags: string[];
44
+ };
45
+
46
+ export function normalizeSearchText(value: string): string {
47
+ return value.toLowerCase().replace(/[^a-z0-9\s]/g, " ").replace(/\s+/g, " ").trim();
48
+ }
49
+
50
+ export function tokenizeSearchTerms(value: string): string[] {
51
+ const normalized = normalizeSearchText(value);
52
+ if (!normalized) return [];
53
+
54
+ const tokens = normalized.split(" ").filter(Boolean);
55
+ const meaningful = tokens.filter((token) => token.length >= 2 && !SEARCH_STOP_WORDS.has(token));
56
+ return meaningful.length > 0 ? meaningful : tokens.filter((token) => token.length >= 2);
57
+ }
58
+
59
+ function levenshteinDistance(a: string, b: string): number {
60
+ if (a === b) return 0;
61
+ if (!a.length) return b.length;
62
+ if (!b.length) return a.length;
63
+
64
+ const prev = new Array<number>(b.length + 1);
65
+ const next = new Array<number>(b.length + 1);
66
+
67
+ for (let j = 0; j <= b.length; j += 1) prev[j] = j;
68
+
69
+ for (let i = 1; i <= a.length; i += 1) {
70
+ next[0] = i;
71
+ for (let j = 1; j <= b.length; j += 1) {
72
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
73
+ next[j] = Math.min(next[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
74
+ }
75
+
76
+ for (let j = 0; j <= b.length; j += 1) prev[j] = next[j];
77
+ }
78
+
79
+ return prev[b.length];
80
+ }
81
+
82
+ function tokenSimilarity(queryToken: string, candidateToken: string): number {
83
+ if (queryToken === candidateToken) return 1;
84
+ if (candidateToken.startsWith(queryToken) || queryToken.startsWith(candidateToken)) return 0.9;
85
+
86
+ const maxLength = Math.max(queryToken.length, candidateToken.length);
87
+ if (maxLength === 0) return 0;
88
+ if (Math.abs(queryToken.length - candidateToken.length) > 3) return 0;
89
+
90
+ const distance = levenshteinDistance(queryToken, candidateToken);
91
+ return Math.max(0, 1 - distance / maxLength);
92
+ }
93
+
94
+ export function createTrigrams(value: string): Set<string> {
95
+ const normalized = normalizeSearchText(value);
96
+ if (normalized.length < 3) {
97
+ return new Set(normalized ? [normalized] : []);
98
+ }
99
+
100
+ const padded = ` ${normalized} `;
101
+ const grams = new Set<string>();
102
+ for (let i = 0; i <= padded.length - 3; i += 1) {
103
+ grams.add(padded.slice(i, i + 3));
104
+ }
105
+ return grams;
106
+ }
107
+
108
+ function jaccardSimilarity(a: Set<string>, b: Set<string>): number {
109
+ if (a.size === 0 || b.size === 0) return 0;
110
+
111
+ let intersection = 0;
112
+ for (const item of a) {
113
+ if (b.has(item)) intersection += 1;
114
+ }
115
+
116
+ const union = a.size + b.size - intersection;
117
+ return union > 0 ? intersection / union : 0;
118
+ }
119
+
120
+ function fuzzyTextScore(context: SearchContext, candidate: string): number {
121
+ const candidateNormalized = normalizeSearchText(candidate);
122
+ if (!candidateNormalized) return 0;
123
+ if (candidateNormalized.includes(context.normalizedQuery)) return 1;
124
+
125
+ const candidateTokens = candidateNormalized.split(" ").filter(Boolean);
126
+ let tokenScore = 0;
127
+
128
+ if (context.tokens.length > 0 && candidateTokens.length > 0) {
129
+ const perToken = context.tokens.map((token) => {
130
+ let best = 0;
131
+ for (const candidateToken of candidateTokens) {
132
+ const similarity = tokenSimilarity(token, candidateToken);
133
+ if (similarity > best) best = similarity;
134
+ if (best >= 1) break;
135
+ }
136
+ return best;
137
+ });
138
+
139
+ tokenScore = perToken.reduce((total, value) => total + value, 0) / perToken.length;
140
+ }
141
+
142
+ const trigramScore = jaccardSimilarity(context.trigrams, createTrigrams(candidateNormalized));
143
+ return 0.72 * tokenScore + 0.28 * trigramScore;
144
+ }
145
+
146
+ export function computeIdeaSearchScore(context: SearchContext, idea: SearchableIdea): number {
147
+ const titleScore = fuzzyTextScore(context, idea.title);
148
+ const problemScore = fuzzyTextScore(context, idea.problemStatement);
149
+ const rawScore = fuzzyTextScore(context, idea.rawInputText);
150
+ const tagsScore = fuzzyTextScore(context, idea.tags.join(" "));
151
+ const blended = titleScore * 0.42 + problemScore * 0.3 + rawScore * 0.2 + tagsScore * 0.08;
152
+
153
+ return Math.max(titleScore, blended);
154
+ }