Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(Item, TreeList): a disabled row's link has no destination (spec:AST-085 FR2) (#9056)

Cindy Zhangd7cd32c09c67
diff --git a/.changeset/disabled-row-link-no-destination.md b/.changeset/disabled-row-link-no-destination.md
new file mode 100644
index 0000000000..f6a3389f38
--- /dev/null
+++ b/.changeset/disabled-row-link-no-destination.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A disabled `Item`, `ListItem` or `TreeList` row with an `href` no longer navigates from a screen reader, Enter, or a link menu. Its link now has no `href`, `target` or `rel`, as a disabled `Link` does, and it keeps the link role.
+
+@cixzhang @duytbp
diff --git a/packages/core/src/Item/Item.test.tsx b/packages/core/src/Item/Item.test.tsx
index acbe62f3a8..235ffd94fc 100644
--- a/packages/core/src/Item/Item.test.tsx
+++ b/packages/core/src/Item/Item.test.tsx
@@ -29,6 +29,7 @@ import {
} from '@testing-library/react';
import {rulesDeclaredFor} from '../__tests__/pressState';
import userEvent from '@testing-library/user-event';
+import {LinkProvider} from '../Link/LinkProvider';
import {Item} from './Item';
import {ItemDescriptionContext} from './ItemDescriptionContext';
import {List, ListItem} from '../List';
@@ -383,6 +384,65 @@ describe('Item', () => {
expect(screen.getByTestId('item')).toHaveAttribute('aria-disabled', 'true');
});
+ it("gives a disabled row's link no destination (spec:AST-085 FR2)", () => {
+ function RouterLink({ref, ...props}: React.ComponentPropsWithRef<'a'>) {
+ return <a ref={ref} data-router-link {...props} />;
+ }
+ render(
+ <LinkProvider component={RouterLink}>
+ <Item
+ label="Billing"
+ href="/billing"
+ target="_blank"
+ rel="noopener"
+ isDisabled
+ />
+ <Item label="Profile" href="/profile" />
+ </LinkProvider>,
+ );
+ // No href, target or rel, so a screen reader's click, Enter or a link
+ // menu cannot navigate; it keeps the link role and skips the router link.
+ const disabled = screen.getByRole('link', {name: 'Billing'});
+ expect(disabled).toHaveAttribute('aria-disabled', 'true');
+ for (const attribute of ['href', 'target', 'rel', 'data-router-link']) {
+ expect(disabled).not.toHaveAttribute(attribute);
+ }
+ const enabled = screen.getByRole('link', {name: 'Profile'});
+ expect(enabled).toHaveAttribute('href', '/profile');
+ expect(enabled).toHaveAttribute('data-router-link');
+ expect(enabled).not.toHaveAttribute('aria-disabled');
+ });
+
+ it('keeps focus on a focused link row that becomes disabled (spec:AST-085 FR4)', () => {
+ const {rerender} = render(<Item label="Billing" href="/billing" />);
+ screen.getByRole('link', {name: 'Billing'}).focus();
+ rerender(<Item label="Billing" href="/billing" isDisabled />);
+ // The disabled row renders a plain anchor in place of the link component;
+ // focus moves to it instead of falling to the page.
+ const disabled = screen.getByRole('link', {name: 'Billing'});
+ expect(disabled).not.toHaveAttribute('href');
+ expect(disabled).toHaveFocus();
+ rerender(<Item label="Billing" href="/billing" />);
+ expect(screen.getByRole('link', {name: 'Billing'})).toHaveFocus();
+ });
+
+ it('does not pull focus back to a row that changes while focus is elsewhere', () => {
+ const {rerender} = render(
+ <>
+ <Item label="Billing" href="/billing" />
+ <button type="button">Elsewhere</button>
+ </>,
+ );
+ screen.getByRole('button', {name: 'Elsewhere'}).focus();
+ rerender(
+ <>
+ <Item label="Billing" href="/billing" isDisabled />
+ <button type="button">Elsewhere</button>
+ </>,
+ );
+ expect(screen.getByRole('button', {name: 'Elsewhere'})).toHaveFocus();
+ });
+
it('disables the invisible button when isDisabled', () => {
const {container} = render(
<Item label="Disabled" onClick={() => {}} isDisabled />,
diff --git a/packages/core/src/Item/Item.tsx b/packages/core/src/Item/Item.tsx
index 063ff2829e..c1b3e5fa97 100644
--- a/packages/core/src/Item/Item.tsx
+++ b/packages/core/src/Item/Item.tsx
@@ -50,6 +50,7 @@ import {
import type {BaseProps} from '../BaseProps';
import {isRenderable} from '../utils/isRenderable';
import {mergeProps} from '../utils/mergeProps';
+import {useFocusAcrossSwap} from '../utils/useFocusAcrossSwap';
import {ItemDescriptionContext} from './ItemDescriptionContext';
import {ItemMarkerColumnsContext} from './ItemMarkerColumnsContext';
import {useMergedRefs} from '../hooks/useMergedRefs';
@@ -611,6 +612,13 @@ export function Item({
const pressable = usePressFeedback();
const columnMarker = use(ItemMarkerColumnsContext);
const LinkComponent = useLinkComponent();
+ // A disabled row's anchor has no destination, so no activation path (a
+ // screen reader's click, Enter, a link context menu) can navigate
+ // (spec:AST-085 FR2). Like a disabled Link, it keeps the link role and skips
+ // the router link component, which may require a live href. The element type
+ // then changes with `isDisabled`, so focus follows the swap (FR4).
+ const RowAnchor = isDisabled ? 'a' : LinkComponent;
+ const anchorRef = useFocusAcrossSwap<HTMLAnchorElement>();
// Delegation mode: the row is an enlarged click/tap target for a nested
// control (e.g. a checkbox) that owns the keyboard access and action. The
@@ -787,19 +795,18 @@ export function Item({
{labelAndDescription}
</span>
) : href != null && !isLinkRoot ? (
- <LinkComponent
- href={href}
- target={target}
- rel={rel}
- aria-disabled={isDisabled || undefined}
- tabIndex={isDisabled ? -1 : undefined}
+ <RowAnchor
+ ref={anchorRef}
+ {...(isDisabled
+ ? {role: 'link', 'aria-disabled': true, tabIndex: -1}
+ : {href, target, rel})}
{...stylex.props(
styles.invisibleAnchor,
isInline && styles.inlineContent,
isDisabled && styles.disabledContent,
)}>
{labelAndDescription}
- </LinkComponent>
+ </RowAnchor>
) : onClick != null ? (
<button
type="button"
diff --git a/packages/core/src/NavMenu/NavHeadingMenuItem.tsx b/packages/core/src/NavMenu/NavHeadingMenuItem.tsx
index cc1f2c4e01..c1d48d2602 100644
--- a/packages/core/src/NavMenu/NavHeadingMenuItem.tsx
+++ b/packages/core/src/NavMenu/NavHeadingMenuItem.tsx
@@ -12,7 +12,7 @@
* - /packages/core/src/NavMenu/index.ts
*/
-import React, {useCallback, useRef, type ReactNode} from 'react';
+import React, {useCallback, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {renderIconSlot, type IconType} from '../Icon';
import {Text} from '../Text';
@@ -23,7 +23,8 @@ import {
typeScaleVars,
radiusVars,
} from '../theme/tokens.stylex';
-import {mergeProps, mergeRefs} from '../utils';
+import {mergeProps} from '../utils/mergeProps';
+import {useFocusAcrossSwap} from '../utils/useFocusAcrossSwap';
import type {BaseProps} from '../BaseProps';
import {useNavHeadingMenuContext} from './NavMenuContext';
import {useLinkComponent} from '../Link/useLinkComponent';
@@ -156,43 +157,8 @@ export function NavHeadingMenuItem({
const Element = href ? (isDisabled ? 'a' : LinkComponent) : 'div';
// The element type above changes when `isDisabled` flips, so React replaces
- // the row. Carry focus over to the replacement when the outgoing node held it
- // (spec:AST-085 FR4). The ref cleanup runs before the old node is removed, so
- // `activeElement` is still readable there. Only a different node replacing a
- // removed one takes focus, and only if focus has fallen to the page: React
- // also detaches and re-attaches the same node (for example when an <Activity>
- // boundary hides and reveals the row), and neither case may pull focus back
- // after the person has moved elsewhere.
- const focusedNodeRef = useRef<HTMLElement | null>(null);
- const itemRef = useCallback(
- (node: HTMLElement | null) => {
- if (node === null) {
- return;
- }
- const outgoing = focusedNodeRef.current;
- focusedNodeRef.current = null;
- // Focus only follows the swap when it has fallen to the page. If the
- // person moved focus elsewhere in the meantime (for example while an
- // <Activity> boundary kept the row hidden), leave it alone.
- const focusFell =
- document.activeElement === null ||
- document.activeElement === document.body;
- if (
- outgoing !== null &&
- outgoing !== node &&
- !outgoing.isConnected &&
- focusFell
- ) {
- node.focus();
- }
- const release = mergeRefs<HTMLElement>(ref)(node);
- return () => {
- focusedNodeRef.current = document.activeElement === node ? node : null;
- release?.();
- };
- },
- [ref],
- );
+ // the row; focus follows to the replacement (spec:AST-085 FR4).
+ const itemRef = useFocusAcrossSwap<HTMLElement>(ref);
return (
<Element
diff --git a/packages/core/src/TreeList/TreeList.test.tsx b/packages/core/src/TreeList/TreeList.test.tsx
index 63b946a463..531cbab4b4 100644
--- a/packages/core/src/TreeList/TreeList.test.tsx
+++ b/packages/core/src/TreeList/TreeList.test.tsx
@@ -861,6 +861,26 @@ describe('TreeList', () => {
});
});
+ it("keeps focus on an item's inner link when the item becomes disabled (spec:AST-085 FR4)", () => {
+ const tree = (isDisabled: boolean) => [
+ {
+ id: 'docs',
+ label: 'Docs',
+ isExpanded: true,
+ children: [
+ {id: 'report', label: 'Report', href: '/report', isDisabled},
+ ],
+ },
+ ];
+ const {rerender} = render(<TreeList items={tree(false)} />);
+ // A pointer click leaves focus on the inner link.
+ screen.getByRole('link', {name: 'Report', hidden: true}).focus();
+ rerender(<TreeList items={tree(true)} />);
+ const disabled = screen.getByRole('link', {name: 'Report', hidden: true});
+ expect(disabled).not.toHaveAttribute('href');
+ expect(disabled).toHaveFocus();
+ });
+
it('does not follow a disabled link row', () => {
const items = [
{
@@ -879,6 +899,12 @@ describe('TreeList', () => {
const row = link.closest<HTMLElement>('.astryx-tree-list-item')!;
fireEvent.click(row.firstElementChild!);
expect(onLinkClick).not.toHaveBeenCalled();
+ // No destination, so a screen reader's click or a link menu cannot
+ // navigate either (spec:AST-085 FR2).
+ expect(link).toHaveAttribute('aria-disabled', 'true');
+ for (const attribute of ['href', 'target']) {
+ expect(link).not.toHaveAttribute(attribute);
+ }
});
describe('row clicks outside the label (FR7)', () => {
diff --git a/packages/core/src/TreeList/TreeListItem.tsx b/packages/core/src/TreeList/TreeListItem.tsx
index 7b152badd2..1e2c8a588d 100644
--- a/packages/core/src/TreeList/TreeListItem.tsx
+++ b/packages/core/src/TreeList/TreeListItem.tsx
@@ -32,7 +32,8 @@ import {
useClickableContainer,
} from '../hooks/useClickableContainer';
import {Icon} from '../Icon';
-import {mergeProps} from '../utils';
+import {mergeProps} from '../utils/mergeProps';
+import {useFocusAcrossSwap} from '../utils/useFocusAcrossSwap';
import {useLinkComponent} from '../Link/useLinkComponent';
import {TreeListBranches} from './TreeListBranches';
import type {TreeListDensity, TreeListVariant} from './TreeListTypes';
@@ -379,6 +380,9 @@ export interface TreeListItemInternalProps {
// Component
// =============================================================================
+/** A plain anchor, for a disabled item whose link has no destination. */
+const DisabledAnchor = 'a';
+
export function TreeListItem({
id,
label,
@@ -414,6 +418,10 @@ export function TreeListItem({
const descriptionId = useId();
const LinkComponent = useLinkComponent();
const linkRef = useRef<HTMLAnchorElement>(null);
+ // Disabling the item swaps the router link for a plain anchor, so React
+ // replaces it; focus on the inner link (after a pointer click) follows the
+ // swap instead of falling to the page (spec:AST-085 FR4).
+ const anchorRef = useFocusAcrossSwap<HTMLAnchorElement>(linkRef);
const isInteractive = onClick != null || href != null;
const handleToggle = useMemo(
@@ -596,12 +604,26 @@ export function TreeListItem({
{startContent != null && (
<span {...stylex.props(styles.startContent)}>{startContent}</span>
)}
- {href != null ? (
+ {href != null && isDisabled ? (
+ // A disabled item's anchor has no destination, so neither the row's
+ // forwarded activation nor a screen reader's click can navigate
+ // (spec:AST-085 FR2). Like a disabled Link, it keeps the link role and
+ // skips the router link component.
+ <DisabledAnchor
+ ref={anchorRef}
+ role="link"
+ aria-disabled={true}
+ aria-labelledby={labelId}
+ aria-describedby={description != null ? descriptionId : undefined}
+ tabIndex={-1}
+ {...stylex.props(styles.invisibleAnchor)}>
+ {labelAndDescription}
+ </DisabledAnchor>
+ ) : href != null ? (
<LinkComponent
- ref={linkRef}
+ ref={anchorRef}
href={href}
target={target}
- aria-disabled={isDisabled || undefined}
aria-labelledby={labelId}
aria-describedby={description != null ? descriptionId : undefined}
// Roving tabindex lives on the treeitem row; inner action is not a
diff --git a/packages/core/src/utils/useFocusAcrossSwap.ts b/packages/core/src/utils/useFocusAcrossSwap.ts
new file mode 100644
index 0000000000..2faa4753e2
--- /dev/null
+++ b/packages/core/src/utils/useFocusAcrossSwap.ts
@@ -0,0 +1,55 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useFocusAcrossSwap.ts
+ * @input An optional forwarded ref
+ * @output A callback ref that carries focus to a replacement element
+ * @position Internal hook for a component whose element type changes with a
+ * prop (a link row that renders a plain anchor while disabled). React
+ * replaces the element, so focus would fall to the page; spec:AST-085 FR4
+ * keeps it on the row.
+ *
+ * The ref cleanup runs before the old node is removed, so `activeElement` is
+ * still readable there. Only a different node replacing a removed one takes
+ * focus, and only if focus has fallen to the page: React also detaches and
+ * re-attaches the same node (for example when an <Activity> boundary hides and
+ * reveals it), and neither case may pull focus back after the person has moved
+ * elsewhere.
+ */
+
+import {useCallback, useRef, type Ref} from 'react';
+import {mergeRefs} from './mergeRefs';
+
+export function useFocusAcrossSwap<T extends HTMLElement>(
+ ref?: Ref<T>,
+): (node: T | null) => (() => void) | undefined {
+ const focusedNodeRef = useRef<T | null>(null);
+ return useCallback(
+ (node: T | null) => {
+ if (node === null) {
+ return undefined;
+ }
+ const outgoing = focusedNodeRef.current;
+ focusedNodeRef.current = null;
+ const focusFell =
+ document.activeElement === null ||
+ document.activeElement === document.body;
+ if (
+ outgoing !== null &&
+ outgoing !== node &&
+ !outgoing.isConnected &&
+ focusFell
+ ) {
+ node.focus();
+ }
+ const release = mergeRefs<T>(ref)(node);
+ return () => {
+ focusedNodeRef.current = document.activeElement === node ? node : null;
+ release?.();
+ };
+ },
+ [ref],
+ );
+}