Skip to content

feat(www): add autocomplete-search component and repo stats in site header - #80

Merged
pras75299 merged 3 commits into
mainfrom
feat/autocomplete-and-repo-stats
Jun 29, 2026
Merged

pras75299 merged 3 commits into
mainfrom
feat/autocomplete-and-repo-stats

Conversation

@pras75299

@pras75299 pras75299 commented Jun 29, 2026 •

Copy link
Copy Markdown
Owner

Type

  • New component / block (registry)
  • CLI change (init / add / list / info / doctor / search / shadcn JSON)
  • Docs site (apps/www)
  • Build / scripts / CI
  • Bug fix
  • Refactor / chore

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 the lg breakpoint.

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 into multi-step-auth-card.json)
  • pnpm --filter uniqueui-cli build — n/a (no packages/cli/ changes)
  • pnpm --dir apps/www exec tsc --noEmit — clean
  • apps/www eslint — clean on new/changed files
  • Manually verified in apps/www dev server: card visible under the new Components tab, live demo filtering + keyboard nav, and /api/stats returning {"stars":5,"forks":0,"downloads":762}

New component checklist

Registry sources

  • registry/autocomplete-search/component.tsx created
  • registry/components/autocomplete-search.json created — registry block (dependencies, files) + docs block (name, description, category, props, variants, overview, scenarios)
  • Slug added to order and docsOrder in registry/manifest.json
  • Demo added (registry/autocomplete-search/demo.tsx, key appended to registry/demos/demo-key-order.json, import in registry/demos/shared.tsx)
  • pnpm build:registry run — generated output matches source

Component quality gate (Section I from backlogs.md)

  • "use client" at the top
  • Accepts className and merges via cn (@/lib/utils)
  • Uses motion from motion/react; prefers type: "spring"
  • Honors useReducedMotion (instant show/hide fallback for the dropdown)
  • No layout shift on mount
  • All setTimeout / pointerdown listeners cleaned up on unmount; async fetch has a stale-response guard
  • SSR-safe — no window/document at module scope
  • Keyboard operable + correct combobox/listbox/option roles, aria-activedescendant, polite live region (follows W3C APG editable-combobox-with-list-autocomplete)
  • No cross-imports; only declared dependencies used
  • Covered by the auto-enumerating component-sync.test.ts / docs-config tests

Related issues

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added a new autocomplete search component with keyboard navigation, grouped results, and support for both local filtering and async search.
    • Displayed live repository stats in the site header.
    • Added a new “Components” category in the component browser.
  • Bug Fixes
    • Improved async search behavior to avoid showing outdated results.
    • Added loading, empty, and error states for search results.
  • Chores
    • Updated ignored files to exclude local premium markdown content.

@vercel

vercel Bot commented Jun 29, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
uniqueui-platform Ready Ready Preview, Comment Jun 29, 2026 9:32am

@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@pras75299, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 12 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7a93bc79-3d59-4421-91e5-676af648d24e

📥 Commits

Reviewing files that changed from the base of the PR and between 5988c26 and 1db20bd.

📒 Files selected for processing (1)
  • apps/www/app/api/stats/route.ts
📝 Walkthrough

Walkthrough

Adds a new AutocompleteSearch combobox component with debounced sync/async search, keyboard navigation, grouped options, ARIA roles, and animated dropdown. Also adds a RepoStats header widget backed by a new /api/stats Next.js route fetching GitHub and NPM statistics. Both components are wired into all registry manifests, demo configs, and generated JSON artifacts.

Changes

AutocompleteSearch Component

