diff --git a/packages/smarthr-ui/src/components/Dialog/ModelessDialog.tsx b/packages/smarthr-ui/src/components/Dialog/ModelessDialog.tsx index 6f52116d62..9b1fb23f98 100644 --- a/packages/smarthr-ui/src/components/Dialog/ModelessDialog.tsx +++ b/packages/smarthr-ui/src/components/Dialog/ModelessDialog.tsx @@ -125,7 +125,6 @@ export const ModelessDialog: FC { const labelId = useId() + const lastFocusElementRef = useRef(null) const { createPortal } = useDialogPortal(portalParent, id) const { @@ -308,14 +308,39 @@ export const ModelessDialog: FC) => { + lastFocusElementRef.current?.focus() + props.onClickClose?.(e) + }, + [props], + ) + useHandleEscape( useCallback(() => { if (isOpen && onPressEscape) { + lastFocusElementRef.current?.focus() onPressEscape() } }, [isOpen, onPressEscape]), ) + useEffect(() => { + const focusHandler = (e: FocusEvent) => { + if (!(e.target instanceof HTMLElement)) return + + // e.target(現在フォーカスがあたっている要素)がModeless dialogの中の要素であれば、lastFocusElementRefに代入しない + if (wrapperRef?.current?.contains(e.target)) { + return + } + + lastFocusElementRef.current = e.target + } + + document.addEventListener('focus', focusHandler, true) + return () => document.removeEventListener('focus', focusHandler, true) + }, []) + return createPortal(