Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ModelessDialog): modeless dialog閉じたときのフォーカス処理修正 #5177

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading