Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pages/tree-view/basic.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down Expand Up @@ -53,6 +54,10 @@ export default function BasicTreeView() {
Show connector lines
</Checkbox>

<Checkbox checked={renderAsList} onChange={({ detail }) => setRenderAsList(detail.checked)}>
Render as list (ariaRole=&quot;list&quot;)
</Checkbox>

<br />

<FormField label="Toggle icon" stretch={true}>
Expand Down Expand Up @@ -115,6 +120,7 @@ export default function BasicTreeView() {
}}
renderItemToggleIcon={renderItemToggleIcon}
connectorLines={showConnectorLines ? 'vertical' : undefined}
ariaRole={renderAsList ? 'list' : 'tree'}
/>
</Container>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
89 changes: 87 additions & 2 deletions src/tree-view/__tests__/a11y.test.tsx
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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(
<TreeView
ariaRole={ariaRole}
items={itemsWithFocusables}
getItemId={item => 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);
});
});
5 changes: 3 additions & 2 deletions src/tree-view/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ import InternalTreeView from './internal';

export { TreeViewProps };

const TreeView = <T,>({ connectorLines = 'none', ...props }: TreeViewProps<T>) => {
const TreeView = <T,>({ connectorLines = 'none', ariaRole = 'tree', ...props }: TreeViewProps<T>) => {
const baseComponentProps = useBaseComponent('TreeView', {
props: { connectorLines },
props: { connectorLines, ariaRole },
});
const baseProps = getBaseProps(props);
const externalProps = getExternalProps(props);
Expand All @@ -26,6 +26,7 @@ const TreeView = <T,>({ connectorLines = 'none', ...props }: TreeViewProps<T>) =
{...externalProps}
{...props}
connectorLines={connectorLines}
ariaRole={ariaRole}
/>
);
};
Expand Down
9 changes: 9 additions & 0 deletions src/tree-view/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ export interface TreeViewProps<T = any> 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.
*/
Expand Down Expand Up @@ -100,6 +107,8 @@ export namespace TreeViewProps {

export type ConnectorLinesVariant = 'vertical' | 'none';

export type AriaRole = 'tree' | 'list';

export interface I18nStrings<T> {
collapseButtonLabel?: (item: T) => string;
expandButtonLabel?: (item: T) => string;
Expand Down
76 changes: 45 additions & 31 deletions src/tree-view/internal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const InternalTreeView = <T,>({
ariaLabelledby,
ariaDescribedby,
connectorLines,
ariaRole,
i18nStrings,
__internalRootRef,
...rest
Expand All @@ -42,6 +43,12 @@ const InternalTreeView = <T,>({
});
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<T>) => {
Expand All @@ -53,39 +60,46 @@ const InternalTreeView = <T,>({
fireNonCancelableEvent(onItemToggle, { id, item, expanded });
};

const list = (
<ul
role={isTree ? 'tree' : 'list'}
ref={treeViewRefObject}
className={clsx(styles.tree, testUtilStyles.tree)}
aria-label={ariaLabel}
aria-labelledby={ariaLabelledby}
aria-describedby={ariaDescribedby}
>
{items.map((item, index) => {
const itemId = getItemId(item, index);
return (
<InternalTreeItem<T>
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}
/>
);
})}
</ul>
);

return (
<div {...baseProps} ref={__internalRootRef} className={clsx(baseProps.className, styles.root, testUtilStyles.root)}>
<KeyboardNavigationProvider getTreeView={() => treeViewRefObject.current}>
<ul
role="tree"
ref={treeViewRefObject}
className={clsx(styles.tree, testUtilStyles.tree)}
aria-label={ariaLabel}
aria-labelledby={ariaLabelledby}
aria-describedby={ariaDescribedby}
>
{items.map((item, index) => {
const itemId = getItemId(item, index);
return (
<InternalTreeItem<T>
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}
/>
);
})}
</ul>
</KeyboardNavigationProvider>
{isTree ? (
<KeyboardNavigationProvider getTreeView={() => treeViewRefObject.current}>{list}</KeyboardNavigationProvider>
) : (
list
)}
</div>
);
};
Expand Down
19 changes: 13 additions & 6 deletions src/tree-view/tree-item/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ interface InternalTreeItemProps<T>
| 'renderItemToggleIcon'
| 'i18nStrings'
| 'connectorLines'
| 'ariaRole'
> {
item: T;
index: number;
Expand All @@ -42,6 +43,7 @@ const InternalTreeItem = <T,>({
i18nStrings,
expandedItems = [],
connectorLines,
ariaRole,
renderItemToggleIcon,
renderItem,
getItemId,
Expand All @@ -58,6 +60,10 @@ const InternalTreeItem = <T,>({
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;

Expand All @@ -74,7 +80,7 @@ const InternalTreeItem = <T,>({

return (
<li
role="treeitem"
role={isTree ? 'treeitem' : 'listitem'}
id={id}
className={clsx(
styles.treeitem,
Expand All @@ -83,8 +89,8 @@ const InternalTreeItem = <T,>({
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]}
>
Expand All @@ -108,9 +114,9 @@ const InternalTreeItem = <T,>({
className={styles['tree-item-focus-target']}
disableFocusHighlight={true}
/>
) : (
) : isTree ? (
<FocusTarget ariaLabel={itemLabelToAnnounce} />
)}
) : null}
</div>
</div>

Expand All @@ -129,7 +135,7 @@ const InternalTreeItem = <T,>({
</div>

{isExpanded && children.length && (
<ul role="group" className={styles['treeitem-group']}>
<ul role={isTree ? 'group' : 'list'} className={styles['treeitem-group']}>
{children.map((child, index) => {
const itemId = getItemId(child, index);
return (
Expand All @@ -147,6 +153,7 @@ const InternalTreeItem = <T,>({
renderItemToggleIcon={renderItemToggleIcon}
allVisibleItemsIndices={allVisibleItemsIndices}
connectorLines={connectorLines}
ariaRole={ariaRole}
/>
);
})}
Expand Down
Loading