Skip to content

Commit

Permalink
feat: CModal: add autofucus and esc key support
Browse files Browse the repository at this point in the history
  • Loading branch information
woothu committed Jul 27, 2020
1 parent a745c28 commit ecc4920
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/modal/CModal.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', {
Expand Down

2 comments on commit ecc4920

@Nelias
Copy link

@Nelias Nelias commented on ecc4920 Oct 1, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now this escape press can not be stopped by a prompt or any other action can not be taken to prevent it, I think also forms inside a modal that use ESC to clear them out might fire the modal close in this manner. onClosed function also does not trigger anything. Then close() is defined after it is being used with that const onKeypress, which makes it less clear where it comes from. Think about some prop to customize this ESC behaviour.

@Nelias
Copy link

@Nelias Nelias commented on ecc4920 Oct 1, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my case where the visibility state was controlled by the store it just unmounted the component and broke some new features.

Please sign in to comment.