Skip to content

Commit

Permalink
fix(docsearch): don't focus input if initial query
Browse files Browse the repository at this point in the history
  • Loading branch information
francoischalifour committed Apr 4, 2020
1 parent d7d6984 commit 80983f5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/DocSearch.tsx
Expand Up @@ -43,6 +43,9 @@ export function DocSearch({
const dropdownRef = React.useRef<HTMLDivElement | null>(null);
const inputRef = React.useRef<HTMLInputElement | null>(null);
const snipetLength = React.useRef<number>(10);
const initialQuery = React.useRef(
typeof window !== 'undefined' ? window.getSelection()!.toString() : ''
).current;

const searchClient = React.useMemo(() => createSearchClient(appId, apiKey), [
appId,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -230,6 +230,7 @@ export function DocSearch({
recentSearches,
favoriteSearches,
saveRecentSearch,
initialQuery,
]
);

Expand Down Expand Up @@ -291,6 +292,7 @@ export function DocSearch({
<SearchBox
{...autocomplete}
state={state}
initialQuery={initialQuery}
onClose={onClose}
inputRef={inputRef}
/>
Expand Down
13 changes: 13 additions & 0 deletions src/SearchBox.tsx
Expand Up @@ -17,6 +17,7 @@ interface SearchBoxProps
React.KeyboardEvent
> {
state: AutocompleteState<InternalDocSearchHit>;
initialQuery: string;
inputRef: MutableRefObject<HTMLInputElement | null>;
onClose(): void;
}
Expand All @@ -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 (
<>
Expand All @@ -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',
Expand Down

0 comments on commit 80983f5

Please sign in to comment.