Skip to content

Commit b3ee1cc

Browse files
feat: select query when coming from a selection search
1 parent ec278ee commit b3ee1cc

2 files changed

Lines changed: 16 additions & 2 deletions

File tree

packages/docsearch-react/src/DocSearchModal.tsx

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,14 @@ export function DocSearchModal({
5656
const dropdownRef = React.useRef<HTMLDivElement | null>(null);
5757
const inputRef = React.useRef<HTMLInputElement | null>(null);
5858
const snippetLength = React.useRef<number>(10);
59-
const initialQuery = React.useRef(
60-
initialQueryFromProp || typeof window !== 'undefined'
59+
const initialQueryFromSelection = React.useRef(
60+
typeof window !== 'undefined'
6161
? window.getSelection()!.toString().slice(0, MAX_QUERY_SIZE)
6262
: ''
6363
).current;
64+
const initialQuery = React.useRef(
65+
initialQueryFromProp || initialQueryFromSelection
66+
).current;
6467

6568
const searchClient = useSearchClient(appId, apiKey, transformSearchClient);
6669
const favoriteSearches = React.useRef(
@@ -373,6 +376,10 @@ export function DocSearchModal({
373376
autoFocus={initialQuery.length === 0}
374377
onClose={onClose}
375378
inputRef={inputRef}
379+
isFromSelection={
380+
Boolean(initialQuery) &&
381+
initialQuery === initialQueryFromSelection
382+
}
376383
/>
377384
</header>
378385

packages/docsearch-react/src/SearchBox.tsx

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ interface SearchBoxProps
2121
autoFocus: boolean;
2222
inputRef: MutableRefObject<HTMLInputElement | null>;
2323
onClose(): void;
24+
isFromSelection: boolean;
2425
}
2526

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

38+
React.useEffect(() => {
39+
if (props.isFromSelection && props.inputRef.current) {
40+
props.inputRef.current.select();
41+
}
42+
}, [props.isFromSelection, props.inputRef]);
43+
3744
return (
3845
<>
3946
<form

0 commit comments

Comments
 (0)