Layer / File(s) Summary
Component types and core implementation
registry/autocomplete-search/component.tsx, apps/www/components/ui/autocomplete-search.tsx
Defines AutocompleteOption and AutocompleteSearchProps; implements debounced sync/async search with a monotonic request-id stale-response guard, open/close state, keyboard navigation (Up/Down/Enter/Escape), outside-pointer dismissal, active-option auto-scroll, grouped option rendering, substring highlighting, and animated dropdown with ARIA combobox/listbox/option roles and aria-live status region.
Demo entries and shared wiring
registry/autocomplete-search/demo.tsx, registry/demos/shared.tsx, registry/demos/demo-key-order.json, apps/www/config/demos.tsx, apps/www/config/docs-scenarios.ts
Adds three demo variants (basic, grouped, async) including a promise-based async onSearch demo with delayed country filtering; updates shared imports, demo key ordering, and docs scenarios.
Registry manifests and generated artifacts
registry/components/autocomplete-search.json, registry/manifest.json, apps/www/public/registry/*, apps/www/public/r/*, apps/www/public/registry.json, registry.json, apps/www/config/components.ts, apps/www/app/components/page.tsx
Registers autocomplete-search in all registry JSON files, manifests, changelogs, index arrays, and cross-references (relatedSlugs); updates icon map with LucideSearch; adds component definitions with prop schema and usage variants; adds "Components" category to the page filter.

RepoStats Header Widget

Layer / File(s) Summary
Stats API route
apps/www/app/api/stats/route.ts
New Next.js route fetches GitHub stars/forks and NPM all-time downloads concurrently via Promise.all, returns merged JSON with Cache-Control public caching and 1-hour revalidate.
RepoStats component and SiteHeader integration
apps/www/components/repo-stats.tsx, apps/www/components/site-header.tsx
RepoStats fetches /api/stats on mount with unmount guard, formats values with compact Intl.NumberFormat, renders animated skeleton placeholders until loaded, and is inserted into SiteHeader's right-side control cluster.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • pras75299/uniqueui#36: Also modifies apps/www/components/site-header.tsx, which this PR extends by inserting RepoStats into the same layout area.
  • pras75299/uniqueui#66: Established the per-slug registry manifest architecture that this PR's registry/components/autocomplete-search.json and manifest ordering entries depend on.

Poem

🐇 Hop hop, a search box appears!
With arrows and Enter, no fears.
Stars, forks, downloads shine bright,
In the header's top-right light.
The registry grows, the bunny cheers! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is clear, conventional, and reflects the main addition of the autocomplete-search component and header stats.
Description check ✅ Passed The description follows the template and covers type, summary, screenshots, test plan, checklist, and related issues.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/autocomplete-and-repo-stats

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (2)
apps/www/components/repo-stats.tsx (1)

26-37: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Skip the request when the widget is hidden below lg.

This component is mounted even when hidden lg:flex keeps it invisible, so the effect still calls /api/stats on 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 win

Extend 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 as onChange, onSelect, value, and defaultValue.

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

📥 Commits

Reviewing files that changed from the base of the PR and between f429ada and 5988c26.

📒 Files selected for processing (23)
  • .gitignore
  • apps/www/app/api/stats/route.ts
  • apps/www/app/components/page.tsx
  • apps/www/components/repo-stats.tsx
  • apps/www/components/site-header.tsx
  • apps/www/components/ui/autocomplete-search.tsx
  • apps/www/config/components.ts
  • apps/www/config/demos.tsx
  • apps/www/config/docs-scenarios.ts
  • apps/www/public/r/autocomplete-search.json
  • apps/www/public/r/registry.json
  • apps/www/public/registry.json
  • apps/www/public/registry/autocomplete-search.json
  • apps/www/public/registry/changelogs.json
  • apps/www/public/registry/index.json
  • apps/www/public/registry/multi-step-auth-card.json
  • registry.json
  • registry/autocomplete-search/component.tsx
  • registry/autocomplete-search/demo.tsx
  • registry/components/autocomplete-search.json
  • registry/demos/demo-key-order.json
  • registry/demos/shared.tsx
  • registry/manifest.json

Comment on lines +10 to +35
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 } },
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.ts

Repository: 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.ts

Repository: 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:


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.

Comment on lines +70 to +87
<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>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
<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.

Comment on lines +90 to +130
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]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
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.

Comment on lines +3575 to +3579
"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",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
"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",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.tsx

Repository: 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",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Suggested change
"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

Comment on lines +90 to +130
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]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
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.

@pras75299
pras75299 merged commit e9a7420 into main Jun 29, 2026
11 of 12 checks passed

This branch was successfully deployed

1 active deployment
Preview — 1db20bd8 Deployed Jun 29, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant