Close FilePreview with Escape key.

Tests.
This commit is contained in:
adcoelho 2023-04-24 10:32:09 +02:00
parent 03464e79c2
commit b87ee2d518
2 changed files with 36 additions and 2 deletions

View file

@ -7,6 +7,7 @@
import React from 'react';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { AppMockRenderer } from '../../common/mock';
@ -35,4 +36,23 @@ describe('FilePreview', () => {
expect(await screen.findByTestId('cases-files-image-preview')).toBeInTheDocument();
});
it('pressing escape calls closePreview', async () => {
const closePreview = jest.fn();
appMockRender.render(<FilePreview closePreview={closePreview} selectedFile={basicFileMock} />);
await waitFor(() =>
expect(appMockRender.getFilesClient().getDownloadHref).toHaveBeenCalledWith({
id: basicFileMock.id,
fileKind: constructFileKindIdByOwner(mockedTestProvidersOwner[0]),
})
);
expect(await screen.findByTestId('cases-files-image-preview')).toBeInTheDocument();
userEvent.keyboard('{esc}');
await waitFor(() => expect(closePreview).toHaveBeenCalled());
});
});

View file

@ -4,12 +4,12 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import React from 'react';
import React, { useEffect } from 'react';
import styled from 'styled-components';
import type { FileJSON } from '@kbn/shared-ux-file-types';
import { EuiOverlayMask, EuiFocusTrap, EuiImage } from '@elastic/eui';
import { EuiOverlayMask, EuiFocusTrap, EuiImage, keys } from '@elastic/eui';
import { useFilesContext } from '@kbn/shared-ux-file-context';
import type { Owner } from '../../../common/constants/types';
@ -36,6 +36,20 @@ export const FilePreview = ({ closePreview, selectedFile }: FilePreviewProps) =>
const { client: filesClient } = useFilesContext();
const { owner } = useCasesContext();
useEffect(() => {
const keyboardListener = (event: KeyboardEvent) => {
if (event.key === keys.ESCAPE || event.code === 'Escape') {
closePreview();
}
};
window.addEventListener('keyup', keyboardListener);
return () => {
window.removeEventListener('keyup', keyboardListener);
};
}, [closePreview]);
return (
<StyledOverlayMask>
<EuiFocusTrap onClickOutside={closePreview}>