Skip to content

Commit

Permalink
fix(ModelessDialog): modeless dialog閉じたときのフォーカス処理修正 (#5177)
Browse files Browse the repository at this point in the history
  • Loading branch information
daiHash authored Dec 18, 2024
1 parent 53b01be commit 1590159
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 @@ -127,7 +127,6 @@ export const ModelessDialog: FC<Props & BaseElementProps & VariantProps<typeof m
contentPadding,
footer,
isOpen,
onClickClose,
onPressEscape,
resizable = false,
width,
Expand All @@ -143,6 +142,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 @@ -310,14 +310,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 1590159

Please sign in to comment.