Skip to content
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

fix(APIKeyModal): implement focus return to generate button #6440

Merged
merged 3 commits into from
Nov 15, 2024
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import React, { useState } from 'react';
import React, { useRef, useState } from 'react';
import {
Button,
TextInput,
Expand Down Expand Up @@ -85,6 +85,7 @@ const blockClass = `${pkg.prefix}--apikey-modal`;
const InstantTemplate = (args) => {
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
const buttonRef = useRef(undefined);

const generateKey = async () => {
setLoading(true);
Expand All @@ -96,7 +97,12 @@ const InstantTemplate = (args) => {
return (
<>
<style>{`.${blockClass} { opacity: 0; }`};</style>
<APIKeyModal {...args} onClose={() => setOpen(false)} open={open} />
<APIKeyModal
{...args}
onClose={() => setOpen(false)}
open={open}
launcherButtonRef={buttonRef}
/>
{loading ? (
<Button
renderIcon={InlineLoading}
Expand All @@ -105,7 +111,9 @@ const InstantTemplate = (args) => {
Generating...
</Button>
) : (
<Button onClick={generateKey}>Generate</Button>
<Button onClick={generateKey} ref={buttonRef}>
Generate
</Button>
)}
</>
);
Expand All @@ -117,6 +125,7 @@ const TemplateWithState = (args) => {
const [apiKey, setApiKey] = useState('');
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState(false);
const buttonRef = useRef(undefined);

// eslint-disable-next-line
const submitHandler = async (apiKeyName) => {
Expand Down Expand Up @@ -148,8 +157,11 @@ const TemplateWithState = (args) => {
onRequestGenerate={submitHandler}
open={open}
error={fetchError}
launcherButtonRef={buttonRef}
/>
<Button onClick={() => setOpen(!open)}>Generate API key</Button>
<Button onClick={() => setOpen(!open)} ref={buttonRef}>
Generate API key
</Button>
</>
);
};
Expand All @@ -166,6 +178,7 @@ const MultiStepTemplate = (args) => {
const [open, setOpen] = useState(false);
const [apiKey, setApiKey] = useState('');
const [loading, setLoading] = useState(false);
const buttonRef = useRef(undefined);

// multi step options
const [name, setName] = useState(savedName);
Expand Down Expand Up @@ -310,8 +323,9 @@ const MultiStepTemplate = (args) => {
customSteps={steps}
nameRequired={false}
editSuccess={editSuccess}
launcherButtonRef={buttonRef}
/>
<Button onClick={() => setOpen(!open)}>
<Button onClick={() => setOpen(!open)} ref={buttonRef}>
{editing ? 'Edit API key' : 'Generate API key'}
</Button>
</>
Expand All @@ -324,6 +338,7 @@ const EditTemplate = (args) => {
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState(false);
const [fetchSuccess, setFetchSuccess] = useState(false);
const buttonRef = useRef(undefined);

const submitHandler = async () => {
action(`submitted ${apiKeyName}`)();
Expand Down Expand Up @@ -357,8 +372,11 @@ const EditTemplate = (args) => {
open={open}
error={fetchError}
editSuccess={fetchSuccess}
launcherButtonRef={buttonRef}
/>
<Button onClick={onOpenHandler}>Edit API key</Button>
<Button onClick={onOpenHandler} ref={buttonRef}>
Edit API key
</Button>
</>
);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import React from 'react';
import { carbon } from '../../settings';

import { APIKeyModal } from '.';
import { Button } from '@carbon/react';

Object.assign(navigator, {
clipboard: {
Expand Down Expand Up @@ -302,6 +303,52 @@ describe(componentName, () => {
expect(step1InputB).toHaveFocus();
});

it('should return focus to the generate button', async () => {
const onOpen = jest.fn(() => false);
const onClose = jest.fn(() => true);

// eslint-disable-next-line react/prop-types
const DummyComponent = ({ open }) => {
const buttonRef = React.useRef(undefined);

return (
<>
<APIKeyModal
{...defaultProps}
launcherButtonRef={buttonRef}
onClose={onClose}
open={open}
/>
<Button ref={buttonRef} onClick={onOpen}>
Generate
</Button>
</>
);
};

const { getByText, rerender } = render(<DummyComponent open={false} />);

const launchButtonEl = getByText('Generate');
expect(launchButtonEl).toBeInTheDocument();

await act(() => userEvent.click(launchButtonEl));
expect(onOpen).toHaveBeenCalled();

rerender(<DummyComponent open={true} />);

const closeButton = getByText(defaultProps.closeButtonText);
await act(() => new Promise((resolve) => setTimeout(resolve, 0)));
expect(closeButton).toBeInTheDocument();

await act(() => userEvent.click(closeButton));
expect(onClose).toHaveBeenCalled();

rerender(<DummyComponent open={false} />);

await act(() => new Promise((resolve) => setTimeout(resolve, 0)));
expect(launchButtonEl).toHaveFocus();
});

it('successfully edits', async () => {
const { change } = fireEvent;
const { click } = userEvent;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import { getDevtoolsProps } from '../../global/js/utils/devtools';
import { isRequiredIf } from '../../global/js/utils/props-helper';
import uuidv4 from '../../global/js/utils/uuidv4';
import { APIKeyModalProps } from './APIKeyModal.types';
import { useFocus } from '../../global/js/hooks';
import { useFocus, usePreviousValue } from '../../global/js/hooks';
import { getSpecificElement } from '../../global/js/hooks/useFocus';

const componentName = 'APIKeyModal';
Expand Down Expand Up @@ -78,6 +78,7 @@ export let APIKeyModal: React.FC<APIKeyModalProps> = forwardRef(
hasAPIKeyVisibilityToggle,
hasDownloadLink,
hideAPIKeyLabel,
launcherButtonRef,
loading,
loadingText,
modalLabel,
Expand Down Expand Up @@ -125,6 +126,7 @@ export let APIKeyModal: React.FC<APIKeyModalProps> = forwardRef(
modalRef,
selectorPrimaryFocus
);
const prevOpen = usePreviousValue(open);

useEffect(() => {
if (copyRef.current && open && apiKeyLoaded) {
Expand Down Expand Up @@ -159,6 +161,14 @@ export let APIKeyModal: React.FC<APIKeyModalProps> = forwardRef(
}
}, [firstElement, modalRef, open, selectorPrimaryFocus]);

useEffect(() => {
if (prevOpen && !open && launcherButtonRef) {
setTimeout(() => {
launcherButtonRef.current.focus();
}, 0);
}
}, [launcherButtonRef, open, prevOpen]);

const isPrimaryButtonDisabled = () => {
if (loading) {
return true;
Expand Down Expand Up @@ -517,6 +527,11 @@ APIKeyModal.propTypes = {
* label text that's displayed when hovering over visibility toggler to hide key
*/
hideAPIKeyLabel: PropTypes.string,
/**
* Provide a ref to return focus to once the tearsheet is closed.
*/
/**@ts-ignore */
launcherButtonRef: PropTypes.any,
/**
* designates if the modal is in a loading state via a request or some other in progress operation
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import { ReactNode } from 'react';
import { ReactNode, RefObject } from 'react';

interface APIKeyModalCommonProps {
/**
Expand Down Expand Up @@ -94,6 +94,10 @@ interface APIKeyModalCommonProps {
* label text that's displayed when hovering over visibility toggler to hide key
*/
hideAPIKeyLabel?: string;
/**
* Provide a ref to return focus to once the tearsheet is closed.
*/
launcherButtonRef?: RefObject<any>;
/**
* designates if the modal is in a loading state via a request or some other in progress operation
*/
Expand Down
Loading