diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx index 0d233b8850..109a71ce9e 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/NavigationSearch.tsx @@ -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 @@ -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(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, @@ -93,7 +157,6 @@ export const NavigationSearch = ({ resultsCount: navigableRowCount(groups), isLoading: isSearching, onClose: () => setOpen(false), - onNavigate: () => handleResultClick(), typeFilter, }) @@ -104,6 +167,7 @@ export const NavigationSearch = ({ const handleChange = (e: React.ChangeEvent) => { const value = e.target.value + cancelNavigation() setSearchTerm(value) setOpen(!!value.trim()) } @@ -111,6 +175,7 @@ export const NavigationSearch = ({ const handleKeyDown = (e: React.KeyboardEvent) => { 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. @@ -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 ( @@ -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} @@ -194,6 +264,7 @@ export const NavigationSearch = ({ @@ -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() + 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' diff --git a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx index 3f4d07287b..27e5906338 100644 --- a/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx +++ b/src/Elastic.Documentation.Site/Assets/web-components/NavigationSearch/SearchResultsList.tsx @@ -79,6 +79,7 @@ export const emptyStateCopy = (typeFilter: TypeFilter) => export interface SearchResultsListProps { results: ResultGroup[] isLoading: boolean + isNavigating?: boolean isKeyboardNavigating: MutableRefObject onMouseMove: () => void onResultClick: (opensElsewhere: boolean) => void @@ -88,6 +89,7 @@ export interface SearchResultsListProps { export const SearchResultsList = ({ results, isLoading, + isNavigating = false, isKeyboardNavigating, onMouseMove, onResultClick, @@ -196,7 +198,18 @@ export const SearchResultsList = ({ } return ( -
+
{results.map(({ result, index, rank, properties }) => (
void - onNavigate: () => void typeFilter: TypeFilter } @@ -26,7 +25,6 @@ export const useNavigationSearchKeyboardNavigation = ({ resultsCount, isLoading, onClose, - onNavigate, typeFilter, }: Options): Result => { const inputRef = useRef(null) @@ -53,10 +51,8 @@ export const useNavigationSearchKeyboardNavigation = ({ const element = document.querySelector( `[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( @@ -114,7 +110,6 @@ export const useNavigationSearchKeyboardNavigation = ({ searchTerm, setSelectedIndex, onClose, - onNavigate, trackNavigation, ] )