diff --git a/components/modal/src/modal/modal.js b/components/modal/src/modal/modal.js index aa52e9edcc..9da7beec7c 100644 --- a/components/modal/src/modal/modal.js +++ b/components/modal/src/modal/modal.js @@ -4,7 +4,7 @@ import { Layer } from '@dhis2-ui/layer' import { spacers, spacersNum, sharedPropTypes } from '@dhis2/ui-constants' import cx from 'classnames' import PropTypes from 'prop-types' -import React, { useCallback, useEffect } from 'react' +import React, { useEffect } from 'react' import { resolve } from 'styled-jsx/css' import { CloseButton } from './close-button.js' @@ -29,26 +29,25 @@ export const Modal = ({ }) => { const layerStyles = resolveLayerStyles(hide) - const handleKeyDown = useCallback( - (event) => { - if (event.key === 'Escape' && onClose) { - onClose() - } - }, - [onClose] - ) - useEffect(() => { if (hide) { return } - const handleKeyDownCallback = handleKeyDown - document.addEventListener('keydown', handleKeyDownCallback) + + const handleKeyDown = (event) => { + event.preventDefault() + if (event.key === 'Escape' && onClose) { + event.stopPropagation() + onClose() + } + } + + document.addEventListener('keydown', handleKeyDown) return () => { - document.removeEventListener('keydown', handleKeyDownCallback) + document.removeEventListener('keydown', handleKeyDown) } - }, [handleKeyDown, hide]) + }, [hide, onClose]) return ( { - describe('Accessibility', () => { + describe('Modal Accessibility', () => { it('closes when ESC key is pressed', () => { const onCloseMock = jest.fn() render() const modalElement = screen.getByRole('dialog') fireEvent.keyDown(modalElement, { key: 'Escape', code: 'Escape' }) - expect(onCloseMock).toHaveBeenCalled() }) + it('does not close when "Enter" is pressed', () => { + const onCloseMock = jest.fn() + render() + + const modalElement = screen.getByRole('dialog') + fireEvent.keyDown(modalElement, { key: 'Enter', code: 'Enter' }) + expect(onCloseMock).not.toHaveBeenCalled() + }) + + it('does not close when "SpaceBar" is pressed', () => { + const onCloseMock = jest.fn() + render() + + const modalElement = screen.getByRole('dialog') + fireEvent.keyDown(modalElement, { key: ' ', code: ' ' }) + expect(onCloseMock).not.toHaveBeenCalled() + }) + it('has a close button with proper accessibility attributes', async () => { render() const closeButton = await screen.findByLabelText( @@ -25,6 +42,7 @@ describe('Modal', () => { expect(closeButton.tagName).toBe('BUTTON') }) }) + describe('Regular dimensions', () => { it('has the correct dimension styles in its default state', () => { render()