From 80983f524565813edc1a931f7ee330b7ed177db5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Sat, 4 Apr 2020 14:11:01 +0200 Subject: [PATCH] fix(docsearch): don't focus input if initial query --- src/DocSearch.tsx | 10 ++++++---- src/SearchBox.tsx | 13 +++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/DocSearch.tsx b/src/DocSearch.tsx index a9193fd59..432a162fb 100644 --- a/src/DocSearch.tsx +++ b/src/DocSearch.tsx @@ -43,6 +43,9 @@ export function DocSearch({ const dropdownRef = React.useRef(null); const inputRef = React.useRef(null); const snipetLength = React.useRef(10); + const initialQuery = React.useRef( + typeof window !== 'undefined' ? window.getSelection()!.toString() : '' + ).current; const searchClient = React.useMemo(() => createSearchClient(appId, apiKey), [ appId, @@ -90,10 +93,7 @@ export function DocSearch({ placeholder: 'Search docs...', openOnFocus: true, initialState: { - query: - typeof window !== 'undefined' - ? window.getSelection()!.toString() - : '', + query: initialQuery, }, onStateChange({ state }) { setState(state as any); @@ -230,6 +230,7 @@ export function DocSearch({ recentSearches, favoriteSearches, saveRecentSearch, + initialQuery, ] ); @@ -291,6 +292,7 @@ export function DocSearch({ diff --git a/src/SearchBox.tsx b/src/SearchBox.tsx index 2189d9c62..b1419913b 100644 --- a/src/SearchBox.tsx +++ b/src/SearchBox.tsx @@ -17,6 +17,7 @@ interface SearchBoxProps React.KeyboardEvent > { state: AutocompleteState; + initialQuery: string; inputRef: MutableRefObject; onClose(): void; } @@ -25,6 +26,17 @@ export function SearchBox(props: SearchBoxProps) { const { onSubmit, onReset } = props.getFormProps({ inputElement: props.inputRef.current, }); + const { initialQuery, refresh } = props; + + // We don't focus the input when there's an initial query because users + // rather want to see the results directly. 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]); return ( <> @@ -48,6 +60,7 @@ export function SearchBox(props: SearchBoxProps) { className="DocSearch-Input" ref={props.inputRef} {...props.getInputProps({ + autoFocus: props.initialQuery.length === 0, inputElement: props.inputRef.current!, type: 'search', maxLength: '512',