|
| 1 | +import { useMemo } from 'react'; |
| 2 | +import { useAriaIdentifiers } from './useAriaIdentifiers'; |
| 3 | + |
| 4 | +export type ResolvedModalAriaProps = { |
| 5 | + 'aria-describedby'?: string; |
| 6 | + 'aria-label'?: string; |
| 7 | + 'aria-labelledby'?: string; |
| 8 | +}; |
| 9 | + |
| 10 | +type UseResolvedModalAriaPropsParams = { |
| 11 | + ariaDescribedby?: string; |
| 12 | + ariaLabel?: string; |
| 13 | + ariaLabelledby?: string; |
| 14 | + dialogId?: string; |
| 15 | +}; |
| 16 | + |
| 17 | +/** |
| 18 | + * Resolves modal labeling/description attributes from explicit props first, |
| 19 | + * then from the modal dialog id convention (`${dialogId}-title|description`). |
| 20 | + * |
| 21 | + * Rules: |
| 22 | + * - `aria-labelledby` wins over `aria-label`. |
| 23 | + * - `aria-describedby` defaults to inferred id when explicit value is absent. |
| 24 | + */ |
| 25 | +export const useResolvedModalAriaProps = ({ |
| 26 | + ariaDescribedby, |
| 27 | + ariaLabel, |
| 28 | + ariaLabelledby, |
| 29 | + dialogId, |
| 30 | +}: UseResolvedModalAriaPropsParams): ResolvedModalAriaProps => { |
| 31 | + const { descriptionId, titleId } = useAriaIdentifiers(dialogId); |
| 32 | + |
| 33 | + return useMemo(() => { |
| 34 | + const resolvedAriaLabelledby = ariaLabel |
| 35 | + ? ariaLabelledby |
| 36 | + : (ariaLabelledby ?? titleId); |
| 37 | + const resolvedAriaDescribedby = ariaDescribedby ?? descriptionId; |
| 38 | + const resolvedAriaLabel = resolvedAriaLabelledby ? undefined : ariaLabel; |
| 39 | + |
| 40 | + return { |
| 41 | + 'aria-describedby': resolvedAriaDescribedby, |
| 42 | + 'aria-label': resolvedAriaLabel, |
| 43 | + 'aria-labelledby': resolvedAriaLabelledby, |
| 44 | + }; |
| 45 | + }, [ariaDescribedby, ariaLabel, ariaLabelledby, descriptionId, titleId]); |
| 46 | +}; |
0 commit comments