Skip to content

Keep search auto-highlight on the first result when results render out of order - #2007

Merged
David Pine (IEvangelist) merged 3 commits into
mainfrom
aspireagent/fix-search-first-result-highlight
Nov 1, 2026
Merged

David Pine (IEvangelist) merged 3 commits into
mainfrom
aspireagent/fix-search-first-result-highlight

Conversation

@davidfowl

@davidfowl David Fowler (davidfowl) commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes a site search bug that also caused an intermittent E2E failure. When Pagefind results render out of order, the dialog highlights a later result instead of the first one. Pressing Enter then opens that wrong result.

CI evidence: the test "arrow keys cycle through results, Tab keeps state, and Escape closes the dialog" passed only on retry on tablet in run 41162894318, job 124426002917. It hit the same failure once more in the Oct 27–30 retry-only scan:

expect(locator).toHaveAttribute(expected) failed
Locator:  locator('site-search dialog[open]').locator('.pagefind-ui__result-link').first()
Expected: "true"   (data-search-active)
Received: ""
14 × locator resolved to <a role="option" aria-selected="false" id="aspire-search-target-0" href="/diagnostics/aspire009/" ...>

Root cause: Pagefind UI 1.5.2 renders each result's .pagefind-ui__result-link only after that result's own fragment loads, so links can appear out of order. SearchKeyboardNav.refresh() in Search.astro then went wrong in two ways:

  1. Wrong result kept. When a later result rendered first, it was auto-highlighted. On the next render, when result 1 appeared, the "preserve previous link" branch kept that later result, as if the user had navigated to it.
  2. First result marked unselected. activeIndex still held the old index while targets was already the new list. setActive therefore "cleared" whichever new target sat at that index, which set aria-selected="false" on result 1.

Fix (Search.astro):

  • Only preserve a highlight the user moved with arrow keys, Home/End or focus/Tab. A new query (input event) resets this, and auto-highlights always go to the first result.
  • Re-index the previously active element in the new target list before calling setActive, so the correct element is cleared.

The intended preservation still works: after ArrowDown/Tab, re-renders keep the user's selection. The existing arrow-key, Tab and API-button navigation tests are unchanged and pass.

Regression test (site-search.spec.ts): "auto-highlights the first result when later results render first". It holds the first pagefind/fragment request until a later result has rendered and been highlighted, then releases it. It asserts that:

  • result 1 gets data-search-active="true" and aria-selected="true"
  • exactly one target is active
  • aria-activedescendant points at result 1
  • Enter opens result 1's URL

The test uses request gating, not sleeps or timeouts.

Review follow-up (c6e30bb): focusing a result that was already auto-highlighted did not count as user navigation, so an earlier result that loaded later could take the highlight while focus stayed on the focused result. handleFocusIn now marks any focused target as user navigation and only calls setActive when the index changes. The second regression test, "keeps the highlight on a focused result when an earlier result renders later", covers this.

Screenshots: Playwright, tablet 1024×768, light theme, search aspire with the first fragment held and then released.

Before (main): the second result (ASPIRE010) stays highlighted.

Before, tablet 1024x768, light theme: second result ASPIRE010 highlighted

After: the first result (ASPIRE009) is highlighted.

After, tablet 1024x768, light theme: first result ASPIRE009 highlighted

Third-party links and affiliations

None.

Validation

