Skip to content

Commit

Permalink
fix(docsearch): support initial query
Browse files Browse the repository at this point in the history
  • Loading branch information
francoischalifour committed Jul 8, 2020
1 parent 7eeb30b commit cf84a25
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 5 deletions.
12 changes: 9 additions & 3 deletions src/DocSearch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -49,6 +54,7 @@ export function DocSearch(props: DocSearchProps) {
createPortal(
<DocSearchModal
{...props}
initialQuery={initialQuery}
initialScrollY={window.scrollY}
onClose={onClose}
/>,
Expand Down
4 changes: 3 additions & 1 deletion src/DocSearchModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { ScreenState } from './ScreenState';
import { Footer } from './Footer';

interface DocSearchModalProps extends DocSearchProps {
initialQuery?: string;
initialScrollY: number;
onClose?(): void;
}
Expand All @@ -42,6 +43,7 @@ export function DocSearchModal({
hitComponent = Hit,
resultsFooterComponent = () => null,
navigator,
initialQuery: queryFromProp = '',
initialScrollY = 0,
}: DocSearchModalProps) {
const [state, setState] = React.useState<
Expand All @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/useDocSearchKeyboardEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
}
}
}
Expand Down

0 comments on commit cf84a25

Please sign in to comment.