diff --git a/pages/tree-view/basic.page.tsx b/pages/tree-view/basic.page.tsx
index 4c77691d5da..57287352eb2 100644
--- a/pages/tree-view/basic.page.tsx
+++ b/pages/tree-view/basic.page.tsx
@@ -26,6 +26,7 @@ export default function BasicTreeView() {
value: 'default',
});
const [showConnectorLines, setShowConnectorLines] = useState(true);
+ const [renderAsList, setRenderAsList] = useState(false);
const renderItemToggleIcon = ({ expanded }: TreeViewProps.ItemToggleRenderIconData) => {
if (toggleIconType.value === 'custom') {
@@ -53,6 +54,10 @@ export default function BasicTreeView() {
Show connector lines
+ setRenderAsList(detail.checked)}>
+ Render as list (ariaRole="list")
+
+
@@ -115,6 +120,7 @@ export default function BasicTreeView() {
}}
renderItemToggleIcon={renderItemToggleIcon}
connectorLines={showConnectorLines ? 'vertical' : undefined}
+ ariaRole={renderAsList ? 'list' : 'tree'}
/>
diff --git a/src/__tests__/snapshot-tests/__snapshots__/documenter.test.ts.snap b/src/__tests__/snapshot-tests/__snapshots__/documenter.test.ts.snap
index a4006166822..09e02718326 100644
--- a/src/__tests__/snapshot-tests/__snapshots__/documenter.test.ts.snap
+++ b/src/__tests__/snapshot-tests/__snapshots__/documenter.test.ts.snap
@@ -35464,6 +35464,23 @@ Don't use \`ariaLabel\` and \`ariaLabelledby\` at the same time.",
"optional": true,
"type": "string",
},
+ {
+ "defaultValue": "'tree'",
+ "description": "Specifies the semantics of the tree view:
+* \`tree\` (default) - Renders a tree widget. Items have the \`treeitem\` role, the tree view is a single tab stop, and users move between items with the arrow keys.
+* \`list\` - Renders nested lists (\`ul\` and \`li\` elements with the \`list\` and \`listitem\` roles). Expand toggles and item actions are in the normal tab order, and arrow-key navigation is turned off.",
+ "inlineType": {
+ "name": "TreeViewProps.AriaRole",
+ "type": "union",
+ "values": [
+ "list",
+ "tree",
+ ],
+ },
+ "name": "ariaRole",
+ "optional": true,
+ "type": "string",
+ },
{
"deprecatedTag": "Custom CSS is not supported. For testing and other use cases, use [data attributes](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes).",
"description": "Adds the specified classes to the root element of the component.",
diff --git a/src/tree-view/__tests__/a11y.test.tsx b/src/tree-view/__tests__/a11y.test.tsx
index e7dd917fad2..29e4649fa79 100644
--- a/src/tree-view/__tests__/a11y.test.tsx
+++ b/src/tree-view/__tests__/a11y.test.tsx
@@ -1,12 +1,13 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import React from 'react';
-import { render } from '@testing-library/react';
+import { fireEvent, render, screen, within } from '@testing-library/react';
import TestI18nProvider from '../../../lib/components/i18n/testing';
import createWrapper from '../../../lib/components/test-utils/dom';
import TreeView, { TreeViewProps } from '../../../lib/components/tree-view';
-import { defaultProps, Item } from './items';
+import { KeyCode } from '../../internal/keycode';
+import { defaultProps, Item, itemsWithFocusables } from './items';
import styles from '../../../lib/components/tree-view/styles.css.js';
@@ -114,3 +115,87 @@ test('correct aria-level is set', () => {
expect(level2Item.getElement().getAttribute('aria-level')).toEqual('2');
expect(level3Item.getElement().getAttribute('aria-level')).toEqual('3');
});
+
+describe('ariaRole', () => {
+ test('uses tree semantics by default', () => {
+ renderTreeView({ ariaLabel: 'Files', expandedItems: ['1'] });
+
+ const tree = screen.getByRole('tree', { name: 'Files' });
+ expect(within(tree).getAllByRole('treeitem').length).toBeGreaterThan(0);
+ expect(within(tree).getByRole('group', { name: 'Item 1.1' })).toBeTruthy();
+ expect(screen.queryByRole('list')).toBeNull();
+ });
+
+ test('renders nested lists with explicit list roles when set to "list"', () => {
+ const { wrapper } = renderTreeView({ ariaRole: 'list', ariaLabel: 'Files', expandedItems: ['1'] });
+
+ expect(screen.queryByRole('tree')).toBeNull();
+ expect(screen.queryByRole('treeitem')).toBeNull();
+ expect(screen.queryByRole('group')).toBeNull();
+
+ const list = screen.getByRole('list', { name: 'Files' });
+ const nestedList = within(list).getAllByRole('list')[0];
+ expect(within(nestedList).getAllByRole('listitem').length).toBe(2);
+ // Explicit roles are required: Safari drops list semantics from lists styled with `list-style: none`.
+ expect(list).toHaveAttribute('role', 'list');
+ expect(nestedList).toHaveAttribute('role', 'list');
+
+ for (const item of wrapper.findItems()) {
+ expect(item.getElement().tagName).toBe('LI');
+ expect(item.getElement()).toHaveAttribute('role', 'listitem');
+ expect(item.getElement()).not.toHaveAttribute('aria-expanded');
+ expect(item.getElement()).not.toHaveAttribute('aria-level');
+ }
+ });
+
+ test('keeps the expanded state on the toggle button when set to "list"', () => {
+ const { wrapper } = renderTreeView({ ariaRole: 'list' });
+
+ const toggle = wrapper.findItemById('1')!.findItemToggle()!.getElement();
+ expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ toggle.click();
+ expect(wrapper.findItemById('1')!.findItemToggle()!.getElement()).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ test('puts all toggles and actions in the tab order when set to "list"', () => {
+ const renderWithFocusables = (ariaRole: TreeViewProps.AriaRole) =>
+ render(
+ item.id}
+ getItemChildren={item => item.children}
+ renderItem={item => ({ content: item.content, actions: item.actions })}
+ />
+ );
+
+ // In tree mode only one element is in the tab order (roving tabindex).
+ const { unmount } = renderWithFocusables('tree');
+ expect(
+ screen
+ .getAllByRole('button')
+ .filter(button => !button.closest('[role="toolbar"]'))
+ .some(button => button.getAttribute('tabindex') === '-1')
+ ).toBe(true);
+ unmount();
+
+ renderWithFocusables('list');
+ // Button group is a toolbar that manages its own roving tabindex, so its buttons are excluded.
+ const buttons = screen.getAllByRole('button').filter(button => !button.closest('[role="toolbar"]'));
+ expect(buttons.length).toBeGreaterThan(1);
+ for (const button of buttons) {
+ expect(button).not.toHaveAttribute('tabindex', '-1');
+ }
+ });
+
+ test('does not move focus with arrow keys when set to "list"', () => {
+ const { wrapper } = renderTreeView({ ariaRole: 'list' });
+
+ const toggle = wrapper.findItemById('1')!.findItemToggle()!.getElement();
+ toggle.focus();
+ fireEvent.keyDown(toggle, { keyCode: KeyCode.down });
+ fireEvent.keyDown(toggle, { keyCode: KeyCode.right });
+
+ expect(document.activeElement).toBe(toggle);
+ });
+});
diff --git a/src/tree-view/index.tsx b/src/tree-view/index.tsx
index e93d258ce4a..09b3627f52e 100644
--- a/src/tree-view/index.tsx
+++ b/src/tree-view/index.tsx
@@ -12,9 +12,9 @@ import InternalTreeView from './internal';
export { TreeViewProps };
-const TreeView = ({ connectorLines = 'none', ...props }: TreeViewProps) => {
+const TreeView = ({ connectorLines = 'none', ariaRole = 'tree', ...props }: TreeViewProps) => {
const baseComponentProps = useBaseComponent('TreeView', {
- props: { connectorLines },
+ props: { connectorLines, ariaRole },
});
const baseProps = getBaseProps(props);
const externalProps = getExternalProps(props);
@@ -26,6 +26,7 @@ const TreeView = ({ connectorLines = 'none', ...props }: TreeViewProps) =
{...externalProps}
{...props}
connectorLines={connectorLines}
+ ariaRole={ariaRole}
/>
);
};
diff --git a/src/tree-view/interfaces.ts b/src/tree-view/interfaces.ts
index 91d467bf6f3..19736f65957 100644
--- a/src/tree-view/interfaces.ts
+++ b/src/tree-view/interfaces.ts
@@ -54,6 +54,13 @@ export interface TreeViewProps extends BaseComponentProps {
*/
ariaDescribedby?: string;
+ /**
+ * Specifies the semantics of the tree view:
+ * * `tree` (default) - Renders a tree widget. Items have the `treeitem` role, the tree view is a single tab stop, and users move between items with the arrow keys. Use only when treeitems are all interactive.
+ * * `list` - Renders nested lists (`ul` and `li` elements with the `list` and `listitem` roles). Expand toggles and item actions are in the normal tab order, and arrow-key navigation is turned off.
+ */
+ ariaRole?: TreeViewProps.AriaRole;
+
/**
* Shows connector lines highlighting hierarchy between parent and child items.
*/
@@ -100,6 +107,8 @@ export namespace TreeViewProps {
export type ConnectorLinesVariant = 'vertical' | 'none';
+ export type AriaRole = 'tree' | 'list';
+
export interface I18nStrings {
collapseButtonLabel?: (item: T) => string;
expandButtonLabel?: (item: T) => string;
diff --git a/src/tree-view/internal.tsx b/src/tree-view/internal.tsx
index 04b272669f9..83111e95169 100644
--- a/src/tree-view/internal.tsx
+++ b/src/tree-view/internal.tsx
@@ -29,6 +29,7 @@ const InternalTreeView = ({
ariaLabelledby,
ariaDescribedby,
connectorLines,
+ ariaRole,
i18nStrings,
__internalRootRef,
...rest
@@ -42,6 +43,12 @@ const InternalTreeView = ({
});
const treeViewRefObject = useRef(null);
+ // When `ariaRole` is "list", the tree view renders nested lists instead of a tree widget.
+ // The `list` and `listitem` roles are set explicitly, even though `ul` and `li` already imply them,
+ // because Safari (WebKit/VoiceOver) removes list semantics from lists styled with `list-style: none`,
+ // which the tree view uses. Without the explicit roles, VoiceOver would not announce the lists or their items.
+ const isTree = ariaRole !== 'list';
+
const allVisibleItemsIndices = getAllVisibleItemsIndices({ items, expandedItems, getItemId, getItemChildren });
const onToggle = ({ id, item, expanded }: TreeViewProps.ItemToggleDetail) => {
@@ -53,39 +60,46 @@ const InternalTreeView = ({
fireNonCancelableEvent(onItemToggle, { id, item, expanded });
};
+ const list = (
+
+ {items.map((item, index) => {
+ const itemId = getItemId(item, index);
+ return (
+
+ key={itemId}
+ item={item}
+ level={1}
+ index={index}
+ expandedItems={expandedItems}
+ i18nStrings={i18nStrings}
+ onItemToggle={onToggle}
+ renderItem={renderItem}
+ getItemId={getItemId}
+ getItemChildren={getItemChildren}
+ renderItemToggleIcon={renderItemToggleIcon}
+ allVisibleItemsIndices={allVisibleItemsIndices}
+ connectorLines={connectorLines}
+ ariaRole={ariaRole}
+ />
+ );
+ })}
+
+ );
+
return (
-
treeViewRefObject.current}>
-
- {items.map((item, index) => {
- const itemId = getItemId(item, index);
- return (
-
- key={itemId}
- item={item}
- level={1}
- index={index}
- expandedItems={expandedItems}
- i18nStrings={i18nStrings}
- onItemToggle={onToggle}
- renderItem={renderItem}
- getItemId={getItemId}
- getItemChildren={getItemChildren}
- renderItemToggleIcon={renderItemToggleIcon}
- allVisibleItemsIndices={allVisibleItemsIndices}
- connectorLines={connectorLines}
- />
- );
- })}
-
-
+ {isTree ? (
+
treeViewRefObject.current}>{list}
+ ) : (
+ list
+ )}
);
};
diff --git a/src/tree-view/tree-item/index.tsx b/src/tree-view/tree-item/index.tsx
index ba1060eabda..a6eb102ce1d 100644
--- a/src/tree-view/tree-item/index.tsx
+++ b/src/tree-view/tree-item/index.tsx
@@ -25,6 +25,7 @@ interface InternalTreeItemProps
| 'renderItemToggleIcon'
| 'i18nStrings'
| 'connectorLines'
+ | 'ariaRole'
> {
item: T;
index: number;
@@ -42,6 +43,7 @@ const InternalTreeItem = ({
i18nStrings,
expandedItems = [],
connectorLines,
+ ariaRole,
renderItemToggleIcon,
renderItem,
getItemId,
@@ -58,6 +60,10 @@ const InternalTreeItem = ({
const isExpandable = children.length > 0;
const isExpanded = isExpandable && expandedItems.includes(id);
const nextLevel = level + 1;
+ // In list mode the nested lists convey the hierarchy, so tree roles and states (`aria-expanded`, `aria-level`) are omitted.
+ // The `listitem` role on `li` and the `list` role on nested `ul` are set explicitly, even though the elements already
+ // imply them, because Safari (WebKit/VoiceOver) removes list semantics from lists styled with `list-style: none`.
+ const isTree = ariaRole !== 'list';
const showVerticalConnectorLines = connectorLines === 'vertical' && isExpanded;
@@ -74,7 +80,7 @@ const InternalTreeItem = ({
return (
({
isExpandable && [testUtilStyles.expandable],
isExpanded && [testUtilStyles.expanded]
)}
- aria-expanded={isExpandable ? isExpanded : undefined}
- aria-level={level}
+ aria-expanded={isTree && isExpandable ? isExpanded : undefined}
+ aria-level={isTree ? level : undefined}
data-testid={`awsui-treeitem-${id}`}
data-awsui-tree-item-index={allVisibleItemsIndices[id]}
>
@@ -108,9 +114,9 @@ const InternalTreeItem = ({
className={styles['tree-item-focus-target']}
disableFocusHighlight={true}
/>
- ) : (
+ ) : isTree ? (
- )}
+ ) : null}
@@ -129,7 +135,7 @@ const InternalTreeItem = ({
{isExpanded && children.length && (
-
+
{children.map((child, index) => {
const itemId = getItemId(child, index);
return (
@@ -147,6 +153,7 @@ const InternalTreeItem = ({
renderItemToggleIcon={renderItemToggleIcon}
allVisibleItemsIndices={allVisibleItemsIndices}
connectorLines={connectorLines}
+ ariaRole={ariaRole}
/>
);
})}