Local runs used astro preview serving main's CI frontend-dist artifact (run 41090849945, f05f5561), with retries disabled. The extraction excluded reference/ and most locale folders for disk space.

  • Fail-before (main build): the new test failed 9/9 across desktop, tablet and mobile (×3 each). It failed at toHaveAttribute('data-search-active', 'true') and the element was <a role="option" aria-selected="false" id="aspire-search-target-0" href="/diagnostics/aspire009/">, identical to the CI failure. The existing arrow-key test passed 9/9 in the same run.
  • Probe on main: with only the first fragment delayed, 3/3 runs highlighted result 5 (the second page) and left link 0 at aria-selected="false". At natural timing, 3/3 were correct.
  • Pass-after: the same change was applied to the built Search chunk. The new test and the arrow-key test passed 30/30 (×5 on each of 3 viewports).
  • Full spec: site-search.spec.ts on all 3 projects gave 42 passed and 6 skipped. 6 failed, all from 2 tests that need the omitted /reference/ API pages ("initializes when entering from API pages", "typed query is forwarded…"). Both fail identically on the unpatched main build in the same setup, so the failure comes from the local setup, not this change. CI covers them with the full build.
  • Review follow-up (built from PR head 41ba000, same setup): without the focusin fix, the second test failed 9/9 on desktop, tablet and mobile: the first result got data-search-active="true" while focus stayed on the later result. With the fix applied to the built chunk, both new tests and both arrow-key tests passed 60/60 (×5 on 3 viewports).
  • Lint and units: npx eslint . --max-warnings 0 is clean, and npx vitest run passed 84 files with 1,120 tests passed and 1 skipped.
  • Overlap: no open issue or PR covers this. Add hybrid API docs with on-demand rendering #1874 only rewords test.skip messages in this spec.

🤖 Posted by AspireAgent (AI Agent)

…t of order

Pagefind renders each result after its own fragment loads, so a later
result can render before the first one. SearchKeyboardNav auto-highlighted
that later result, then preserved it on the next render as if the user had
navigated there, and cleared the stale activeIndex against the new target
list, which marked the first result aria-selected=false. Enter then opened
the wrong result and the site-search arrow-key E2E test flaked.

Only preserve highlights the user moved (keyboard or focus), reset on new
query input, and re-index the surviving active element before setActive.
Add an E2E test that holds the first fragment to reproduce deterministically.

Co-authored-by: Copilot <[email protected]>
@aspire-repo-bot

Copy link
Copy Markdown
Contributor

Frontend HTML artifact ready

The latest frontend build uploaded the frontend-dist artifact for PR #2007. Use the VS Code button below to open this PR with GitHub Artifacts Explorer and browse the built HTML locally.

VS Code: Open PR #2007 artifacts

This comment updates automatically when a new frontend build artifact is uploaded.

@davidfowl
David Fowler (davidfowl) marked this pull request as ready for review October 31, 2026 05:10
Copilot AI balanced review requested due to automatic review settings October 31, 2026 05:10

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Focusing an already highlighted search result does not mark user navigation, allowing a later-loading earlier result to move the highlight out of sync with keyboard focus and arrow navigation.

1 open issue
What changed in this PR

This PR fixes site-search selection when Pagefind results render out of order, so automatic highlighting follows the first result rather than the first one loaded.

Changes:

  • Distinguishes automatic highlighting from user navigation and resets that state when the query changes.
  • Re-indexes the previously active element before updating selection.
  • Adds a request-gated regression test covering highlight state, accessibility attributes, and Enter navigation.
File Description
src/​frontend/​tests/​e2e/​site-search.spec.ts Adds regression coverage for out-of-order result rendering.
src/​frontend/​src/​components/​starlight/​Search.astro Updates highlight preservation and active-element tracking.

Review effort: Balanced

Focusing a result that was already auto-highlighted skipped setting
userNavigated, so an earlier result that finished loading later took the
highlight while keyboard focus stayed on the focused result.

Co-authored-by: Copilot <[email protected]>
@IEvangelist

Copy link
Copy Markdown
Member

Project docs review — not applicable

Reviewed PR #2007 against main (base f05f5561b1b858344124cd848ff06469627d7e6e), at head c6e30bb9f49906b75d83869068ac74b7feef7253, using the repository's doc-pr-reviewer skill and its doc-tester dependency.

Phase A — claim verification: No changed documentation claims found. The complete diff changes only the search implementation in src/frontend/src/components/starlight/Search.astro (+20/-1) and its regression tests in src/frontend/tests/e2e/site-search.spec.ts (+88). No documentation pages, examples, Aspire APIs, commands, package/version guidance, or documentation links change. Claims extracted: 0; verified / verified-with-nuance / unverifiable / contradicted: 0 / 0 / 0 / 0. Upstream Aspire/Toolkit/Azure source verification is not applicable; no source repository refs were consulted.

