Repository navigation
feat(www): add autocomplete-search component and repo stats in site header - #80
Conversation
…nc, grouped options and keyboard nav
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Review limit reached
Next review available in: 12 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughAdds a new ChangesAutocompleteSearch Component
RepoStats Header Widget
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (2)
apps/www/components/repo-stats.tsx (1)
26-37: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winSkip the request when the widget is hidden below
lg.This component is mounted even when
hidden lg:flexkeeps it invisible, so the effect still calls/api/statson small screens where the result is never shown. Gate the fetch/render behind a media match, or lift the visibility decision above this component.Also applies to: 63-67
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/www/components/repo-stats.tsx` around lines 26 - 37, The RepoStats widget still triggers fetch("/api/stats") in useEffect even when it is hidden by the lg breakpoint, so update RepoStats to gate the request behind the same visibility decision or a media query check before the effect runs. Use the existing RepoStats component and its useEffect/setStats flow to only fetch when the widget will actually be rendered, and make sure the render path is also conditioned so small screens do not mount the data-loading logic at all.registry/autocomplete-search/component.tsx (1)
28-47: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtend the input props contract.
This registry component currently blocks standard input attributes like
disabled,name,autoFocus,aria-describedby, etc. Extend the relevant input props and omit controlled/conflicting handlers such asonChange,onSelect,value, anddefaultValue.As per coding guidelines,
registry/**/*.tsx: “Extend the relevant HTML/motion props interface and omit conflicting event handlers in TypeScript components.”Proposed API shape
-export interface AutocompleteSearchProps { +export interface AutocompleteSearchProps + extends Omit< + React.ComponentPropsWithoutRef<"input">, + | "className" + | "defaultValue" + | "onChange" + | "onSelect" + | "type" + | "value" + > {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@registry/autocomplete-search/component.tsx` around lines 28 - 47, AutocompleteSearchProps currently omits standard input attributes, so extend the component’s input contract to accept native input props like disabled, name, autoFocus, aria-describedby, and similar. Update AutocompleteSearchProps to inherit the relevant HTML input props while explicitly omitting conflicting controlled handlers and values such as onChange, onSelect, value, and defaultValue, then thread the remaining props through the AutocompleteSearch input element.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/www/app/api/stats/route.ts`:
- Around line 10-35: Both upstream calls in getGitHub and getNpmDownloads can
hang until the platform timeout, so add a short fetch deadline to fail fast
while preserving the existing null fallback behavior. Update the fetches in
apps/www/app/api/stats/route.ts to use an AbortController or equivalent timeout
wrapper, and make sure the timeout is applied consistently to both the GitHub
and npm requests without changing the returned response shape.
In `@apps/www/components/repo-stats.tsx`:
- Around line 70-87: The link in RepoStats is overriding its accessible name
with only item.label, so the visible formatted count from format(item.value) is
not announced. Update the accessible name in the repo-stats component so it
includes both the label and the rendered value, or shift the label into hidden
text while keeping the count in the announced text. Use the existing anchor and
item.icon/item.label/item.value rendering in RepoStats to make the accessible
name match what users see.
In `@apps/www/components/ui/autocomplete-search.tsx`:
- Around line 90-130: The autocomplete search effect still allows stale async
responses to win because cleanup only clears the debounce timer and does not
invalidate a pending onSearch(trimmed) request. Update the useEffect in
autocomplete-search.tsx to bump requestIdRef.current during cleanup (or
otherwise cancel/invalidate the in-flight request) so any late .then/.catch for
a previous query is ignored, while keeping the existing stale-response guard
around requestIdRef and setResults/setStatus.
In `@apps/www/config/components.ts`:
- Around line 3575-3579: The new component entry for Autocomplete Search is
missing its creation timestamp, so the docs “NEW” badge cannot be detected. Add
the addedAt field to the Autocomplete Search object in the components
configuration, matching the existing shape used by other new components, so
isNewComponent() can return true and render the highlight.
In `@apps/www/public/r/autocomplete-search.json`:
- Line 16: The autocomplete list is using stale results between keystrokes,
which lets the user select an option from the previous query before the
debounced search runs. Update AutocompleteSearch so that onChange clears or
invalidates the current results and resets activeIndex immediately before
setting the new query/open state, or otherwise puts the dropdown into a pending
state until the next filter/fetch completes. Make the change in the onChange
handler and keep it consistent with the useEffect debounce/search flow and
select/onKeyDown behavior.
- Line 16: AutocompleteSearchProps is too narrow because it only exposes custom
props, so standard input attributes can’t be passed through. Update
AutocompleteSearchProps to extend React.ComponentPropsWithoutRef<"input"> and
omit conflicting controlled props like value and onChange, then forward the
remaining input props from AutocompleteSearch so callers can supply id, name,
disabled, required, and ARIA attributes.
In `@apps/www/public/registry/autocomplete-search.json`:
- Line 12: The AutocompleteSearch effect only clears the debounce timer on
cleanup, so a pending onSearch promise can still resolve after unmount and
update state. Update the useEffect in AutocompleteSearch to also invalidate
in-flight async requests during cleanup by bumping requestIdRef (and keep the
existing timer cleanup), so stale promise callbacks in the reqId guard cannot
commit results after unmount.
In `@registry/autocomplete-search/component.tsx`:
- Around line 90-130: Invalidate any pending async search when the effect cleans
up, not just the debounce timer. In `AutocompleteSearch`’s `useEffect`, the
current `clearTimeout(timer)` only stops the scheduled callback, so an
already-started `onSearch(trimmed)` can still resolve with a stale `reqId`.
Update the cleanup to also bump `requestIdRef.current` (or otherwise mark the
current request stale) so old responses from `onSearch` are ignored immediately
when `trimmed`, `belowMin`, or `onSearch` changes.
---
Nitpick comments:
In `@apps/www/components/repo-stats.tsx`:
- Around line 26-37: The RepoStats widget still triggers fetch("/api/stats") in
useEffect even when it is hidden by the lg breakpoint, so update RepoStats to
gate the request behind the same visibility decision or a media query check
before the effect runs. Use the existing RepoStats component and its
useEffect/setStats flow to only fetch when the widget will actually be rendered,
and make sure the render path is also conditioned so small screens do not mount
the data-loading logic at all.
In `@registry/autocomplete-search/component.tsx`:
- Around line 28-47: AutocompleteSearchProps currently omits standard input
attributes, so extend the component’s input contract to accept native input
props like disabled, name, autoFocus, aria-describedby, and similar. Update
AutocompleteSearchProps to inherit the relevant HTML input props while
explicitly omitting conflicting controlled handlers and values such as onChange,
onSelect, value, and defaultValue, then thread the remaining props through the
AutocompleteSearch input element.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 3e625fe0-7652-4658-b65e-3b68275ed05e
📒 Files selected for processing (23)
.gitignoreapps/www/app/api/stats/route.tsapps/www/app/components/page.tsxapps/www/components/repo-stats.tsxapps/www/components/site-header.tsxapps/www/components/ui/autocomplete-search.tsxapps/www/config/components.tsapps/www/config/demos.tsxapps/www/config/docs-scenarios.tsapps/www/public/r/autocomplete-search.jsonapps/www/public/r/registry.jsonapps/www/public/registry.jsonapps/www/public/registry/autocomplete-search.jsonapps/www/public/registry/changelogs.jsonapps/www/public/registry/index.jsonapps/www/public/registry/multi-step-auth-card.jsonregistry.jsonregistry/autocomplete-search/component.tsxregistry/autocomplete-search/demo.tsxregistry/components/autocomplete-search.jsonregistry/demos/demo-key-order.jsonregistry/demos/shared.tsxregistry/manifest.json
| async function getGitHub(): Promise<{ stars: number | null; forks: number | null }> { | ||
| try { | ||
| const res = await fetch(`https://api.github.com/repos/${GITHUB_REPO}`, { | ||
| headers: { Accept: "application/vnd.github+json" }, | ||
| next: { revalidate: REVALIDATE }, | ||
| }); | ||
| if (!res.ok) return { stars: null, forks: null }; | ||
| const data = await res.json(); | ||
| return { | ||
| stars: typeof data.stargazers_count === "number" ? data.stargazers_count : null, | ||
| forks: typeof data.forks_count === "number" ? data.forks_count : null, | ||
| }; | ||
| } catch { | ||
| return { stars: null, forks: null }; | ||
| } | ||
| } | ||
|
|
||
| async function getNpmDownloads(): Promise<{ downloads: number | null }> { | ||
| try { | ||
| // A wide range auto-clamps to the first published day, so this is the | ||
| // effective all-time total for the package. | ||
| const today = new Date().toISOString().slice(0, 10); | ||
| const res = await fetch( | ||
| `https://api.npmjs.org/downloads/point/2015-01-01:${today}/${NPM_PACKAGE}`, | ||
| { next: { revalidate: REVALIDATE } }, | ||
| ); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Map the route file and nearby helpers.
git ls-files 'apps/www/app/api/stats/route.ts' 'apps/www/app/**' | sed -n '1,120p'
echo
echo '--- route.ts ---'
cat -n apps/www/app/api/stats/route.ts | sed -n '1,220p'
echo
echo '--- search for AbortSignal.timeout / fetch wrappers in apps/www ---'
rg -n "AbortSignal\.timeout|signal:\s*AbortSignal|fetch\(" apps/www -g '!**/node_modules/**' | sed -n '1,220p'Repository: pras75299/uniqueui
Length of output: 7111
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the file that defines the stats endpoint in smaller chunks if needed.
wc -l apps/www/app/api/stats/route.ts
sed -n '1,120p' apps/www/app/api/stats/route.tsRepository: pras75299/uniqueui
Length of output: 2067
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Look for any existing timeout or fetch wrapper used in the app.
rg -n "AbortSignal\.timeout|fetchWithTimeout|timeout.*fetch|signal:\s*AbortSignal" apps/www -g '!**/node_modules/**' | sed -n '1,200p'
echo
echo '--- route file ---'
sed -n '1,220p' apps/www/app/api/stats/route.tsRepository: pras75299/uniqueui
Length of output: 156
🌐 Web query:
Next.js Route Handler fetch timeout AbortSignal.timeout Node.js runtime support
💡 Result:
Next.js Route Handlers support the use of AbortSignal.timeout within their fetch calls, as it is a standard Web API available in both the Node.js and Edge runtimes [1][2][3]. Support Status: - Node.js Runtime: AbortSignal.timeout is natively supported in Node.js versions 17.3.0 and later (as well as 16.14.0+) [2][4]. Since modern Next.js applications run on up-to-date Node.js environments, this API is available for use in your code. - Edge Runtime: As the Edge Runtime is designed to be a compliant subset of standard Web APIs, it includes support for standard signal-based cancellation patterns, including AbortSignal.timeout [1]. Implementation: In a Next.js Route Handler, you can pass the signal returned by AbortSignal.timeout(ms) directly into the fetch options [3][5]: export async function GET { try { const res = await fetch('https://api.example.com', { signal: AbortSignal.timeout(5000), // Aborts after 5 seconds }); return Response.json(await res.json); } catch (err) { if (err.name === 'TimeoutError') { return new Response('Gateway Timeout', { status: 504 }); } return new Response('Internal Server Error', { status: 500 }); } } Additional Context: - Client Disconnects: If you need to handle scenarios where the client disconnects, Next.js provides a request signal (request.signal) in Route Handlers [6][7]. You can combine this with your own timeout logic using AbortSignal.any [3]. - Platform Specifics: If deploying on Vercel, be aware that while function-level execution limits (maxDuration) are platform-enforced, the manual use of AbortSignal.timeout inside your fetch calls is the recommended way to handle downstream service timeouts gracefully [6][5].
Citations:
- 1: https://vercel-next-js.mintlify.app/api-reference/config/edge
- 2: https://nodejs.org/api/globals.html
- 3: https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
- 4: https://r2.nodejs.org/docs/v20.6.0/api/globals.html
- 5: https://auditbuffet.com/patterns/ab-002211
- 6: https://vercel.com/docs/functions/functions-api-reference?framework=other&language=ts
- 7: Ensure
edgeruntime Pages API/App Route handlersAbortSignalaborts on client disconnect vercel/next.js#51727
Add timeouts to the upstream fetches. A stalled GitHub or npm request can keep /api/stats open until the platform timeout; both calls already fall back to null, so a short deadline would fail fast without changing the response shape.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/www/app/api/stats/route.ts` around lines 10 - 35, Both upstream calls in
getGitHub and getNpmDownloads can hang until the platform timeout, so add a
short fetch deadline to fail fast while preserving the existing null fallback
behavior. Update the fetches in apps/www/app/api/stats/route.ts to use an
AbortController or equivalent timeout wrapper, and make sure the timeout is
applied consistently to both the GitHub and npm requests without changing the
returned response shape.
| <a | ||
| key={item.label} | ||
| href={item.href} | ||
| target="_blank" | ||
| rel="noopener noreferrer" | ||
| aria-label={item.label} | ||
| title={item.label} | ||
| className={cn( | ||
| "flex items-center gap-1.5 px-2.5 py-1.5 text-sm transition-colors duration-200 ease-out tabular-nums", | ||
| i > 0 && (isDark ? "border-l border-neutral-800" : "border-l border-neutral-200"), | ||
| isDark | ||
| ? "text-neutral-400 hover:text-white" | ||
| : "text-neutral-600 hover:text-neutral-900", | ||
| )} | ||
| > | ||
| <item.icon className="h-3.5 w-3.5 shrink-0" aria-hidden /> | ||
| {loaded ? ( | ||
| <span>{format(item.value)}</span> |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Don’t override the visible count in the link name.
aria-label={item.label} replaces the accessible name with just the label, so a screen reader never hears the rendered star/fork/download count. Include the formatted value in the accessible name, or move the label into hidden text instead.
Proposed fix
- aria-label={item.label}
+ aria-label={
+ loaded ? `${item.label}: ${format(item.value)}` : `${item.label}: loading`
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| <a | |
| key={item.label} | |
| href={item.href} | |
| target="_blank" | |
| rel="noopener noreferrer" | |
| aria-label={item.label} | |
| title={item.label} | |
| className={cn( | |
| "flex items-center gap-1.5 px-2.5 py-1.5 text-sm transition-colors duration-200 ease-out tabular-nums", | |
| i > 0 && (isDark ? "border-l border-neutral-800" : "border-l border-neutral-200"), | |
| isDark | |
| ? "text-neutral-400 hover:text-white" | |
| : "text-neutral-600 hover:text-neutral-900", | |
| )} | |
| > | |
| <item.icon className="h-3.5 w-3.5 shrink-0" aria-hidden /> | |
| {loaded ? ( | |
| <span>{format(item.value)}</span> | |
| <a | |
| key={item.label} | |
| href={item.href} | |
| target="_blank" | |
| rel="noopener noreferrer" | |
| aria-label={ | |
| loaded ? `${item.label}: ${format(item.value)}` : `${item.label}: loading` | |
| } | |
| title={item.label} | |
| className={cn( | |
| "flex items-center gap-1.5 px-2.5 py-1.5 text-sm transition-colors duration-200 ease-out tabular-nums", | |
| i > 0 && (isDark ? "border-l border-neutral-800" : "border-l border-neutral-200"), | |
| isDark | |
| ? "text-neutral-400 hover:text-white" | |
| : "text-neutral-600 hover:text-neutral-900", | |
| )} | |
| > | |
| <item.icon className="h-3.5 w-3.5 shrink-0" aria-hidden /> | |
| {loaded ? ( | |
| <span>{format(item.value)}</span> |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/www/components/repo-stats.tsx` around lines 70 - 87, The link in
RepoStats is overriding its accessible name with only item.label, so the visible
formatted count from format(item.value) is not announced. Update the accessible
name in the repo-stats component so it includes both the label and the rendered
value, or shift the label into hidden text while keeping the count in the
announced text. Use the existing anchor and item.icon/item.label/item.value
rendering in RepoStats to make the accessible name match what users see.
| useEffect(() => { | ||
| const timer = setTimeout(() => { | ||
| if (belowMin) { | ||
| requestIdRef.current++; // invalidate any in-flight async result | ||
| setResults([]); | ||
| setActiveIndex(-1); | ||
| setStatus("idle"); | ||
| return; | ||
| } | ||
|
|
||
| // Sync mode — local case-insensitive substring filter. | ||
| if (!onSearch) { | ||
| const needle = trimmed.toLowerCase(); | ||
| const next = (options ?? []).filter((o) => | ||
| o.label.toLowerCase().includes(needle), | ||
| ); | ||
| setResults(next); | ||
| setActiveIndex(next.length ? 0 : -1); | ||
| setStatus("idle"); | ||
| return; | ||
| } | ||
|
|
||
| // Async mode — fetch with a stale-response guard. | ||
| setStatus("loading"); | ||
| const reqId = ++requestIdRef.current; | ||
| onSearch(trimmed) | ||
| .then((next) => { | ||
| if (reqId !== requestIdRef.current) return; | ||
| setResults(next); | ||
| setActiveIndex(next.length ? 0 : -1); | ||
| setStatus("idle"); | ||
| }) | ||
| .catch(() => { | ||
| if (reqId !== requestIdRef.current) return; | ||
| setResults([]); | ||
| setActiveIndex(-1); | ||
| setStatus("error"); | ||
| }); | ||
| }, debounceMs); | ||
| return () => clearTimeout(timer); | ||
| }, [trimmed, belowMin, onSearch, options, debounceMs]); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Invalidate in-flight async searches during cleanup.
Same issue as the registry source: once onSearch(trimmed) is pending, cleanup only clears the timer and does not invalidate that request. A stale response can update results after the user has typed a newer query.
Proposed fix
useEffect(() => {
const timer = setTimeout(() => {
if (belowMin) {
- requestIdRef.current++; // invalidate any in-flight async result
setResults([]);
setActiveIndex(-1);
setStatus("idle");
return;
}
@@
- return () => clearTimeout(timer);
+ return () => {
+ clearTimeout(timer);
+ requestIdRef.current++;
+ };
}, [trimmed, belowMin, onSearch, options, debounceMs]);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| useEffect(() => { | |
| const timer = setTimeout(() => { | |
| if (belowMin) { | |
| requestIdRef.current++; // invalidate any in-flight async result | |
| setResults([]); | |
| setActiveIndex(-1); | |
| setStatus("idle"); | |
| return; | |
| } | |
| // Sync mode — local case-insensitive substring filter. | |
| if (!onSearch) { | |
| const needle = trimmed.toLowerCase(); | |
| const next = (options ?? []).filter((o) => | |
| o.label.toLowerCase().includes(needle), | |
| ); | |
| setResults(next); | |
| setActiveIndex(next.length ? 0 : -1); | |
| setStatus("idle"); | |
| return; | |
| } | |
| // Async mode — fetch with a stale-response guard. | |
| setStatus("loading"); | |
| const reqId = ++requestIdRef.current; | |
| onSearch(trimmed) | |
| .then((next) => { | |
| if (reqId !== requestIdRef.current) return; | |
| setResults(next); | |
| setActiveIndex(next.length ? 0 : -1); | |
| setStatus("idle"); | |
| }) | |
| .catch(() => { | |
| if (reqId !== requestIdRef.current) return; | |
| setResults([]); | |
| setActiveIndex(-1); | |
| setStatus("error"); | |
| }); | |
| }, debounceMs); | |
| return () => clearTimeout(timer); | |
| }, [trimmed, belowMin, onSearch, options, debounceMs]); | |
| useEffect(() => { | |
| const timer = setTimeout(() => { | |
| if (belowMin) { | |
| setResults([]); | |
| setActiveIndex(-1); | |
| setStatus("idle"); | |
| return; | |
| } | |
| // Sync mode — local case-insensitive substring filter. | |
| if (!onSearch) { | |
| const needle = trimmed.toLowerCase(); | |
| const next = (options ?? []).filter((o) => | |
| o.label.toLowerCase().includes(needle), | |
| ); | |
| setResults(next); | |
| setActiveIndex(next.length ? 0 : -1); | |
| setStatus("idle"); | |
| return; | |
| } | |
| // Async mode — fetch with a stale-response guard. | |
| setStatus("loading"); | |
| const reqId = ++requestIdRef.current; | |
| onSearch(trimmed) | |
| .then((next) => { | |
| if (reqId !== requestIdRef.current) return; | |
| setResults(next); | |
| setActiveIndex(next.length ? 0 : -1); | |
| setStatus("idle"); | |
| }) | |
| .catch(() => { | |
| if (reqId !== requestIdRef.current) return; | |
| setResults([]); | |
| setActiveIndex(-1); | |
| setStatus("error"); | |
| }); | |
| }, debounceMs); | |
| return () => { | |
| clearTimeout(timer); | |
| requestIdRef.current++; | |
| }; | |
| }, [trimmed, belowMin, onSearch, options, debounceMs]); |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/www/components/ui/autocomplete-search.tsx` around lines 90 - 130, The
autocomplete search effect still allows stale async responses to win because
cleanup only clears the debounce timer and does not invalidate a pending
onSearch(trimmed) request. Update the useEffect in autocomplete-search.tsx to
bump requestIdRef.current during cleanup (or otherwise cancel/invalidate the
in-flight request) so any late .then/.catch for a previous query is ignored,
while keeping the existing stale-response guard around requestIdRef and
setResults/setStatus.
| "slug": "autocomplete-search", | ||
| "name": "Autocomplete Search", | ||
| "description": "Accessible combobox with debounced filtering, async-ready search, full keyboard navigation, grouped options, matched-text highlighting, and loading / empty / error states.", | ||
| "icon": "LucideSearch", | ||
| "category": "Components", |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Add addedAt so the new badge can render.
This is a new component, but without addedAt, isNewComponent() will always return false and the docs “NEW” highlight won’t appear.
Proposed fix
"description": "Accessible combobox with debounced filtering, async-ready search, full keyboard navigation, grouped options, matched-text highlighting, and loading / empty / error states.",
"icon": "LucideSearch",
"category": "Components",
+ "addedAt": "2026-06-29",
"props": [📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "slug": "autocomplete-search", | |
| "name": "Autocomplete Search", | |
| "description": "Accessible combobox with debounced filtering, async-ready search, full keyboard navigation, grouped options, matched-text highlighting, and loading / empty / error states.", | |
| "icon": "LucideSearch", | |
| "category": "Components", | |
| "slug": "autocomplete-search", | |
| "name": "Autocomplete Search", | |
| "description": "Accessible combobox with debounced filtering, async-ready search, full keyboard navigation, grouped options, matched-text highlighting, and loading / empty / error states.", | |
| "icon": "LucideSearch", | |
| "category": "Components", | |
| "addedAt": "2026-06-29", |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/www/config/components.ts` around lines 3575 - 3579, The new component
entry for Autocomplete Search is missing its creation timestamp, so the docs
“NEW” badge cannot be detected. Add the addedAt field to the Autocomplete Search
object in the components configuration, matching the existing shape used by
other new components, so isNewComponent() can return true and render the
highlight.
| "files": [ | ||
| { | ||
| "path": "components/ui/autocomplete-search.tsx", | ||
| "content": "\"use client\";\n\nimport {\n useCallback,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { Loader2, Search } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\nexport type AutocompleteOption = {\n /** Stable, unique value used as the React key and returned on select. */\n value: string;\n /** Visible text; also what is matched against and highlighted. */\n label: string;\n /** Optional section label — consecutive options sharing it are grouped. */\n group?: string;\n /** Optional secondary line shown under the label. */\n description?: string;\n /** Optional leading icon node. */\n icon?: React.ReactNode;\n};\n\nexport interface AutocompleteSearchProps {\n /** Static option list (synchronous local filtering). Ignored when `onSearch` is set. */\n options?: AutocompleteOption[];\n /** Async resolver — return matching options for a query. Enables async mode. */\n onSearch?: (query: string) => Promise<AutocompleteOption[]>;\n /** Fired when an option is chosen via click or Enter. */\n onSelect?: (option: AutocompleteOption) => void;\n placeholder?: string;\n /** Debounce before filtering/fetching. Default 300ms. */\n debounceMs?: number;\n /** Minimum characters before searching. Default 0. */\n minChars?: number;\n emptyMessage?: string;\n loadingMessage?: string;\n /** Shown when the query is below `minChars` (only if provided). */\n hintMessage?: string;\n errorMessage?: string;\n theme?: \"light\" | \"dark\";\n className?: string;\n}\n\ntype Status = \"idle\" | \"loading\" | \"error\";\n\nexport function AutocompleteSearch({\n options,\n onSearch,\n onSelect,\n placeholder = \"Search…\",\n debounceMs = 300,\n minChars = 0,\n emptyMessage = \"No results found\",\n loadingMessage = \"Searching…\",\n hintMessage,\n errorMessage = \"Something went wrong. Try again.\",\n theme = \"dark\",\n className,\n}: AutocompleteSearchProps) {\n const dark = theme === \"dark\";\n const reduceMotion = useReducedMotion();\n\n const baseId = useId();\n const listboxId = `${baseId}-listbox`;\n const statusId = `${baseId}-status`;\n const optionId = (i: number) => `${baseId}-option-${i}`;\n\n const [query, setQuery] = useState(\"\");\n const [open, setOpen] = useState(false);\n const [results, setResults] = useState<AutocompleteOption[]>([]);\n const [activeIndex, setActiveIndex] = useState(-1);\n const [status, setStatus] = useState<Status>(\"idle\");\n\n const containerRef = useRef<HTMLDivElement>(null);\n const inputRef = useRef<HTMLInputElement>(null);\n const listRef = useRef<HTMLDivElement>(null);\n // Monotonic id so a slow async response can't overwrite a newer query.\n const requestIdRef = useRef(0);\n\n const trimmed = query.trim();\n const belowMin = trimmed.length < minChars;\n\n // Debounced sync filter / async fetch. All state writes live in the timer or\n // promise callback so nothing runs synchronously in the effect body.\n useEffect(() => {\n const timer = setTimeout(() => {\n if (belowMin) {\n requestIdRef.current++; // invalidate any in-flight async result\n setResults([]);\n setActiveIndex(-1);\n setStatus(\"idle\");\n return;\n }\n\n // Sync mode — local case-insensitive substring filter.\n if (!onSearch) {\n const needle = trimmed.toLowerCase();\n const next = (options ?? []).filter((o) =>\n o.label.toLowerCase().includes(needle),\n );\n setResults(next);\n setActiveIndex(next.length ? 0 : -1);\n setStatus(\"idle\");\n return;\n }\n\n // Async mode — fetch with a stale-response guard.\n setStatus(\"loading\");\n const reqId = ++requestIdRef.current;\n onSearch(trimmed)\n .then((next) => {\n if (reqId !== requestIdRef.current) return;\n setResults(next);\n setActiveIndex(next.length ? 0 : -1);\n setStatus(\"idle\");\n })\n .catch(() => {\n if (reqId !== requestIdRef.current) return;\n setResults([]);\n setActiveIndex(-1);\n setStatus(\"error\");\n });\n }, debounceMs);\n return () => clearTimeout(timer);\n }, [trimmed, belowMin, onSearch, options, debounceMs]);\n\n // Close on outside pointer interaction.\n useEffect(() => {\n if (!open) return;\n function onPointerDown(e: PointerEvent) {\n if (!containerRef.current?.contains(e.target as Node)) {\n setOpen(false);\n setActiveIndex(-1);\n }\n }\n document.addEventListener(\"pointerdown\", onPointerDown);\n return () => document.removeEventListener(\"pointerdown\", onPointerDown);\n }, [open]);\n\n // Keep the active option scrolled into view during keyboard navigation.\n useEffect(() => {\n if (!open || activeIndex < 0) return;\n listRef.current\n ?.querySelector<HTMLElement>(`[data-index=\"${activeIndex}\"]`)\n ?.scrollIntoView({ block: \"nearest\" });\n }, [activeIndex, open]);\n\n const select = useCallback(\n (option: AutocompleteOption) => {\n setQuery(option.label);\n setOpen(false);\n setActiveIndex(-1);\n onSelect?.(option);\n inputRef.current?.focus();\n },\n [onSelect],\n );\n\n const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n switch (e.key) {\n case \"ArrowDown\":\n e.preventDefault();\n if (!open) {\n setOpen(true);\n break;\n }\n setActiveIndex((i) => (results.length ? (i + 1) % results.length : -1));\n break;\n case \"ArrowUp\":\n e.preventDefault();\n if (!open) {\n setOpen(true);\n break;\n }\n setActiveIndex((i) =>\n results.length ? (i - 1 + results.length) % results.length : -1,\n );\n break;\n case \"Enter\":\n if (open && activeIndex >= 0 && results[activeIndex]) {\n e.preventDefault();\n select(results[activeIndex]);\n }\n break;\n case \"Escape\":\n if (open) {\n setOpen(false);\n setActiveIndex(-1);\n } else if (query) {\n setQuery(\"\");\n }\n break;\n }\n };\n\n // Group consecutive options that share a `group` label.\n const sections = useMemo(() => {\n const out: {\n group?: string;\n items: { option: AutocompleteOption; index: number }[];\n }[] = [];\n results.forEach((option, index) => {\n const last = out[out.length - 1];\n if (last && last.group === option.group) {\n last.items.push({ option, index });\n } else {\n out.push({ group: option.group, items: [{ option, index }] });\n }\n });\n return out;\n }, [results]);\n\n const showLoading = open && status === \"loading\";\n const showError = open && status === \"error\";\n const showList = open && status === \"idle\" && results.length > 0;\n const showHint = open && belowMin && !!hintMessage;\n const showEmpty =\n open && status === \"idle\" && !belowMin && results.length === 0;\n const dropdownOpen =\n showLoading || showError || showList || showHint || showEmpty;\n\n const statusText = showLoading\n ? loadingMessage\n : showError\n ? errorMessage\n : showList\n ? `${results.length} result${results.length === 1 ? \"\" : \"s\"} available`\n : showEmpty\n ? emptyMessage\n : \"\";\n\n return (\n <div\n ref={containerRef}\n className={cn(\"relative w-full max-w-md\", className)}\n >\n <div className=\"relative\">\n <Search\n aria-hidden\n className={cn(\n \"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n />\n <input\n ref={inputRef}\n type=\"text\"\n role=\"combobox\"\n aria-expanded={dropdownOpen}\n aria-controls={listboxId}\n aria-autocomplete=\"list\"\n aria-activedescendant={\n showList && activeIndex >= 0 ? optionId(activeIndex) : undefined\n }\n aria-label={placeholder}\n autoComplete=\"off\"\n spellCheck={false}\n value={query}\n placeholder={placeholder}\n onChange={(e) => {\n setQuery(e.target.value);\n setOpen(true);\n }}\n onFocus={() => setOpen(true)}\n onKeyDown={onKeyDown}\n className={cn(\n \"w-full rounded-xl border py-2.5 pl-9 pr-9 text-sm outline-none transition-colors\",\n dark\n ? \"border-neutral-800 bg-neutral-900 text-neutral-100 placeholder:text-neutral-500 focus:border-neutral-600\"\n : \"border-neutral-200 bg-white text-neutral-900 placeholder:text-neutral-400 focus:border-neutral-400\",\n )}\n />\n {showLoading && (\n <Loader2\n aria-hidden\n className={cn(\n \"absolute right-3 top-1/2 size-4 -translate-y-1/2 animate-spin\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n />\n )}\n </div>\n\n <div id={statusId} role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n {statusText}\n </div>\n\n <AnimatePresence>\n {dropdownOpen && (\n <motion.div\n initial={reduceMotion ? false : { opacity: 0, y: -4, scale: 0.98 }}\n animate={{ opacity: 1, y: 0, scale: 1 }}\n exit={\n reduceMotion\n ? { opacity: 0 }\n : { opacity: 0, y: -4, scale: 0.98 }\n }\n transition={\n reduceMotion\n ? { duration: 0 }\n : { type: \"spring\", stiffness: 520, damping: 36 }\n }\n className={cn(\n \"absolute z-50 mt-2 w-full overflow-hidden rounded-xl border shadow-xl\",\n dark\n ? \"border-neutral-800 bg-neutral-900\"\n : \"border-neutral-200 bg-white\",\n )}\n >\n {showLoading && (\n <div\n className={cn(\n \"flex items-center gap-2 px-3 py-3 text-sm\",\n dark ? \"text-neutral-400\" : \"text-neutral-500\",\n )}\n >\n <Loader2 aria-hidden className=\"size-4 animate-spin\" />\n {loadingMessage}\n </div>\n )}\n\n {showError && (\n <div\n className={cn(\n \"px-3 py-3 text-sm\",\n dark ? \"text-red-400\" : \"text-red-600\",\n )}\n >\n {errorMessage}\n </div>\n )}\n\n {showHint && (\n <div\n className={cn(\n \"px-3 py-3 text-sm\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n >\n {hintMessage}\n </div>\n )}\n\n {showEmpty && (\n <div\n className={cn(\n \"px-3 py-3 text-sm\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n >\n {emptyMessage}\n </div>\n )}\n\n {showList && (\n <div\n ref={listRef}\n id={listboxId}\n role=\"listbox\"\n aria-label={placeholder}\n // Keep input focus when clicking an option.\n onMouseDown={(e) => e.preventDefault()}\n className=\"max-h-72 overflow-y-auto p-1\"\n >\n {sections.map((section, si) => (\n <div\n key={section.group ?? `section-${si}`}\n role={section.group ? \"group\" : undefined}\n aria-label={section.group}\n >\n {section.group && (\n <div\n aria-hidden\n className={cn(\n \"px-2.5 pb-1 pt-2 text-[11px] font-semibold uppercase tracking-wider\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n >\n {section.group}\n </div>\n )}\n {section.items.map(({ option, index }) => {\n const active = index === activeIndex;\n return (\n <div\n key={option.value}\n id={optionId(index)}\n data-index={index}\n role=\"option\"\n aria-selected={active}\n onClick={() => select(option)}\n onMouseMove={() => setActiveIndex(index)}\n className={cn(\n \"flex cursor-pointer items-center gap-2.5 rounded-lg px-2.5 py-2 text-sm transition-colors\",\n active\n ? dark\n ? \"bg-neutral-800 text-neutral-100\"\n : \"bg-neutral-100 text-neutral-900\"\n : dark\n ? \"text-neutral-300\"\n : \"text-neutral-700\",\n )}\n >\n {option.icon && (\n <span className=\"flex size-4 shrink-0 items-center justify-center\">\n {option.icon}\n </span>\n )}\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate\">\n {highlightMatch(option.label, trimmed, dark)}\n </span>\n {option.description && (\n <span\n className={cn(\n \"block truncate text-xs\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n >\n {option.description}\n </span>\n )}\n </span>\n </div>\n );\n })}\n </div>\n ))}\n </div>\n )}\n </motion.div>\n )}\n </AnimatePresence>\n </div>\n );\n}\n\n/** Bold the first case-insensitive substring of `query` within `label`. */\nfunction highlightMatch(label: string, query: string, dark: boolean) {\n if (!query) return label;\n const i = label.toLowerCase().indexOf(query.toLowerCase());\n if (i === -1) return label;\n return (\n <>\n {label.slice(0, i)}\n <span\n className={cn(\"font-semibold\", dark ? \"text-purple-400\" : \"text-purple-600\")}\n >\n {label.slice(i, i + query.length)}\n </span>\n {label.slice(i + query.length)}\n </>\n );\n}\n", |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Clear stale options as soon as the query changes.
The old result set stays selectable until the debounce timer fires, so a quick Enter or click can choose an option for the previous query. Reset results/activeIndex or move the list into a pending state in onChange before scheduling the next search.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/www/public/r/autocomplete-search.json` at line 16, The autocomplete list
is using stale results between keystrokes, which lets the user select an option
from the previous query before the debounced search runs. Update
AutocompleteSearch so that onChange clears or invalidates the current results
and resets activeIndex immediately before setting the new query/open state, or
otherwise puts the dropdown into a pending state until the next filter/fetch
completes. Make the change in the onChange handler and keep it consistent with
the useEffect debounce/search flow and select/onKeyDown behavior.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
ast-grep outline registry/autocomplete-search/component.tsx --view expanded
sed -n '1,220p' registry/autocomplete-search/component.tsx
rg -n --type=tsx 'interface .*Props extends|type .*Props = .*ComponentProps|ComponentPropsWithoutRef<"input">|InputHTMLAttributes' registry --iglob '*/component.tsx'Repository: pras75299/uniqueui
Length of output: 7660
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Find registry components that extend intrinsic element props.
rg -n --glob 'registry/**/component.tsx' \
'ComponentPropsWithoutRef<"input">|InputHTMLAttributes|TextareaHTMLAttributes|SelectHTMLAttributes|ComponentPropsWithoutRef<"textarea">|ComponentPropsWithoutRef<"select">' .
printf '\n---\n'
# Show the exact prop surface of the autocomplete component and surrounding type usage.
sed -n '1,120p' registry/autocomplete-search/component.tsx
printf '\n---\n'
# Look for other props or spreads that would already accept arbitrary input attributes.
rg -n --glob 'registry/autocomplete-search/component.tsx' '...props|{...props}|rest|inputRef|onChange|onSelect|disabled|required|name|id|aria-' registry/autocomplete-search/component.tsxRepository: pras75299/uniqueui
Length of output: 156
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate any registry component prop patterns for comparison.
rg -n --glob 'registry/**/component.tsx' \
'extends .*ComponentProps|extends .*HTMLAttributes|InputHTMLAttributes|ComponentPropsWithoutRef<"input">' .
printf '\n--- autocomplete-search component ---\n'
sed -n '1,120p' registry/autocomplete-search/component.tsx
printf '\n--- any native input prop passthrough in this component ---\n'
rg -n --glob 'registry/autocomplete-search/component.tsx' '...props|{...props}|disabled|required|name=|id=|aria-|tabIndex|autoFocus|form=' registry/autocomplete-search/component.tsx
printf '\n--- registry guidance references ---\n'
rg -n --glob 'README*' --glob 'registry/**' 'extend the relevant HTML/motion props interface|omit conflicting event handlers|registry-facing API' .Repository: pras75299/uniqueui
Length of output: 4922
Extend AutocompleteSearchProps from React.ComponentPropsWithoutRef<"input"> and omit conflicting props like onChange/value. That keeps the API open for standard input attrs such as id, name, disabled, required, and ARIA wiring.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/www/public/r/autocomplete-search.json` at line 16,
AutocompleteSearchProps is too narrow because it only exposes custom props, so
standard input attributes can’t be passed through. Update
AutocompleteSearchProps to extend React.ComponentPropsWithoutRef<"input"> and
omit conflicting controlled props like value and onChange, then forward the
remaining input props from AutocompleteSearch so callers can supply id, name,
disabled, required, and ARIA attributes.
Source: Coding guidelines
| "files": [ | ||
| { | ||
| "path": "autocomplete-search/component.tsx", | ||
| "content": "\"use client\";\n\nimport {\n useCallback,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { Loader2, Search } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\nexport type AutocompleteOption = {\n /** Stable, unique value used as the React key and returned on select. */\n value: string;\n /** Visible text; also what is matched against and highlighted. */\n label: string;\n /** Optional section label — consecutive options sharing it are grouped. */\n group?: string;\n /** Optional secondary line shown under the label. */\n description?: string;\n /** Optional leading icon node. */\n icon?: React.ReactNode;\n};\n\nexport interface AutocompleteSearchProps {\n /** Static option list (synchronous local filtering). Ignored when `onSearch` is set. */\n options?: AutocompleteOption[];\n /** Async resolver — return matching options for a query. Enables async mode. */\n onSearch?: (query: string) => Promise<AutocompleteOption[]>;\n /** Fired when an option is chosen via click or Enter. */\n onSelect?: (option: AutocompleteOption) => void;\n placeholder?: string;\n /** Debounce before filtering/fetching. Default 300ms. */\n debounceMs?: number;\n /** Minimum characters before searching. Default 0. */\n minChars?: number;\n emptyMessage?: string;\n loadingMessage?: string;\n /** Shown when the query is below `minChars` (only if provided). */\n hintMessage?: string;\n errorMessage?: string;\n theme?: \"light\" | \"dark\";\n className?: string;\n}\n\ntype Status = \"idle\" | \"loading\" | \"error\";\n\nexport function AutocompleteSearch({\n options,\n onSearch,\n onSelect,\n placeholder = \"Search…\",\n debounceMs = 300,\n minChars = 0,\n emptyMessage = \"No results found\",\n loadingMessage = \"Searching…\",\n hintMessage,\n errorMessage = \"Something went wrong. Try again.\",\n theme = \"dark\",\n className,\n}: AutocompleteSearchProps) {\n const dark = theme === \"dark\";\n const reduceMotion = useReducedMotion();\n\n const baseId = useId();\n const listboxId = `${baseId}-listbox`;\n const statusId = `${baseId}-status`;\n const optionId = (i: number) => `${baseId}-option-${i}`;\n\n const [query, setQuery] = useState(\"\");\n const [open, setOpen] = useState(false);\n const [results, setResults] = useState<AutocompleteOption[]>([]);\n const [activeIndex, setActiveIndex] = useState(-1);\n const [status, setStatus] = useState<Status>(\"idle\");\n\n const containerRef = useRef<HTMLDivElement>(null);\n const inputRef = useRef<HTMLInputElement>(null);\n const listRef = useRef<HTMLDivElement>(null);\n // Monotonic id so a slow async response can't overwrite a newer query.\n const requestIdRef = useRef(0);\n\n const trimmed = query.trim();\n const belowMin = trimmed.length < minChars;\n\n // Debounced sync filter / async fetch. All state writes live in the timer or\n // promise callback so nothing runs synchronously in the effect body.\n useEffect(() => {\n const timer = setTimeout(() => {\n if (belowMin) {\n requestIdRef.current++; // invalidate any in-flight async result\n setResults([]);\n setActiveIndex(-1);\n setStatus(\"idle\");\n return;\n }\n\n // Sync mode — local case-insensitive substring filter.\n if (!onSearch) {\n const needle = trimmed.toLowerCase();\n const next = (options ?? []).filter((o) =>\n o.label.toLowerCase().includes(needle),\n );\n setResults(next);\n setActiveIndex(next.length ? 0 : -1);\n setStatus(\"idle\");\n return;\n }\n\n // Async mode — fetch with a stale-response guard.\n setStatus(\"loading\");\n const reqId = ++requestIdRef.current;\n onSearch(trimmed)\n .then((next) => {\n if (reqId !== requestIdRef.current) return;\n setResults(next);\n setActiveIndex(next.length ? 0 : -1);\n setStatus(\"idle\");\n })\n .catch(() => {\n if (reqId !== requestIdRef.current) return;\n setResults([]);\n setActiveIndex(-1);\n setStatus(\"error\");\n });\n }, debounceMs);\n return () => clearTimeout(timer);\n }, [trimmed, belowMin, onSearch, options, debounceMs]);\n\n // Close on outside pointer interaction.\n useEffect(() => {\n if (!open) return;\n function onPointerDown(e: PointerEvent) {\n if (!containerRef.current?.contains(e.target as Node)) {\n setOpen(false);\n setActiveIndex(-1);\n }\n }\n document.addEventListener(\"pointerdown\", onPointerDown);\n return () => document.removeEventListener(\"pointerdown\", onPointerDown);\n }, [open]);\n\n // Keep the active option scrolled into view during keyboard navigation.\n useEffect(() => {\n if (!open || activeIndex < 0) return;\n listRef.current\n ?.querySelector<HTMLElement>(`[data-index=\"${activeIndex}\"]`)\n ?.scrollIntoView({ block: \"nearest\" });\n }, [activeIndex, open]);\n\n const select = useCallback(\n (option: AutocompleteOption) => {\n setQuery(option.label);\n setOpen(false);\n setActiveIndex(-1);\n onSelect?.(option);\n inputRef.current?.focus();\n },\n [onSelect],\n );\n\n const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n switch (e.key) {\n case \"ArrowDown\":\n e.preventDefault();\n if (!open) {\n setOpen(true);\n break;\n }\n setActiveIndex((i) => (results.length ? (i + 1) % results.length : -1));\n break;\n case \"ArrowUp\":\n e.preventDefault();\n if (!open) {\n setOpen(true);\n break;\n }\n setActiveIndex((i) =>\n results.length ? (i - 1 + results.length) % results.length : -1,\n );\n break;\n case \"Enter\":\n if (open && activeIndex >= 0 && results[activeIndex]) {\n e.preventDefault();\n select(results[activeIndex]);\n }\n break;\n case \"Escape\":\n if (open) {\n setOpen(false);\n setActiveIndex(-1);\n } else if (query) {\n setQuery(\"\");\n }\n break;\n }\n };\n\n // Group consecutive options that share a `group` label.\n const sections = useMemo(() => {\n const out: {\n group?: string;\n items: { option: AutocompleteOption; index: number }[];\n }[] = [];\n results.forEach((option, index) => {\n const last = out[out.length - 1];\n if (last && last.group === option.group) {\n last.items.push({ option, index });\n } else {\n out.push({ group: option.group, items: [{ option, index }] });\n }\n });\n return out;\n }, [results]);\n\n const showLoading = open && status === \"loading\";\n const showError = open && status === \"error\";\n const showList = open && status === \"idle\" && results.length > 0;\n const showHint = open && belowMin && !!hintMessage;\n const showEmpty =\n open && status === \"idle\" && !belowMin && results.length === 0;\n const dropdownOpen =\n showLoading || showError || showList || showHint || showEmpty;\n\n const statusText = showLoading\n ? loadingMessage\n : showError\n ? errorMessage\n : showList\n ? `${results.length} result${results.length === 1 ? \"\" : \"s\"} available`\n : showEmpty\n ? emptyMessage\n : \"\";\n\n return (\n <div\n ref={containerRef}\n className={cn(\"relative w-full max-w-md\", className)}\n >\n <div className=\"relative\">\n <Search\n aria-hidden\n className={cn(\n \"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n />\n <input\n ref={inputRef}\n type=\"text\"\n role=\"combobox\"\n aria-expanded={dropdownOpen}\n aria-controls={listboxId}\n aria-autocomplete=\"list\"\n aria-activedescendant={\n showList && activeIndex >= 0 ? optionId(activeIndex) : undefined\n }\n aria-label={placeholder}\n autoComplete=\"off\"\n spellCheck={false}\n value={query}\n placeholder={placeholder}\n onChange={(e) => {\n setQuery(e.target.value);\n setOpen(true);\n }}\n onFocus={() => setOpen(true)}\n onKeyDown={onKeyDown}\n className={cn(\n \"w-full rounded-xl border py-2.5 pl-9 pr-9 text-sm outline-none transition-colors\",\n dark\n ? \"border-neutral-800 bg-neutral-900 text-neutral-100 placeholder:text-neutral-500 focus:border-neutral-600\"\n : \"border-neutral-200 bg-white text-neutral-900 placeholder:text-neutral-400 focus:border-neutral-400\",\n )}\n />\n {showLoading && (\n <Loader2\n aria-hidden\n className={cn(\n \"absolute right-3 top-1/2 size-4 -translate-y-1/2 animate-spin\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n />\n )}\n </div>\n\n <div id={statusId} role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n {statusText}\n </div>\n\n <AnimatePresence>\n {dropdownOpen && (\n <motion.div\n initial={reduceMotion ? false : { opacity: 0, y: -4, scale: 0.98 }}\n animate={{ opacity: 1, y: 0, scale: 1 }}\n exit={\n reduceMotion\n ? { opacity: 0 }\n : { opacity: 0, y: -4, scale: 0.98 }\n }\n transition={\n reduceMotion\n ? { duration: 0 }\n : { type: \"spring\", stiffness: 520, damping: 36 }\n }\n className={cn(\n \"absolute z-50 mt-2 w-full overflow-hidden rounded-xl border shadow-xl\",\n dark\n ? \"border-neutral-800 bg-neutral-900\"\n : \"border-neutral-200 bg-white\",\n )}\n >\n {showLoading && (\n <div\n className={cn(\n \"flex items-center gap-2 px-3 py-3 text-sm\",\n dark ? \"text-neutral-400\" : \"text-neutral-500\",\n )}\n >\n <Loader2 aria-hidden className=\"size-4 animate-spin\" />\n {loadingMessage}\n </div>\n )}\n\n {showError && (\n <div\n className={cn(\n \"px-3 py-3 text-sm\",\n dark ? \"text-red-400\" : \"text-red-600\",\n )}\n >\n {errorMessage}\n </div>\n )}\n\n {showHint && (\n <div\n className={cn(\n \"px-3 py-3 text-sm\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n >\n {hintMessage}\n </div>\n )}\n\n {showEmpty && (\n <div\n className={cn(\n \"px-3 py-3 text-sm\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n >\n {emptyMessage}\n </div>\n )}\n\n {showList && (\n <div\n ref={listRef}\n id={listboxId}\n role=\"listbox\"\n aria-label={placeholder}\n // Keep input focus when clicking an option.\n onMouseDown={(e) => e.preventDefault()}\n className=\"max-h-72 overflow-y-auto p-1\"\n >\n {sections.map((section, si) => (\n <div\n key={section.group ?? `section-${si}`}\n role={section.group ? \"group\" : undefined}\n aria-label={section.group}\n >\n {section.group && (\n <div\n aria-hidden\n className={cn(\n \"px-2.5 pb-1 pt-2 text-[11px] font-semibold uppercase tracking-wider\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n >\n {section.group}\n </div>\n )}\n {section.items.map(({ option, index }) => {\n const active = index === activeIndex;\n return (\n <div\n key={option.value}\n id={optionId(index)}\n data-index={index}\n role=\"option\"\n aria-selected={active}\n onClick={() => select(option)}\n onMouseMove={() => setActiveIndex(index)}\n className={cn(\n \"flex cursor-pointer items-center gap-2.5 rounded-lg px-2.5 py-2 text-sm transition-colors\",\n active\n ? dark\n ? \"bg-neutral-800 text-neutral-100\"\n : \"bg-neutral-100 text-neutral-900\"\n : dark\n ? \"text-neutral-300\"\n : \"text-neutral-700\",\n )}\n >\n {option.icon && (\n <span className=\"flex size-4 shrink-0 items-center justify-center\">\n {option.icon}\n </span>\n )}\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate\">\n {highlightMatch(option.label, trimmed, dark)}\n </span>\n {option.description && (\n <span\n className={cn(\n \"block truncate text-xs\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n >\n {option.description}\n </span>\n )}\n </span>\n </div>\n );\n })}\n </div>\n ))}\n </div>\n )}\n </motion.div>\n )}\n </AnimatePresence>\n </div>\n );\n}\n\n/** Bold the first case-insensitive substring of `query` within `label`. */\nfunction highlightMatch(label: string, query: string, dark: boolean) {\n if (!query) return label;\n const i = label.toLowerCase().indexOf(query.toLowerCase());\n if (i === -1) return label;\n return (\n <>\n {label.slice(0, i)}\n <span\n className={cn(\"font-semibold\", dark ? \"text-purple-400\" : \"text-purple-600\")}\n >\n {label.slice(i, i + query.length)}\n </span>\n {label.slice(i + query.length)}\n </>\n );\n}\n", |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Invalidate pending async searches on unmount.
Line 12's embedded AutocompleteSearch cleanup only clears the debounce timer. If onSearch resolves after unmount, the matching reqId still allows the promise callback to commit state. Invalidate in-flight requests in the cleanup as well.
Proposed fix
useEffect(() => {
const timer = setTimeout(() => {
// ...
}, debounceMs);
- return () => clearTimeout(timer);
+ return () => {
+ clearTimeout(timer);
+ requestIdRef.current++;
+ };
}, [trimmed, belowMin, onSearch, options, debounceMs]);As per coding guidelines, "Cleanup: Cancel rAF / useAnimationFrame / subscriptions on unmount".
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "content": "\"use client\";\n\nimport {\n useCallback,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { Loader2, Search } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\nexport type AutocompleteOption = {\n /** Stable, unique value used as the React key and returned on select. */\n value: string;\n /** Visible text; also what is matched against and highlighted. */\n label: string;\n /** Optional section label — consecutive options sharing it are grouped. */\n group?: string;\n /** Optional secondary line shown under the label. */\n description?: string;\n /** Optional leading icon node. */\n icon?: React.ReactNode;\n};\n\nexport interface AutocompleteSearchProps {\n /** Static option list (synchronous local filtering). Ignored when `onSearch` is set. */\n options?: AutocompleteOption[];\n /** Async resolver — return matching options for a query. Enables async mode. */\n onSearch?: (query: string) => Promise<AutocompleteOption[]>;\n /** Fired when an option is chosen via click or Enter. */\n onSelect?: (option: AutocompleteOption) => void;\n placeholder?: string;\n /** Debounce before filtering/fetching. Default 300ms. */\n debounceMs?: number;\n /** Minimum characters before searching. Default 0. */\n minChars?: number;\n emptyMessage?: string;\n loadingMessage?: string;\n /** Shown when the query is below `minChars` (only if provided). */\n hintMessage?: string;\n errorMessage?: string;\n theme?: \"light\" | \"dark\";\n className?: string;\n}\n\ntype Status = \"idle\" | \"loading\" | \"error\";\n\nexport function AutocompleteSearch({\n options,\n onSearch,\n onSelect,\n placeholder = \"Search…\",\n debounceMs = 300,\n minChars = 0,\n emptyMessage = \"No results found\",\n loadingMessage = \"Searching…\",\n hintMessage,\n errorMessage = \"Something went wrong. Try again.\",\n theme = \"dark\",\n className,\n}: AutocompleteSearchProps) {\n const dark = theme === \"dark\";\n const reduceMotion = useReducedMotion();\n\n const baseId = useId();\n const listboxId = `${baseId}-listbox`;\n const statusId = `${baseId}-status`;\n const optionId = (i: number) => `${baseId}-option-${i}`;\n\n const [query, setQuery] = useState(\"\");\n const [open, setOpen] = useState(false);\n const [results, setResults] = useState<AutocompleteOption[]>([]);\n const [activeIndex, setActiveIndex] = useState(-1);\n const [status, setStatus] = useState<Status>(\"idle\");\n\n const containerRef = useRef<HTMLDivElement>(null);\n const inputRef = useRef<HTMLInputElement>(null);\n const listRef = useRef<HTMLDivElement>(null);\n // Monotonic id so a slow async response can't overwrite a newer query.\n const requestIdRef = useRef(0);\n\n const trimmed = query.trim();\n const belowMin = trimmed.length < minChars;\n\n // Debounced sync filter / async fetch. All state writes live in the timer or\n // promise callback so nothing runs synchronously in the effect body.\n useEffect(() => {\n const timer = setTimeout(() => {\n if (belowMin) {\n requestIdRef.current++; // invalidate any in-flight async result\n setResults([]);\n setActiveIndex(-1);\n setStatus(\"idle\");\n return;\n }\n\n // Sync mode — local case-insensitive substring filter.\n if (!onSearch) {\n const needle = trimmed.toLowerCase();\n const next = (options ?? []).filter((o) =>\n o.label.toLowerCase().includes(needle),\n );\n setResults(next);\n setActiveIndex(next.length ? 0 : -1);\n setStatus(\"idle\");\n return;\n }\n\n // Async mode — fetch with a stale-response guard.\n setStatus(\"loading\");\n const reqId = ++requestIdRef.current;\n onSearch(trimmed)\n .then((next) => {\n if (reqId !== requestIdRef.current) return;\n setResults(next);\n setActiveIndex(next.length ? 0 : -1);\n setStatus(\"idle\");\n })\n .catch(() => {\n if (reqId !== requestIdRef.current) return;\n setResults([]);\n setActiveIndex(-1);\n setStatus(\"error\");\n });\n }, debounceMs);\n return () => clearTimeout(timer);\n }, [trimmed, belowMin, onSearch, options, debounceMs]);\n\n // Close on outside pointer interaction.\n useEffect(() => {\n if (!open) return;\n function onPointerDown(e: PointerEvent) {\n if (!containerRef.current?.contains(e.target as Node)) {\n setOpen(false);\n setActiveIndex(-1);\n }\n }\n document.addEventListener(\"pointerdown\", onPointerDown);\n return () => document.removeEventListener(\"pointerdown\", onPointerDown);\n }, [open]);\n\n // Keep the active option scrolled into view during keyboard navigation.\n useEffect(() => {\n if (!open || activeIndex < 0) return;\n listRef.current\n ?.querySelector<HTMLElement>(`[data-index=\"${activeIndex}\"]`)\n ?.scrollIntoView({ block: \"nearest\" });\n }, [activeIndex, open]);\n\n const select = useCallback(\n (option: AutocompleteOption) => {\n setQuery(option.label);\n setOpen(false);\n setActiveIndex(-1);\n onSelect?.(option);\n inputRef.current?.focus();\n },\n [onSelect],\n );\n\n const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n switch (e.key) {\n case \"ArrowDown\":\n e.preventDefault();\n if (!open) {\n setOpen(true);\n break;\n }\n setActiveIndex((i) => (results.length ? (i + 1) % results.length : -1));\n break;\n case \"ArrowUp\":\n e.preventDefault();\n if (!open) {\n setOpen(true);\n break;\n }\n setActiveIndex((i) =>\n results.length ? (i - 1 + results.length) % results.length : -1,\n );\n break;\n case \"Enter\":\n if (open && activeIndex >= 0 && results[activeIndex]) {\n e.preventDefault();\n select(results[activeIndex]);\n }\n break;\n case \"Escape\":\n if (open) {\n setOpen(false);\n setActiveIndex(-1);\n } else if (query) {\n setQuery(\"\");\n }\n break;\n }\n };\n\n // Group consecutive options that share a `group` label.\n const sections = useMemo(() => {\n const out: {\n group?: string;\n items: { option: AutocompleteOption; index: number }[];\n }[] = [];\n results.forEach((option, index) => {\n const last = out[out.length - 1];\n if (last && last.group === option.group) {\n last.items.push({ option, index });\n } else {\n out.push({ group: option.group, items: [{ option, index }] });\n }\n });\n return out;\n }, [results]);\n\n const showLoading = open && status === \"loading\";\n const showError = open && status === \"error\";\n const showList = open && status === \"idle\" && results.length > 0;\n const showHint = open && belowMin && !!hintMessage;\n const showEmpty =\n open && status === \"idle\" && !belowMin && results.length === 0;\n const dropdownOpen =\n showLoading || showError || showList || showHint || showEmpty;\n\n const statusText = showLoading\n ? loadingMessage\n : showError\n ? errorMessage\n : showList\n ? `${results.length} result${results.length === 1 ? \"\" : \"s\"} available`\n : showEmpty\n ? emptyMessage\n : \"\";\n\n return (\n <div\n ref={containerRef}\n className={cn(\"relative w-full max-w-md\", className)}\n >\n <div className=\"relative\">\n <Search\n aria-hidden\n className={cn(\n \"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n />\n <input\n ref={inputRef}\n type=\"text\"\n role=\"combobox\"\n aria-expanded={dropdownOpen}\n aria-controls={listboxId}\n aria-autocomplete=\"list\"\n aria-activedescendant={\n showList && activeIndex >= 0 ? optionId(activeIndex) : undefined\n }\n aria-label={placeholder}\n autoComplete=\"off\"\n spellCheck={false}\n value={query}\n placeholder={placeholder}\n onChange={(e) => {\n setQuery(e.target.value);\n setOpen(true);\n }}\n onFocus={() => setOpen(true)}\n onKeyDown={onKeyDown}\n className={cn(\n \"w-full rounded-xl border py-2.5 pl-9 pr-9 text-sm outline-none transition-colors\",\n dark\n ? \"border-neutral-800 bg-neutral-900 text-neutral-100 placeholder:text-neutral-500 focus:border-neutral-600\"\n : \"border-neutral-200 bg-white text-neutral-900 placeholder:text-neutral-400 focus:border-neutral-400\",\n )}\n />\n {showLoading && (\n <Loader2\n aria-hidden\n className={cn(\n \"absolute right-3 top-1/2 size-4 -translate-y-1/2 animate-spin\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n />\n )}\n </div>\n\n <div id={statusId} role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n {statusText}\n </div>\n\n <AnimatePresence>\n {dropdownOpen && (\n <motion.div\n initial={reduceMotion ? false : { opacity: 0, y: -4, scale: 0.98 }}\n animate={{ opacity: 1, y: 0, scale: 1 }}\n exit={\n reduceMotion\n ? { opacity: 0 }\n : { opacity: 0, y: -4, scale: 0.98 }\n }\n transition={\n reduceMotion\n ? { duration: 0 }\n : { type: \"spring\", stiffness: 520, damping: 36 }\n }\n className={cn(\n \"absolute z-50 mt-2 w-full overflow-hidden rounded-xl border shadow-xl\",\n dark\n ? \"border-neutral-800 bg-neutral-900\"\n : \"border-neutral-200 bg-white\",\n )}\n >\n {showLoading && (\n <div\n className={cn(\n \"flex items-center gap-2 px-3 py-3 text-sm\",\n dark ? \"text-neutral-400\" : \"text-neutral-500\",\n )}\n >\n <Loader2 aria-hidden className=\"size-4 animate-spin\" />\n {loadingMessage}\n </div>\n )}\n\n {showError && (\n <div\n className={cn(\n \"px-3 py-3 text-sm\",\n dark ? \"text-red-400\" : \"text-red-600\",\n )}\n >\n {errorMessage}\n </div>\n )}\n\n {showHint && (\n <div\n className={cn(\n \"px-3 py-3 text-sm\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n >\n {hintMessage}\n </div>\n )}\n\n {showEmpty && (\n <div\n className={cn(\n \"px-3 py-3 text-sm\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n >\n {emptyMessage}\n </div>\n )}\n\n {showList && (\n <div\n ref={listRef}\n id={listboxId}\n role=\"listbox\"\n aria-label={placeholder}\n // Keep input focus when clicking an option.\n onMouseDown={(e) => e.preventDefault()}\n className=\"max-h-72 overflow-y-auto p-1\"\n >\n {sections.map((section, si) => (\n <div\n key={section.group ?? `section-${si}`}\n role={section.group ? \"group\" : undefined}\n aria-label={section.group}\n >\n {section.group && (\n <div\n aria-hidden\n className={cn(\n \"px-2.5 pb-1 pt-2 text-[11px] font-semibold uppercase tracking-wider\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n >\n {section.group}\n </div>\n )}\n {section.items.map(({ option, index }) => {\n const active = index === activeIndex;\n return (\n <div\n key={option.value}\n id={optionId(index)}\n data-index={index}\n role=\"option\"\n aria-selected={active}\n onClick={() => select(option)}\n onMouseMove={() => setActiveIndex(index)}\n className={cn(\n \"flex cursor-pointer items-center gap-2.5 rounded-lg px-2.5 py-2 text-sm transition-colors\",\n active\n ? dark\n ? \"bg-neutral-800 text-neutral-100\"\n : \"bg-neutral-100 text-neutral-900\"\n : dark\n ? \"text-neutral-300\"\n : \"text-neutral-700\",\n )}\n >\n {option.icon && (\n <span className=\"flex size-4 shrink-0 items-center justify-center\">\n {option.icon}\n </span>\n )}\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate\">\n {highlightMatch(option.label, trimmed, dark)}\n </span>\n {option.description && (\n <span\n className={cn(\n \"block truncate text-xs\",\n dark ? \"text-neutral-500\" : \"text-neutral-400\",\n )}\n >\n {option.description}\n </span>\n )}\n </span>\n </div>\n );\n })}\n </div>\n ))}\n </div>\n )}\n </motion.div>\n )}\n </AnimatePresence>\n </div>\n );\n}\n\n/** Bold the first case-insensitive substring of `query` within `label`. */\nfunction highlightMatch(label: string, query: string, dark: boolean) {\n if (!query) return label;\n const i = label.toLowerCase().indexOf(query.toLowerCase());\n if (i === -1) return label;\n return (\n <>\n {label.slice(0, i)}\n <span\n className={cn(\"font-semibold\", dark ? \"text-purple-400\" : \"text-purple-600\")}\n >\n {label.slice(i, i + query.length)}\n </span>\n {label.slice(i + query.length)}\n </>\n );\n}\n", | |
| // Debounced sync filter / async fetch. All state writes live in the timer or | |
| // promise callback so nothing runs synchronously in the effect body. | |
| useEffect(() => { | |
| const timer = setTimeout(() => { | |
| if (belowMin) { | |
| requestIdRef.current++; // invalidate any in-flight async result | |
| setResults([]); | |
| setActiveIndex(-1); | |
| setStatus("idle"); | |
| return; | |
| } | |
| // Sync mode — local case-insensitive substring filter. | |
| if (!onSearch) { | |
| const needle = trimmed.toLowerCase(); | |
| const next = (options ?? []).filter((o) => | |
| o.label.toLowerCase().includes(needle), | |
| ); | |
| setResults(next); | |
| setActiveIndex(next.length ? 0 : -1); | |
| setStatus("idle"); | |
| return; | |
| } | |
| // Async mode — fetch with a stale-response guard. | |
| setStatus("loading"); | |
| const reqId = ++requestIdRef.current; | |
| onSearch(trimmed) | |
| .then((next) => { | |
| if (reqId !== requestIdRef.current) return; | |
| setResults(next); | |
| setActiveIndex(next.length ? 0 : -1); | |
| setStatus("idle"); | |
| }) | |
| .catch(() => { | |
| if (reqId !== requestIdRef.current) return; | |
| setResults([]); | |
| setActiveIndex(-1); | |
| setStatus("error"); | |
| }); | |
| }, debounceMs); | |
| return () => { | |
| clearTimeout(timer); | |
| requestIdRef.current++; | |
| }; | |
| }, [trimmed, belowMin, onSearch, options, debounceMs]); |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/www/public/registry/autocomplete-search.json` at line 12, The
AutocompleteSearch effect only clears the debounce timer on cleanup, so a
pending onSearch promise can still resolve after unmount and update state.
Update the useEffect in AutocompleteSearch to also invalidate in-flight async
requests during cleanup by bumping requestIdRef (and keep the existing timer
cleanup), so stale promise callbacks in the reqId guard cannot commit results
after unmount.
Source: Coding guidelines
| useEffect(() => { | ||
| const timer = setTimeout(() => { | ||
| if (belowMin) { | ||
| requestIdRef.current++; // invalidate any in-flight async result | ||
| setResults([]); | ||
| setActiveIndex(-1); | ||
| setStatus("idle"); | ||
| return; | ||
| } | ||
|
|
||
| // Sync mode — local case-insensitive substring filter. | ||
| if (!onSearch) { | ||
| const needle = trimmed.toLowerCase(); | ||
| const next = (options ?? []).filter((o) => | ||
| o.label.toLowerCase().includes(needle), | ||
| ); | ||
| setResults(next); | ||
| setActiveIndex(next.length ? 0 : -1); | ||
| setStatus("idle"); | ||
| return; | ||
| } | ||
|
|
||
| // Async mode — fetch with a stale-response guard. | ||
| setStatus("loading"); | ||
| const reqId = ++requestIdRef.current; | ||
| onSearch(trimmed) | ||
| .then((next) => { | ||
| if (reqId !== requestIdRef.current) return; | ||
| setResults(next); | ||
| setActiveIndex(next.length ? 0 : -1); | ||
| setStatus("idle"); | ||
| }) | ||
| .catch(() => { | ||
| if (reqId !== requestIdRef.current) return; | ||
| setResults([]); | ||
| setActiveIndex(-1); | ||
| setStatus("error"); | ||
| }); | ||
| }, debounceMs); | ||
| return () => clearTimeout(timer); | ||
| }, [trimmed, belowMin, onSearch, options, debounceMs]); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Invalidate in-flight async searches during cleanup.
clearTimeout(timer) only cancels unsent work. If onSearch(trimmed) is already pending, a query change leaves the old reqId valid until the next debounce timer fires, so a slow response can briefly overwrite newer results.
Proposed fix
useEffect(() => {
const timer = setTimeout(() => {
if (belowMin) {
- requestIdRef.current++; // invalidate any in-flight async result
setResults([]);
setActiveIndex(-1);
setStatus("idle");
return;
}
@@
// Async mode — fetch with a stale-response guard.
setStatus("loading");
const reqId = ++requestIdRef.current;
@@
- return () => clearTimeout(timer);
+ return () => {
+ clearTimeout(timer);
+ requestIdRef.current++;
+ };
}, [trimmed, belowMin, onSearch, options, debounceMs]);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| useEffect(() => { | |
| const timer = setTimeout(() => { | |
| if (belowMin) { | |
| requestIdRef.current++; // invalidate any in-flight async result | |
| setResults([]); | |
| setActiveIndex(-1); | |
| setStatus("idle"); | |
| return; | |
| } | |
| // Sync mode — local case-insensitive substring filter. | |
| if (!onSearch) { | |
| const needle = trimmed.toLowerCase(); | |
| const next = (options ?? []).filter((o) => | |
| o.label.toLowerCase().includes(needle), | |
| ); | |
| setResults(next); | |
| setActiveIndex(next.length ? 0 : -1); | |
| setStatus("idle"); | |
| return; | |
| } | |
| // Async mode — fetch with a stale-response guard. | |
| setStatus("loading"); | |
| const reqId = ++requestIdRef.current; | |
| onSearch(trimmed) | |
| .then((next) => { | |
| if (reqId !== requestIdRef.current) return; | |
| setResults(next); | |
| setActiveIndex(next.length ? 0 : -1); | |
| setStatus("idle"); | |
| }) | |
| .catch(() => { | |
| if (reqId !== requestIdRef.current) return; | |
| setResults([]); | |
| setActiveIndex(-1); | |
| setStatus("error"); | |
| }); | |
| }, debounceMs); | |
| return () => clearTimeout(timer); | |
| }, [trimmed, belowMin, onSearch, options, debounceMs]); | |
| useEffect(() => { | |
| const timer = setTimeout(() => { | |
| if (belowMin) { | |
| setResults([]); | |
| setActiveIndex(-1); | |
| setStatus("idle"); | |
| return; | |
| } | |
| // Sync mode — local case-insensitive substring filter. | |
| if (!onSearch) { | |
| const needle = trimmed.toLowerCase(); | |
| const next = (options ?? []).filter((o) => | |
| o.label.toLowerCase().includes(needle), | |
| ); | |
| setResults(next); | |
| setActiveIndex(next.length ? 0 : -1); | |
| setStatus("idle"); | |
| return; | |
| } | |
| // Async mode — fetch with a stale-response guard. | |
| setStatus("loading"); | |
| const reqId = ++requestIdRef.current; | |
| onSearch(trimmed) | |
| .then((next) => { | |
| if (reqId !== requestIdRef.current) return; | |
| setResults(next); | |
| setActiveIndex(next.length ? 0 : -1); | |
| setStatus("idle"); | |
| }) | |
| .catch(() => { | |
| if (reqId !== requestIdRef.current) return; | |
| setResults([]); | |
| setActiveIndex(-1); | |
| setStatus("error"); | |
| }); | |
| }, debounceMs); | |
| return () => { | |
| clearTimeout(timer); | |
| requestIdRef.current++; | |
| }; | |
| }, [trimmed, belowMin, onSearch, options, debounceMs]); |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@registry/autocomplete-search/component.tsx` around lines 90 - 130, Invalidate
any pending async search when the effect cleans up, not just the debounce timer.
In `AutocompleteSearch`’s `useEffect`, the current `clearTimeout(timer)` only
stops the scheduled callback, so an already-started `onSearch(trimmed)` can
still resolve with a stale `reqId`. Update the cleanup to also bump
`requestIdRef.current` (or otherwise mark the current request stale) so old
responses from `onSearch` are ignored immediately when `trimmed`, `belowMin`, or
`onSearch` changes.
Type
Summary
Adds a new free-tier Autocomplete Search combobox to the registry, and surfaces live GitHub stars / forks and total npm downloads in the site header so visitors can see project traction at a glance. Also adds the missing Components category tab to
/components(six existing components, incl. the new one, were only reachable under "All").Screenshots / video (UI changes only)
Header stats —
★ 5 │ ⑂ 0 │ ⬇ 762(stars · forks · npm downloads), rendered before the GitHub link, hidden below thelgbreakpoint.Autocomplete — typing filters the list with matched-text highlighting, grouped sections, full keyboard nav, and loading/empty states; verified live in the dev server. (Local screenshots captured during review; can attach on request.)
Test plan
pnpm test— all suites pass (cli-core 192, www 115, registry-schema 55)pnpm build:registry— generated artifacts regenerated; diff limited to the new slug (+ expected cross-link intomulti-step-auth-card.json)pnpm --filter uniqueui-cli build— n/a (nopackages/cli/changes)pnpm --dir apps/www exec tsc --noEmit— cleanapps/wwweslint — clean on new/changed filesapps/wwwdev server: card visible under the new Components tab, live demo filtering + keyboard nav, and/api/statsreturning{"stars":5,"forks":0,"downloads":762}New component checklist
Registry sources
registry/autocomplete-search/component.tsxcreatedregistry/components/autocomplete-search.jsoncreated —registryblock (dependencies,files) +docsblock (name, description, category, props, variants, overview, scenarios)orderanddocsOrderinregistry/manifest.jsonregistry/autocomplete-search/demo.tsx, key appended toregistry/demos/demo-key-order.json, import inregistry/demos/shared.tsx)pnpm build:registryrun — generated output matches sourceComponent quality gate (Section I from
backlogs.md)"use client"at the topclassNameand merges viacn(@/lib/utils)motionfrommotion/react; preferstype: "spring"useReducedMotion(instant show/hide fallback for the dropdown)setTimeout/pointerdownlisteners cleaned up on unmount; async fetch has a stale-response guardwindow/documentat module scopearia-activedescendant, polite live region (follows W3C APG editable-combobox-with-list-autocomplete)dependenciesusedcomponent-sync.test.ts/ docs-config testsRelated issues
🤖 Generated with Claude Code
Summary by CodeRabbit