oops, don't auto-focus feedback button on load

This commit is contained in:
Emi Matchu 2020-10-07 10:17:52 -07:00
parent cd42988a90
commit 3e147ec5b4

View file

@ -252,18 +252,31 @@ function FeedbackFormSection() {
const openButtonRef = React.useRef(null); const openButtonRef = React.useRef(null);
const emailFieldRef = React.useRef(null); const emailFieldRef = React.useRef(null);
const elementAwaitingFocusRef = React.useRef(null);
const openForm = React.useCallback(() => {
setIsOpen(true);
// Wait for the re-render to enable the field, then focus it.
elementAwaitingFocusRef.current = emailFieldRef.current;
}, [setIsOpen]);
const closeForm = React.useCallback(() => {
setIsOpen(false);
// Wait for the re-render to enable the button, then focus it.
elementAwaitingFocusRef.current = openButtonRef.current;
}, [setIsOpen]);
// This lil layout effect will focus whatever element is awaiting focus, then
// clear it out. We use this to set up focus() calls, but wait until the next
// layout finishes to actually call them.
React.useLayoutEffect(() => { React.useLayoutEffect(() => {
if (isOpen) { if (elementAwaitingFocusRef.current) {
if (emailFieldRef.current) { elementAwaitingFocusRef.current.focus();
emailFieldRef.current.focus(); elementAwaitingFocusRef.current = null;
}
} else {
if (openButtonRef.current) {
openButtonRef.current.focus();
}
} }
}, [isOpen]); });
return ( return (
<Flex <Flex
@ -279,7 +292,7 @@ function FeedbackFormSection() {
paddingRight="4" paddingRight="4"
paddingY="2" paddingY="2"
cursor={!isOpen && "pointer"} cursor={!isOpen && "pointer"}
onClick={!isOpen && (() => setIsOpen(true))} onClick={!isOpen ? openForm : null}
> >
<Box <Box
padding="2" padding="2"
@ -318,7 +331,7 @@ function FeedbackFormSection() {
icon={<CloseIcon />} icon={<CloseIcon />}
size="xs" size="xs"
variant="ghost" variant="ghost"
onClick={() => setIsOpen(false)} onClick={closeForm}
isDisabled={!isOpen} isDisabled={!isOpen}
/> />
</Box> </Box>
@ -331,7 +344,7 @@ function FeedbackFormSection() {
> >
<FeedbackFormPitch <FeedbackFormPitch
isDisabled={isOpen} isDisabled={isOpen}
onClick={() => setIsOpen(true)} onClick={openForm}
openButtonRef={openButtonRef} openButtonRef={openButtonRef}
/> />
</Box> </Box>
@ -344,7 +357,7 @@ function FeedbackFormSection() {
> >
<FeedbackForm <FeedbackForm
isDisabled={!isOpen} isDisabled={!isOpen}
onClose={() => setIsOpen(false)} onClose={closeForm}
emailFieldRef={emailFieldRef} emailFieldRef={emailFieldRef}
/> />
</Box> </Box>