diff --git a/src/DocSearch.tsx b/src/DocSearch.tsx index 432a162fb..57a4547d4 100644 --- a/src/DocSearch.tsx +++ b/src/DocSearch.tsx @@ -5,18 +5,18 @@ import { } from '@francoischalifour/autocomplete-core'; import { getAlgoliaHits } from '@francoischalifour/autocomplete-preset-algolia'; +import { MAX_QUERY_SIZE } from './constants'; import { DocSearchHit, InternalDocSearchHit, StoredDocSearchHit, } from './types'; import { createSearchClient, groupBy, noop } from './utils'; +import { createStoredSearches } from './stored-searches'; import { SearchBox } from './SearchBox'; import { ScreenState } from './ScreenState'; import { Footer } from './Footer'; -import { createStoredSearches } from './stored-searches'; - interface DocSearchProps { appId?: string; apiKey: string; @@ -44,7 +44,12 @@ export function DocSearch({ const inputRef = React.useRef(null); const snipetLength = React.useRef(10); const initialQuery = React.useRef( - typeof window !== 'undefined' ? window.getSelection()!.toString() : '' + typeof window !== 'undefined' + ? window + .getSelection()! + .toString() + .slice(0, MAX_QUERY_SIZE) + : '' ).current; const searchClient = React.useMemo(() => createSearchClient(appId, apiKey), [ @@ -234,7 +239,7 @@ export function DocSearch({ ] ); - const { getEnvironmentProps, getRootProps } = autocomplete; + const { getEnvironmentProps, getRootProps, refresh } = autocomplete; React.useEffect(() => { const isMobileMediaQuery = window.matchMedia('(max-width: 750px)'); @@ -250,6 +255,17 @@ export function DocSearch({ } }, [state.query]); + // We don't focus the input when there's an initial query (i.e. Selection + // Search) because users rather want to see the results directly, without the + // keyboard appearing. + // We therefore need to refresh the autocomplete instance to load all the + // results, which is usually triggered on focus. + React.useEffect(() => { + if (initialQuery.length > 0) { + refresh(); + } + }, [initialQuery, refresh]); + React.useEffect(() => { if (!(searchBoxRef.current && dropdownRef.current && inputRef.current)) { return undefined; @@ -292,7 +308,7 @@ export function DocSearch({ diff --git a/src/EmptyScreen.tsx b/src/EmptyScreen.tsx index 9175b703e..963030641 100644 --- a/src/EmptyScreen.tsx +++ b/src/EmptyScreen.tsx @@ -95,7 +95,7 @@ export function EmptyScreen(props: EmptyScreenProps) {