Skip to content

Commit

Permalink
Add functionality to auto-focus the delete text input on modal visibi…
Browse files Browse the repository at this point in the history
…lity
  • Loading branch information
aniketkatkar97 committed Aug 2, 2024
1 parent b8bbe99 commit 6d7adb3
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,25 @@ describe('Test EntityDelete Modal Component', () => {

expect(await screen.findByText('label.soft-delete')).toBeInTheDocument();
});

it('should focus the input box on open', async () => {
// since the focus is set using setTimeout, we need to use fake timers
jest.useFakeTimers();
await act(async () => {
render(<EntityDeleteModal {...mockProp} visible />, {
wrapper: MemoryRouter,
});
});

await act(async () => {
jest.runAllTimers();
});

const inputBox = await screen.findByTestId('confirmation-text-input');

// Check if element is focused
expect(inputBox).toHaveFocus();

jest.useRealTimers();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,15 @@
* limitations under the License.
*/

import { Button, Input, Modal, Typography } from 'antd';
import { Button, Input, InputRef, Modal, Typography } from 'antd';
import { t } from 'i18next';
import React, { ChangeEvent, useEffect, useMemo, useState } from 'react';
import React, {
ChangeEvent,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { Trans } from 'react-i18next';
import { Transi18next } from '../../../utils/CommonUtils';
import { EntityDeleteModalProp } from './EntityDeleteModal.interface';
Expand All @@ -27,6 +33,7 @@ const EntityDeleteModal = ({
visible,
bodyText,
}: EntityDeleteModalProp) => {
const deleteTextInputRef = useRef<InputRef>(null);
const [name, setName] = useState('');
const [saving, setSaving] = useState(false);

Expand All @@ -45,6 +52,20 @@ const EntityDeleteModal = ({
// To remove the entered text in the modal input after modal closed
useEffect(() => {
setName('');

// Using this method to autoFocus Input element since directly calling focus() doesn't work
// for the inputs inside modal. Ref - https://github.com/ant-design/ant-design/issues/8668
let timeout: number;

if (visible) {
timeout = window.setTimeout(() => {
deleteTextInputRef.current?.focus();
}, 1);
}

return () => {
clearTimeout(timeout);
};
}, [visible]);

return (
Expand Down Expand Up @@ -112,11 +133,13 @@ const EntityDeleteModal = ({
</Trans>
</Typography>
<Input
autoFocus
autoComplete="off"
data-testid="confirmation-text-input"
disabled={saving}
name="entityName"
placeholder={t('label.delete-uppercase')}
ref={deleteTextInputRef}
type="text"
value={name}
onChange={handleOnChange}
Expand Down

0 comments on commit 6d7adb3

Please sign in to comment.