Skip to content

Fix showing two modals after pressing ctrl+k or / to open the search modal for the first time #3909

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions src/theme/SearchBar/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { useEffect } from 'react';
import { getGoogleAnalyticsUserIdFromBrowserCookie } from '../../lib/google/google'

let DocSearchModal = null;
let searchContainer = null;

function Hit({ hit, children }) {
const handleClick = () => {
Expand Down Expand Up @@ -69,7 +70,6 @@ function DocSearch({ contextualSearch, externalUrlRegex, ...props }) {
clickAnalytics: true,
};
const history = useHistory();
const searchContainer = useRef(null);
const searchButtonRef = useRef(null);
const [isOpen, setIsOpen] = useState(false);
const [initialQuery, setInitialQuery] = useState(undefined);
Expand Down Expand Up @@ -100,18 +100,26 @@ function DocSearch({ contextualSearch, externalUrlRegex, ...props }) {

const onOpen = useCallback(() => {
importDocSearchModalIfNeeded().then(() => {
searchContainer.current = document.createElement('div');
// searchContainer is not null here when the modal is already open
// this check is needed because ctrl + k shortcut was handled by another instance of SearchBar component
if (searchContainer) {
return;
}

searchContainer = document.createElement('div');
document.body.insertBefore(
searchContainer.current,
searchContainer,
document.body.firstChild,
);

setIsOpen(true);
});
}, [importDocSearchModalIfNeeded, setIsOpen]);

const onClose = useCallback(() => {
setIsOpen(false);
searchContainer.current?.remove();
searchContainer?.remove();
searchContainer = null;;
}, [setIsOpen]);

const onInput = useCallback(
Expand Down Expand Up @@ -204,7 +212,7 @@ function DocSearch({ contextualSearch, externalUrlRegex, ...props }) {

{isOpen &&
DocSearchModal &&
searchContainer.current &&
searchContainer &&
createPortal(
<DocSearchModal
onClose={onClose}
Expand All @@ -223,7 +231,7 @@ function DocSearch({ contextualSearch, externalUrlRegex, ...props }) {
placeholder={translations.placeholder}
translations={translations.modal}
/>,
searchContainer.current,
searchContainer,
)}
</>
);
Expand Down