fix(docsearch): support initial query
This commit is contained in:
parent
7eeb30bf22
commit
cf84a256a4
3 changed files with 13 additions and 5 deletions
|
|
@ -30,10 +30,15 @@ export interface DocSearchProps
|
|||
export function DocSearch(props: DocSearchProps) {
|
||||
const [isOpen, setIsOpen] = React.useState(false);
|
||||
const searchButtonRef = React.useRef<HTMLButtonElement>(null);
|
||||
const [initialQuery, setInitialQuery] = React.useState('');
|
||||
|
||||
const onOpen = React.useCallback(() => {
|
||||
setIsOpen(true);
|
||||
}, [setIsOpen]);
|
||||
const onOpen = React.useCallback(
|
||||
({ query = '' } = {}) => {
|
||||
setIsOpen(true);
|
||||
setInitialQuery(query);
|
||||
},
|
||||
[setIsOpen]
|
||||
);
|
||||
|
||||
const onClose = React.useCallback(() => {
|
||||
setIsOpen(false);
|
||||
|
|
@ -49,6 +54,7 @@ export function DocSearch(props: DocSearchProps) {
|
|||
createPortal(
|
||||
<DocSearchModal
|
||||
{...props}
|
||||
initialQuery={initialQuery}
|
||||
initialScrollY={window.scrollY}
|
||||
onClose={onClose}
|
||||
/>,
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ import { ScreenState } from './ScreenState';
|
|||
import { Footer } from './Footer';
|
||||
|
||||
interface DocSearchModalProps extends DocSearchProps {
|
||||
initialQuery?: string;
|
||||
initialScrollY: number;
|
||||
onClose?(): void;
|
||||
}
|
||||
|
|
@ -42,6 +43,7 @@ export function DocSearchModal({
|
|||
hitComponent = Hit,
|
||||
resultsFooterComponent = () => null,
|
||||
navigator,
|
||||
initialQuery: queryFromProp = '',
|
||||
initialScrollY = 0,
|
||||
}: DocSearchModalProps) {
|
||||
const [state, setState] = React.useState<
|
||||
|
|
@ -57,7 +59,7 @@ export function DocSearchModal({
|
|||
const inputRef = React.useRef<HTMLInputElement | null>(null);
|
||||
const snipetLength = React.useRef<number>(10);
|
||||
const initialQuery = React.useRef(
|
||||
typeof window !== 'undefined'
|
||||
queryFromProp || typeof window !== 'undefined'
|
||||
? window.getSelection()!.toString().slice(0, MAX_QUERY_SIZE)
|
||||
: ''
|
||||
).current;
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ export function useDocSearchKeyboardEvents({
|
|||
searchButtonRef.current === document.activeElement
|
||||
) {
|
||||
if (/[a-zA-Z0-9]/.test(String.fromCharCode(event.keyCode))) {
|
||||
onOpen();
|
||||
onOpen({ query: event.keyCode });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue