Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
useIsWithinMaxBreakpoint,
} from '@elastic/eui'
import { css } from '@emotion/react'
import { useRef, useState, useMemo } from 'react'
import { useEffect, useRef, useState, useMemo } from 'react'

interface Props {
placeholder?: string
Expand Down Expand Up @@ -78,12 +78,76 @@ export const NavigationSearch = ({
setOpen(false)
}

const handleResultClick = (opensElsewhere = false) => {
if (opensElsewhere) return
// The result link whose htmx request is in flight. The dropdown stays up until that request ends, so the reader
// is not left on the old page with no cue. htmx sends from its listener on the link itself, ahead of React's
// delegated onClick, so the click handler already sees it. beforeSend, not beforeRequest: preloads and the
// new-tab and full-page-load paths in htmx-hooks cancel beforeRequest and never send.
const pendingRef = useRef<Element | null>(null)
const [isNavigating, setIsNavigating] = useState(false)
const setPending = (link: Element | null) => {
pendingRef.current = link
setIsNavigating(!!link)
}

const finishNavigation = () => {
setPending(null)
close('navigate')
inputRef.current?.blur()
}

const cancelNavigation = () => {
const link = pendingRef.current
if (!link) return
// Cleared first, so the afterRequest the abort fires is not taken for the end of a navigation.
setPending(null)
link.dispatchEvent(
new CustomEvent('htmx:abort', {
bubbles: true,
detail: { elt: link },
})
)
}

const handleResultClick = (opensElsewhere = false) => {
if (opensElsewhere) return
if (!pendingRef.current) finishNavigation()
}

const finishNavigationRef = useRef(finishNavigation)
finishNavigationRef.current = finishNavigation

useEffect(() => {
const resultLink = (event: Event) => {
const link = (event as CustomEvent<{ elt?: Element }>).detail?.elt
return link?.hasAttribute('data-search-result-index') &&
popoverContentRef.current?.contains(link)
? link
: null
}
// Tab and Enter reach another result while one loads; its request would race the one in flight.
const onBeforeRequest = (event: Event) => {
if (pendingRef.current && resultLink(event)) event.preventDefault()
}
const onBeforeSend = (event: Event) => {
const link = resultLink(event)
if (link) setPending(link)
}
// Fires once the response is swapped in, and on an error, abort or timeout as well.
const onAfterRequest = (event: Event) => {
const link = (event as CustomEvent<{ elt?: Element }>).detail?.elt
if (link && link === pendingRef.current)
finishNavigationRef.current()
}
document.addEventListener('htmx:beforeRequest', onBeforeRequest)
document.addEventListener('htmx:beforeSend', onBeforeSend)
document.addEventListener('htmx:afterRequest', onAfterRequest)
return () => {
document.removeEventListener('htmx:beforeRequest', onBeforeRequest)
document.removeEventListener('htmx:beforeSend', onBeforeSend)
document.removeEventListener('htmx:afterRequest', onAfterRequest)
}
}, [])

const {
inputRef,
isKeyboardNavigating,
Expand All @@ -93,7 +157,6 @@ export const NavigationSearch = ({
resultsCount: navigableRowCount(groups),
isLoading: isSearching,
onClose: () => setOpen(false),
onNavigate: () => handleResultClick(),
typeFilter,
})

Expand All @@ -104,13 +167,15 @@ export const NavigationSearch = ({

const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
cancelNavigation()
setSearchTerm(value)
setOpen(!!value.trim())
}

const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Escape') {
e.preventDefault()
cancelNavigation()
close('escape')
setSearchTerm('')
// After the re-render, so handleBlur doesn't log a second close for the same Escape.
Expand All @@ -119,10 +184,15 @@ export const NavigationSearch = ({
}
return
}
if (e.key === 'Enter' && pendingRef.current) {
e.preventDefault()
return
}
handleInputKeyDown(e)
}

const handleBlur = (e: React.FocusEvent) => {
if (pendingRef.current) return
// Check if focus is moving to something inside the popover
const relatedTarget = e.relatedTarget as Node | null
if (
Expand Down Expand Up @@ -176,7 +246,7 @@ export const NavigationSearch = ({
onBlur={handleBlur}
onKeyDown={handleKeyDown}
disabled={isSearchCooldownActive}
isLoading={isSearching}
isLoading={isSearching || isNavigating}
keyShortcuts={slashFocusEnabled ? '/ s' : undefined}
shortcutHint={slashFocusEnabled ? '/' : undefined}
ariaLabel={isApi ? 'Explore APIs' : undefined}
Expand All @@ -194,6 +264,7 @@ export const NavigationSearch = ({
<SearchResultsList
results={groups}
isLoading={isSearching}
isNavigating={isNavigating}
isKeyboardNavigating={isKeyboardNavigating}
onMouseMove={handleMouseMove}
onResultClick={handleResultClick}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ATTR_NAVIGATION_SEARCH_RESULT_ANCHOR } from '../../telemetry/semconv'
import { sharedQueryClient } from '../shared/queryClient'
import { NavigationSearchWrapper } from './NavigationSearchComponent'
import { navigationSearchStore } from './navigationSearch.store'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'

vi.mock('../../telemetry/logging', async () =>
Expand Down Expand Up @@ -281,6 +281,137 @@ describe('NavigationSearchWrapper result navigation', () => {
})
})

describe('NavigationSearchWrapper while htmx loads the result', () => {
const operationUrl =
'/docs/api/doc/elasticsearch/operation/operation-search'

beforeEach(() => {
sharedQueryClient.clear()
navigationSearchStore.getState().actions.clearSearchTerm()
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
...emptySearch,
totalResults: 1,
results: [
{
type: 'api',
url: operationUrl,
title: 'Search',
description: 'Search documents',
score: 5,
parents: [],
},
{
type: 'api',
url: `${operationUrl}-other`,
title: 'Delete a document',
description: 'Removes a document',
score: 4,
parents: [],
},
],
}),
})
})

const htmxEvent = (elt: Element, name: string) =>
elt.dispatchEvent(
new CustomEvent(name, { bubbles: true, detail: { elt } })
)

// htmx listens on the boosted link itself, so its request is sent before React's delegated onClick runs.
const openBoostedResult = async () => {
render(<NavigationSearchWrapper type="api" />)
const input = await screen.findByPlaceholderText('Explore APIs')
await userEvent.type(input, 'search')
const row = await screen.findByRole('link', { name: /Search/ })
row.addEventListener('click', (event) => {
event.preventDefault()
htmxEvent(row, 'htmx:beforeSend')
})
const aborted = vi.fn()
row.addEventListener('htmx:abort', aborted)
await waitFor(() => expect(row).toBeVisible())
const endRequest = () =>
act(() => {
htmxEvent(row, 'htmx:afterRequest')
})
return { input, row, aborted, endRequest }
}

const closeReasons = () =>
vi
.mocked(logInfo)
.mock.calls.filter(([name]) => name === 'navigation_search_closed')
.map(([, attrs]) => attrs?.['navigation_search.close_reason'])

it('stays open with a spinner until the request ends, then closes', async () => {
const { input, row, endRequest } = await openBoostedResult()
vi.mocked(logInfo).mockClear()

await userEvent.click(row)

expect(row).toBeVisible()
expect(input).toHaveFocus()
expect(screen.getByRole('progressbar')).toBeInTheDocument()
expect(closeReasons()).toEqual([])

endRequest()

await waitFor(() => expect(row).not.toBeVisible())
expect(input).not.toHaveFocus()
expect(closeReasons()).toEqual(['navigate'])
})

it('stays open until the request ends when Enter opens the result', async () => {
const { row, endRequest } = await openBoostedResult()

await userEvent.keyboard('{Enter}')
expect(row).toBeVisible()

endRequest()
await waitFor(() => expect(row).not.toBeVisible())
})

it('rejects another result while one is loading', async () => {
const { row } = await openBoostedResult()
await userEvent.click(row)
const other = screen.getByRole('link', { name: /Delete a document/ })

const second = new CustomEvent('htmx:beforeRequest', {
bubbles: true,
cancelable: true,
detail: { elt: other },
})
other.dispatchEvent(second)

expect(second.defaultPrevented).toBe(true)
})

it('aborts the request and closes on Escape', async () => {
const { row, aborted } = await openBoostedResult()
await userEvent.click(row)

await userEvent.keyboard('{Escape}')

expect(aborted).toHaveBeenCalledTimes(1)
await waitFor(() => expect(row).not.toBeVisible())
})

it('aborts the request and keeps the results open when typing', async () => {
const { input, row, aborted, endRequest } = await openBoostedResult()
await userEvent.click(row)

await userEvent.type(input, 'x')
endRequest()

expect(aborted).toHaveBeenCalledTimes(1)
expect(input).toHaveFocus()
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()
})
})

describe('NavigationSearchWrapper slash shortcut', () => {
const apiPlaceholder = 'Explore APIs'

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export const emptyStateCopy = (typeFilter: TypeFilter) =>
export interface SearchResultsListProps {
results: ResultGroup[]
isLoading: boolean
isNavigating?: boolean
isKeyboardNavigating: MutableRefObject<boolean>
onMouseMove: () => void
onResultClick: (opensElsewhere: boolean) => void
Expand All @@ -88,6 +89,7 @@ export interface SearchResultsListProps {
export const SearchResultsList = ({
results,
isLoading,
isNavigating = false,
isKeyboardNavigating,
onMouseMove,
onResultClick,
Expand Down Expand Up @@ -196,7 +198,18 @@ export const SearchResultsList = ({
}

return (
<div ref={containerRef} css={containerStyles}>
<div
ref={containerRef}
aria-busy={isNavigating}
css={[
containerStyles,
// A second click would start a request racing the one in flight.
isNavigating &&
css`
pointer-events: none;
`,
Comment thread
infra-vault-gh-plugin-prod[bot] marked this conversation as resolved.
Resolved
]}
>
{results.map(({ result, index, rank, properties }) => (
<div
key={result.url}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ interface Options {
resultsCount: number
isLoading: boolean
onClose: () => void
onNavigate: () => void
typeFilter: TypeFilter
}

Expand All @@ -26,7 +25,6 @@ export const useNavigationSearchKeyboardNavigation = ({
resultsCount,
isLoading,
onClose,
onNavigate,
typeFilter,
}: Options): Result => {
const inputRef = useRef<HTMLInputElement>(null)
Expand All @@ -53,10 +51,8 @@ export const useNavigationSearchKeyboardNavigation = ({
const element = document.querySelector<HTMLAnchorElement>(
`[data-search-result-index="${index}"]`
)
if (element) {
onNavigate()
element.click()
}
// The row's onClick closes the dropdown or waits for the htmx request, as for a mouse click.
element?.click()
}

const handleInputKeyDown = useCallback(
Expand Down Expand Up @@ -114,7 +110,6 @@ export const useNavigationSearchKeyboardNavigation = ({
searchTerm,
setSelectedIndex,
onClose,
onNavigate,
trackNavigation,
]
)
Expand Down
Loading