Skip to content

Commit

Permalink
Merge pull request #243 from mash-up-kr/refactor/modal-focus-trap
Browse files Browse the repository at this point in the history
Modal오픈시 초기 포커스를 Modal 내부 focusable의 첫번째 요소로 변경
  • Loading branch information
HaJunRyu authored Apr 2, 2023
2 parents 9008b34 + ae47a0b commit e02dee2
Showing 1 changed file with 22 additions and 14 deletions.
36 changes: 22 additions & 14 deletions src/components/common/Modal/Modal.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,27 +59,35 @@ const Modal = ({
'input, button, textarea, select, [href], [tabindex]',
);

if (focusableNodeList) {
const firstFocusableNode = focusableNodeList[0];
const lastFocusableNode = focusableNodeList[focusableNodeList.length - 1];

if (e.target === firstFocusableNode && e.shiftKey && e.key === 'Tab') {
e.preventDefault();
lastFocusableNode.focus();
}
if (e.target === lastFocusableNode && !e.shiftKey && e.key === 'Tab') {
e.preventDefault();
firstFocusableNode.focus();
}
if (!focusableNodeList) return;

const firstFocusableNode = focusableNodeList[0];
const lastFocusableNode = focusableNodeList[focusableNodeList.length - 1];

if (e.target === firstFocusableNode && e.shiftKey && e.key === 'Tab') {
e.preventDefault();
lastFocusableNode.focus();
}
if (e.target === lastFocusableNode && !e.shiftKey && e.key === 'Tab') {
e.preventDefault();
firstFocusableNode.focus();
}
};

if (escClose) window.addEventListener('keyup', handleCloseModalWithEscHandler);

if (mounted) {
dialogRef.current?.focus();
const focusableNodeList = dialogRef.current?.querySelectorAll<HTMLElement>(
'input, button, textarea, select, [href], [tabindex]',
);

if (focusableNodeList) {
const firstFocusableNode = focusableNodeList[0];

firstFocusableNode?.focus();

window.addEventListener('keydown', handleFocusTrap);
window.addEventListener('keydown', handleFocusTrap);
}
}

if (!mounted) setMounted(true);
Expand Down

0 comments on commit e02dee2

Please sign in to comment.