Skip to content

Commit

Permalink
feat: select query when coming from a selection search
Browse files Browse the repository at this point in the history
  • Loading branch information
francoischalifour committed Oct 2, 2020
1 parent ec278ee commit b3ee1cc
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
11 changes: 9 additions & 2 deletions packages/docsearch-react/src/DocSearchModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,14 @@ export function DocSearchModal({
const dropdownRef = React.useRef<HTMLDivElement | null>(null);
const inputRef = React.useRef<HTMLInputElement | null>(null);
const snippetLength = React.useRef<number>(10);
const initialQuery = React.useRef(
initialQueryFromProp || typeof window !== 'undefined'
const initialQueryFromSelection = React.useRef(
typeof window !== 'undefined'
? window.getSelection()!.toString().slice(0, MAX_QUERY_SIZE)
: ''
).current;
const initialQuery = React.useRef(
initialQueryFromProp || initialQueryFromSelection
).current;

const searchClient = useSearchClient(appId, apiKey, transformSearchClient);
const favoriteSearches = React.useRef(
Expand Down Expand Up @@ -373,6 +376,10 @@ export function DocSearchModal({
autoFocus={initialQuery.length === 0}
onClose={onClose}
inputRef={inputRef}
isFromSelection={
Boolean(initialQuery) &&
initialQuery === initialQueryFromSelection
}
/>
</header>

Expand Down
7 changes: 7 additions & 0 deletions packages/docsearch-react/src/SearchBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ interface SearchBoxProps
autoFocus: boolean;
inputRef: MutableRefObject<HTMLInputElement | null>;
onClose(): void;
isFromSelection: boolean;
}

export function SearchBox(props: SearchBoxProps) {
Expand All @@ -34,6 +35,12 @@ export function SearchBox(props: SearchBoxProps) {
}
}, [props.autoFocus, props.inputRef]);

React.useEffect(() => {
if (props.isFromSelection && props.inputRef.current) {
props.inputRef.current.select();
}
}, [props.isFromSelection, props.inputRef]);

return (
<>
<form
Expand Down

0 comments on commit b3ee1cc

Please sign in to comment.