Skip to content

Commit

Permalink
fix: focus on close modal (#3967)
Browse files Browse the repository at this point in the history
  • Loading branch information
lisalupi authored Jul 5, 2024
1 parent e20f2be commit 3a97e74
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 11 deletions.
5 changes: 5 additions & 0 deletions .changeset/seven-laws-pump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ultraviolet/ui": patch
---

`<Modal />`: when a modal is closed, focus should be on disclosure
11 changes: 2 additions & 9 deletions packages/ui/src/components/Modal/Disclosure.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
import type { PropsWithRef } from 'react'
import {
cloneElement,
createRef,
isValidElement,
useEffect,
useMemo,
} from 'react'
import { cloneElement, isValidElement, useEffect, useMemo } from 'react'
import type { DisclosureProps } from './types'

export const Disclosure = ({
Expand All @@ -15,9 +9,8 @@ export const Disclosure = ({
handleClose,
toggle,
id,
disclosureRef,
}: DisclosureProps) => {
const disclosureRef = createRef<HTMLElement>()

useEffect(() => {
const element = disclosureRef.current
element?.addEventListener('click', handleOpen)
Expand Down
7 changes: 5 additions & 2 deletions packages/ui/src/components/Modal/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import styled from '@emotion/styled'
import type { ReactElement, ReactNode } from 'react'
import type React from 'react'
import { useCallback, useId, useState } from 'react'
import { useCallback, useId, useRef, useState } from 'react'
import { Button } from '../Button'
import { Dialog } from './Dialog'
import { Disclosure } from './Disclosure'
Expand Down Expand Up @@ -77,6 +77,7 @@ export const Modal = ({
// Used for disclosure usage only
const [visible, setVisible] = useState(false)
const controlId = useId()
const disclosureRef = useRef<HTMLElement>(null)

const handleOpen = useCallback(() => {
setVisible(true)
Expand All @@ -92,7 +93,8 @@ export const Modal = ({
}
setVisible(false)
}
}, [onBeforeClose, onClose])
disclosureRef.current?.focus()
}, [disclosureRef, onBeforeClose, onClose])

const handleToggle = useCallback(() => {
setVisible(current => !current)
Expand All @@ -111,6 +113,7 @@ export const Modal = ({
handleClose={handleClose}
visible={visible}
toggle={handleToggle}
disclosureRef={disclosureRef}
/>
) : null}
<Dialog
Expand Down
1 change: 1 addition & 0 deletions packages/ui/src/components/Modal/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export type DisclosureProps = {
visible: ModalState['visible']
toggle: ModalState['toggle']
id: string
disclosureRef: React.RefObject<HTMLElement>
}

export type DialogProps = {
Expand Down

0 comments on commit 3a97e74

Please sign in to comment.