From ecc4920a6dc72b5b7a34cd71a08ccdae5d3ca156 Mon Sep 17 00:00:00 2001 From: woothu <32914662+woothu@users.noreply.github.com> Date: Mon, 27 Jul 2020 14:25:47 +0200 Subject: [PATCH] feat: CModal: add autofucus and `esc` key support --- src/modal/CModal.js | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/modal/CModal.js b/src/modal/CModal.js index 7888f56f..40160fb1 100644 --- a/src/modal/CModal.js +++ b/src/modal/CModal.js @@ -33,21 +33,35 @@ const CModal = props => { } = props const [isOpen, setIsOpen] = useState(false) + const [modalTrigger, setModalTrigger] = useState(false) const modalClick = e => e.target.dataset.modal && closeOnBackdrop && close() useEffect(() => { setIsOpen(show) }, [show]) + const onKeypress = e => e.keyCode == '27' && close() + + useEffect(() => { + isOpen && document.addEventListener('keydown', onKeypress) + return () => document.removeEventListener('keydown', onKeypress) + }, [isOpen]) const close = () => { onClose && onClose() setIsOpen(false) } - const onEntered = () => onOpened && onOpened() + const onEntered = () => { + setModalTrigger(document.querySelector(':focus')) + nodeRef.current.focus() + onOpened && onOpened() + } - const onExited = () => onClosed && onClosed() + const onExited = () => { + modalTrigger && modalTrigger.focus() + onClosed && onClosed() + } const modalClasses = classNames( 'modal overflow-auto fade', {