Phase B — blind documentation testing: Not applicable: there are no changed documentation pages, sections, or executable examples to exercise. Routes exercised: none. No docs server, browser, CLI example, or sample project was run, and no documentation checks are represented as passed. Critical issues, warnings, recommendations, and knowledge gaps: not assessed (no applicable documentation scope). Search UI behavior belongs to the subsequent code review, not an invented documentation test.

Outcome: Documentation applicability assessment complete; no documentation-accuracy finding. This is a top-level informational comment, not an approval or change request. The applicable code review follows separately. This one-time docs stage is recorded for the lifetime of this PR, not per head SHA.

@IEvangelist

Copy link
Copy Markdown
Member

Project code review — two coverage gaps

Reviewed the complete two-file diff against main (f05f5561b1b858344124cd848ff06469627d7e6e) at head c6e30bb9f49906b75d83869068ac74b7feef7253, following .agents/skills/code-review/SKILL.md. No new high-confidence implementation defect found; the findings below are missing regression/accessibility coverage, not observed runtime failures.

High — important test coverage

  1. src/frontend/src/components/starlight/Search.astro:118-120 / src/frontend/tests/e2e/site-search.spec.ts:584-670 — Query changes do not have a regression test for clearing intentional selection. Both added tests start from a fresh page and fill the query before navigating. Neither establishes userNavigated = true, returns to the input, changes the query, and verifies that automatic selection resumes. The existing query-clear test asserts API hrefs, not selection. Consequently the new query-input reset could be removed without these regression cases detecting it.

    • Why it matters: A result selected for the previous query could remain selected instead of the new first result when Pagefind reuses the element or the href survives; Enter from the input would open that stale selection.
    • Suggested fix: Add a request-gated case that selects a non-first result, edits the query while the selected href remains among the matches, then verifies that the new first result becomes the only active/selected result, aria-activedescendant follows it, and Enter opens it. Run the existing three viewport projects; ensure this test fails when the reset handler is removed.
  2. src/frontend/tests/e2e/site-search.spec.ts:615-621,663-669 — The changed live search selection has no open-dialog axe audit. These cases check individual selection attributes but do not run AxeBuilder on the populated dialog after out-of-order insertion or focused-result preservation. The existing wcag-aa.spec.ts page audits do not open search, so hidden dialog content is not a substitute for this state.

    • Why it matters: Individual attribute assertions do not establish that the resulting visible combobox/listbox state satisfies the automated accessibility contract. This is a coverage gap, not a claim that axe currently reports a violation.
    • Suggested fix: Add a scoped @axe-core/playwright scan of the open populated dialog after these transitions, using withTags(['wcag2a', 'wcag2aa']), and require zero violations across desktop, tablet, and mobile.

Reviewed behavior and existing discussion

Automatic selection now follows the first rendered result until explicit navigation; surviving active elements are re-indexed before their old marker is cleared. Arrow/Home/End navigation records intent, focus events record intent even when the target is already active, and native Enter on a focused link remains native. Pointer-triggered focus follows the same focus handler; hover alone does not count as navigation. The input reset listener has matching cleanup.

The earlier already-active focus finding is addressed at this head: handleFocusIn sets userNavigated before comparing indices, with the added focused-result regression. It is not being raised again as a new finding. The request-gated tests check that a later result is active while the first result is still absent before releasing the held request; this avoids pretending that ordinary render timing reproduced the race.

Test coverage and evidence

I inspected the existing CI run for this exact head. The two new tests executed and passed, rather than skipped, along with both existing arrow-navigation cases on desktop, tablet, and mobile. The CI command was bun run playwright test --project=<project> --shard=2/2, with each named project above passing. CI bun run test:unit also passed (84 files; 1,120 tests passed, 1 skipped); no focused SearchKeyboardNav unit tests were found. Frontend validation/build and all six E2E shard checks are green. This evidence does not cover the two missing scenarios above.

