Skip to content

Commit

Permalink
fix: modeless dialog閉じる際のフォーカス処理修正
Browse files Browse the repository at this point in the history
  • Loading branch information
daiHash committed Dec 6, 2024
1 parent 2989699 commit 1e64a72
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion packages/smarthr-ui/src/components/Dialog/ModelessDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,6 @@ export const ModelessDialog: FC<Props & BaseElementProps & VariantProps<typeof m
contentPadding,
footer,
isOpen,
onClickClose,
onPressEscape,
resizable = false,
width,
Expand All @@ -141,6 +140,7 @@ export const ModelessDialog: FC<Props & BaseElementProps & VariantProps<typeof m
...props
}) => {
const labelId = useId()
const lastFocusElementRef = useRef<HTMLElement | null>(null)
const { createPortal } = useDialogPortal(portalParent, id)

const {
Expand Down Expand Up @@ -308,14 +308,39 @@ export const ModelessDialog: FC<Props & BaseElementProps & VariantProps<typeof m
}
}, [isOpen])

const onClickClose = useCallback(
(e: MouseEvent<HTMLButtonElement>) => {
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(
<DialogOverlap isOpen={isOpen} className={overlapStyle}>
<Draggable
Expand Down

0 comments on commit 1e64a72

Please sign in to comment.