From 42ba5dc5e722c2341761bf4c6e1e993aac9f2ca8 Mon Sep 17 00:00:00 2001 From: Stephanie Hong <41085564+JelloBagel@users.noreply.github.com> Date: Tue, 28 May 2024 17:17:30 -0700 Subject: [PATCH] TreeView: Add custom aria label to TreeView.Item (#4617) * Add custom aria label to TreeView.Item * Add changelog * Update hungry-rockets-smell.md --- .changeset/hungry-rockets-smell.md | 5 ++++ packages/react/src/TreeView/TreeView.test.tsx | 24 +++++++++++++++++++ packages/react/src/TreeView/TreeView.tsx | 7 +++++- 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 .changeset/hungry-rockets-smell.md diff --git a/.changeset/hungry-rockets-smell.md b/.changeset/hungry-rockets-smell.md new file mode 100644 index 00000000000..ff29319f0a6 --- /dev/null +++ b/.changeset/hungry-rockets-smell.md @@ -0,0 +1,5 @@ +--- +'@primer/react': minor +--- + +Add an ability to provide custom `aria-label` and `aria-labelledby` to `TreeView.Item` diff --git a/packages/react/src/TreeView/TreeView.test.tsx b/packages/react/src/TreeView/TreeView.test.tsx index ff48cbde3b6..3dc535270fa 100644 --- a/packages/react/src/TreeView/TreeView.test.tsx +++ b/packages/react/src/TreeView/TreeView.test.tsx @@ -47,6 +47,30 @@ describe('Markup', () => { expect(items).toHaveLength(3) }) + it('uses treeitem aria label', () => { + const {queryAllByRole} = renderWithTheme( + <> + + + Item 1 + + + Item 2 + + Item 3 + + Tree item 2 description + , + ) + + const items = queryAllByRole('treeitem') + expect(items).toHaveLength(3) + expect(items[0]).toHaveAccessibleName('Test tree item 1') + expect(items[1]).toHaveAccessibleName('Tree item 2 description') + expect(items[2]).toHaveAttribute('aria-labelledby') + expect(items[2]).toHaveAccessibleName('Item 3') + }) + it('hides subtrees by default', () => { const {queryByRole} = renderWithTheme( diff --git a/packages/react/src/TreeView/TreeView.tsx b/packages/react/src/TreeView/TreeView.tsx index 06aa13321c6..51d970d444a 100644 --- a/packages/react/src/TreeView/TreeView.tsx +++ b/packages/react/src/TreeView/TreeView.tsx @@ -352,6 +352,8 @@ Root.displayName = 'TreeView' // TreeView.Item export type TreeViewItemProps = { + 'aria-label'?: React.AriaAttributes['aria-label'] + 'aria-labelledby'?: React.AriaAttributes['aria-labelledby'] id: string children: React.ReactNode containIntrinsicSize?: string @@ -375,6 +377,8 @@ const Item = React.forwardRef( onSelect, children, className, + 'aria-label': ariaLabel, + 'aria-labelledby': ariaLabelledby, }, ref, ) => { @@ -472,7 +476,8 @@ const Item = React.forwardRef( tabIndex={0} id={itemId} role="treeitem" - aria-labelledby={labelId} + aria-label={ariaLabel} + aria-labelledby={ariaLabel ? undefined : ariaLabelledby || labelId} aria-describedby={`${leadingVisualId} ${trailingVisualId}`} aria-level={level} aria-expanded={isSubTreeEmpty ? undefined : isExpanded}