Limits and cleanup: No local tests, browser session, assistive-technology test, physical-device test, dependency restore, or local production build was performed. Bun and frontend dependencies are absent in this worktree; a dev server would not provide the production Pagefind index needed by these regressions. Viewport evidence is CI Chromium emulation, not real devices. No source changes, checkout switch, server, fixes, push, formal approval/change request, or merge. This is the one-time top-level code report for this PR, independent of future head SHAs.

Add a deterministic regression where a refined query keeps the user's
selection in its results; the new first result must take the highlight
and receive Enter. Run a scoped WCAG A/AA axe audit after out-of-order
insertion, focused-result preservation and the query change.

The audit exposed Pagefind's list items and paragraphs sitting between
the listbox and its options, so mark those wrappers presentational.

Co-authored-by: Copilot <[email protected]>

Copy link
Copy Markdown
Contributor Author

Thanks David Pine (@IEvangelist). Both coverage gaps are addressed in 02a054f, and the new audit found a real issue that's fixed too.

1. Query-change reset regression. The new test a query change hands the highlight back to the new first result stubs the Pagefind backend so results are deterministic. It types alpha (3 results), uses ArrowDown to select the second result, returns to the input and refines the query to alpha beta. The new results still contain the selected page, but not first. The test then asserts that the new first result is the only active/aria-selected option, that aria-activedescendant follows it, and that Enter opens it.

2. Open-dialog axe audit. expectOpenSearchDialogAccessible runs AxeBuilder with wcag2a/wcag2aa on the open search UI (#starlight__search: query combobox plus results listbox). It runs after out-of-order insertion, after focused-result preservation and after the query change.

Defect found by the audit. In every populated state, axe reported aria-required-children, aria-required-parent and listitem. Pagefind's <li> and <p> wrappers sat between role="listbox" and the role="option" links. Search.astro now marks those wrappers role="none". This change has no visual effect.

Validation. I ran the tests locally with Playwright against astro preview of this PR's CI frontend-dist artifact. Per repo guidance, I didn't run a local production build. I applied the one-line Search.astro change to the built bundle to match this commit.

  • Desktop, tablet and mobile Chromium: the 3 selection tests plus the existing arrow/highlight tests all pass (15/15).
  • Negative control: removing the query input reset listener makes the new test fail at the "new first result is active" assertion on all three viewports.
  • Negative control: the unpatched bundle fails all three axe checks with the violations above.
  • custom-components and search-presentation unit suites pass (128 tests). ESLint is clean.

Out of scope. An unscoped dialog scan on mobile also flags Starlight's mobile Cancel button for color contrast: #7455dd on #eceef1 is 4.42:1, below the 4.5:1 minimum. That comes from the site theme, not search selection, so I kept the audit scoped and didn't change it here.

🤖 Posted by AspireAgent (AI Agent)

@IEvangelist
David Pine (IEvangelist) enabled auto-merge (squash) November 1, 2026 14:49
@IEvangelist
David Pine (IEvangelist) merged commit 24367b8 into main Nov 1, 2026
19 checks passed
@IEvangelist
David Pine (IEvangelist) deleted the aspireagent/fix-search-first-result-highlight branch November 1, 2026 14:51
Sébastien Ros (sebastienros) added a commit that referenced this pull request Nov 11, 2026
- TypeScript API parameter descriptions (#2009)
- No locale prefix or hreflang alternates for English-only pages: the footer
  language picker (#1988), hreflang (#1987) and the sidebar Glossary link (#1989)
- Footer link to the Aspire MIT license
- Homepage: environment fade (#1993), stale AppHost animations (#1950), the
  dashboard carousel keeps the selected slide on activation
- Search: first-result highlight with out-of-order renders (#2007), hover cursor
  flicker (#1977)
- Live status over WebSocket (#1942) and twoslash hover, merged into the copies
  of the frontend scripts
- Icon data 5.40.0 and the regenerated sprite
- src/frontend now uses Bun: README and script usage updated
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.

3 participants