Skip to content

Commit

Permalink
feat(useRole): add label role (#2621)
Browse files Browse the repository at this point in the history
  • Loading branch information
atomiks committed Nov 7, 2023
1 parent c1965f6 commit 628fd11
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/warm-hornets-doubt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@floating-ui/react': patch
---

feat(useRole): add label role
16 changes: 10 additions & 6 deletions packages/react/src/hooks/useRole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export interface UseRoleProps {
enabled?: boolean;
role?:
| 'tooltip'
| 'label'
| 'dialog'
| 'alertdialog'
| 'menu'
Expand All @@ -30,16 +31,19 @@ export function useRole<RT extends ReferenceType = ReferenceType>(
const referenceId = useId();

return React.useMemo(() => {
const floatingProps = {id: floatingId, role};
if (!enabled) return {};

if (!enabled) {
return {};
}
const floatingProps = {
id: floatingId,
...(role !== 'label' && {role}),
};

if (role === 'tooltip') {
if (role === 'tooltip' || role === 'label') {
return {
reference: {
'aria-describedby': open ? floatingId : undefined,
[`aria-${role === 'label' ? 'labelledby' : 'describedby'}`]: open
? floatingId
: undefined,
},
floating: floatingProps,
};
Expand Down
9 changes: 9 additions & 0 deletions packages/react/test/unit/useRole.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,15 @@ describe('tooltip', () => {
});
});

describe('label', () => {
test('sets correct aria attributes based on the open state', () => {
const {container} = render(<App role="label" initiallyOpen />);
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
expect(container.querySelector('[aria-labelledby]')).toBeInTheDocument();
cleanup();
});
});

describe('dialog', () => {
test('sets correct aria attributes based on the open state', () => {
render(<App role="dialog" />);
Expand Down

0 comments on commit 628fd11

Please sign in to comment.