Skip to content

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

TypeScript

fix(core): render Token remove button as a sibling of its link (#4361)

Baraa Hamodie891748fb09d
diff --git a/.changeset/a11y-token-remove-link.md b/.changeset/a11y-token-remove-link.md
new file mode 100644
index 0000000000..8952172b61
--- /dev/null
+++ b/.changeset/a11y-token-remove-link.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Token: render the remove button as a sibling of the link instead of nesting it inside the anchor when both `href` and `onRemove` are provided. The token surface now delegates to the link via `useClickableContainer`, so clicking anywhere on the token (including with middle-click or cmd/ctrl+click to open in a new tab) activates the link, while the remove button keeps handling its own clicks.
+@bhamodi
diff --git a/packages/core/src/Token/Token.test.tsx b/packages/core/src/Token/Token.test.tsx
index f0d3928c8c..44530863c6 100644
--- a/packages/core/src/Token/Token.test.tsx
+++ b/packages/core/src/Token/Token.test.tsx
@@ -330,6 +330,151 @@ describe('Token accessibility', () => {
});
});
+describe('Token link with remove button', () => {
+ it('does not nest the remove button inside the link', () => {
+ render(<Token label="Tag" href="/test" onRemove={() => {}} />);
+ const link = screen.getByRole('link', {name: 'Tag'});
+ const removeButton = screen.getByRole('button', {name: 'Remove Tag'});
+ expect(link.contains(removeButton)).toBe(false);
+ });
+
+ it('keeps the link keyboard-focusable and fires onRemove from the sibling button', async () => {
+ const user = userEvent.setup();
+ const handleRemove = vi.fn();
+ render(<Token label="Tag" href="/test" onRemove={handleRemove} />);
+
+ const link = screen.getByRole('link', {name: 'Tag'});
+ expect(link.tagName).toBe('A');
+ expect(link).toHaveAttribute('href', '/test');
+
+ // Tab reaches the link first, then the remove button
+ await user.tab();
+ expect(link).toHaveFocus();
+ await user.tab();
+ const removeButton = screen.getByRole('button', {name: 'Remove Tag'});
+ expect(removeButton).toHaveFocus();
+
+ // Activating the remove button fires onRemove without involving the link
+ await user.keyboard('{Enter}');
+ expect(handleRemove).toHaveBeenCalledTimes(1);
+ });
+
+ it('wrapper structure matches the onClick branch pattern', () => {
+ render(
+ <Token
+ label="Tag"
+ href="/test"
+ onRemove={() => {}}
+ data-testid="link-token"
+ />,
+ );
+ render(
+ <Token
+ label="Tag"
+ onClick={() => {}}
+ onRemove={() => {}}
+ data-testid="click-token"
+ />,
+ );
+
+ const linkRoot = screen.getByTestId('link-token');
+ const clickRoot = screen.getByTestId('click-token');
+
+ // Both render a <span> container with the same visual classes
+ expect(linkRoot.tagName).toBe('SPAN');
+ expect(linkRoot.className).toBe(clickRoot.className);
+ });
+
+ it('clicking the container activates the link', () => {
+ render(
+ <Token
+ label="Tag"
+ href="/test"
+ onRemove={() => {}}
+ icon={<span data-testid="icon">★</span>}
+ data-testid="link-token"
+ />,
+ );
+ const link = screen.getByRole('link', {name: 'Tag'});
+ const handleLinkClick = vi.fn((e: MouseEvent) => e.preventDefault());
+ link.addEventListener('click', handleLinkClick);
+
+ // Clicking outside the anchor (e.g. the icon) still activates the link
+ fireEvent.click(screen.getByTestId('icon'));
+ expect(handleLinkClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('clicking the remove button does not activate the link', () => {
+ const handleRemove = vi.fn();
+ render(<Token label="Tag" href="/test" onRemove={handleRemove} />);
+ const link = screen.getByRole('link', {name: 'Tag'});
+ const handleLinkClick = vi.fn((e: MouseEvent) => e.preventDefault());
+ link.addEventListener('click', handleLinkClick);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Remove Tag'}));
+ expect(handleRemove).toHaveBeenCalledTimes(1);
+ expect(handleLinkClick).not.toHaveBeenCalled();
+ });
+
+ it('cmd/ctrl+click on the container opens the link in a new tab', () => {
+ const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
+ render(
+ <Token
+ label="Tag"
+ href="/test"
+ onRemove={() => {}}
+ icon={<span data-testid="icon">★</span>}
+ />,
+ );
+
+ // Clicking the surface (not the anchor) with a modifier opens a new tab
+ // rather than navigating in place — provided by useClickableContainer.
+ fireEvent.click(screen.getByTestId('icon'), {metaKey: true});
+ expect(openSpy).toHaveBeenCalledWith('/test', '_blank', 'noopener');
+ openSpy.mockRestore();
+ });
+
+ it('middle-click on the container opens the link in a new tab', () => {
+ const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
+ render(
+ <Token
+ label="Tag"
+ href="/test"
+ onRemove={() => {}}
+ icon={<span data-testid="icon">★</span>}
+ />,
+ );
+
+ fireEvent.mouseUp(screen.getByTestId('icon'), {button: 1});
+ expect(openSpy).toHaveBeenCalledWith('/test', '_blank', 'noopener');
+ openSpy.mockRestore();
+ });
+
+ it('a modified click that opens a new tab does not fire onRemove', () => {
+ const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
+ const handleRemove = vi.fn();
+ render(
+ <Token
+ label="Tag"
+ href="/test"
+ onRemove={handleRemove}
+ icon={<span data-testid="icon">★</span>}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId('icon'), {metaKey: true});
+ fireEvent.mouseUp(screen.getByTestId('icon'), {button: 1});
+ expect(handleRemove).not.toHaveBeenCalled();
+ expect(openSpy).toHaveBeenCalledTimes(2);
+ openSpy.mockRestore();
+ });
+
+ it('link without onRemove still renders the anchor as the root', () => {
+ const {container} = render(<Token label="Link" href="/test" />);
+ expect(container.firstElementChild?.tagName).toBe('A');
+ });
+});
+
describe('Token text overflow', () => {
it('label element has overflow hidden and text-overflow ellipsis styles', () => {
const {container} = render(<Token label="A very long label text" />);
diff --git a/packages/core/src/Token/Token.tsx b/packages/core/src/Token/Token.tsx
index d99c03f1f1..71945c9912 100644
--- a/packages/core/src/Token/Token.tsx
+++ b/packages/core/src/Token/Token.tsx
@@ -9,6 +9,7 @@
* @position Core implementation; consumed by index.ts, tested by Token.test.tsx
*
* SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Token/TokenLink.tsx (interactive wrapper for href+onRemove)
* - /packages/core/src/Token/Token.doc.mjs (props table, features, implementation notes)
* - /packages/core/src/Token/Token.test.tsx (tests for new/changed behavior)
* - /packages/core/src/Token/index.ts (exports if types change)
@@ -32,6 +33,7 @@ import {Icon} from '../Icon';
import {mergeProps} from '../utils';
import {useLinkComponent} from '../Link/useLinkComponent';
import {useInteractiveRole} from '../hooks/useInteractiveRole';
+import {TokenLink} from './TokenLink';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
@@ -313,7 +315,9 @@ const colorStyles = stylex.create({
* `<span>` container with an invisible `<button>` when `onClick` is provided.
* The invisible button pattern provides real button semantics for accessibility
* while the container uses `:focus-within` to show focus outlines around the
- * entire token.
+ * entire token. When both `href` and `onRemove` are provided, the same
+ * container pattern is used with an invisible `<a>` so the remove `<button>`
+ * renders as a sibling of the link rather than nested inside it.
*
* @example
* ```
@@ -350,6 +354,20 @@ export function Token({
// if onClick was provided — the popover attaches its own handler.
const effectiveOnClick = onClick ?? (role === 'button' ? () => {} : null);
+ const removeButton = onRemove != null && (
+ <button
+ type="button"
+ aria-label={t('@astryx.token.remove', {label})}
+ onClick={e => {
+ e.stopPropagation();
+ onRemove(e);
+ }}
+ disabled={isDisabled}
+ {...stylex.props(styles.removeButton)}>
+ <Icon icon="close" size="xsm" color="inherit" />
+ </button>
+ );
+
const content = (
<>
{icon}
@@ -358,19 +376,7 @@ export function Token({
{label}
</span>
{endContent}
- {onRemove != null && (
- <button
- type="button"
- aria-label={t('@astryx.token.remove', {label})}
- onClick={e => {
- e.stopPropagation();
- onRemove(e);
- }}
- disabled={isDisabled}
- {...stylex.props(styles.removeButton)}>
- <Icon icon="close" size="xsm" color="inherit" />
- </button>
- )}
+ {removeButton}
</>
);
@@ -381,11 +387,57 @@ export function Token({
};
if (role === 'link') {
+ if (onRemove == null) {
+ return (
+ <LinkComponent
+ ref={ref as React.Ref<HTMLAnchorElement>}
+ href={href as string}
+ aria-disabled={isDisabled || undefined}
+ {...sharedProps}
+ {...mergeProps(
+ themeProps('token', {color, size}),
+ stylex.props(
+ styles.base,
+ sizeStyles[size],
+ colorStyles[color],
+ styles.interactive,
+ isDisabled && styles.disabled,
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ {content}
+ </LinkComponent>
+ );
+ }
+
+ // With a remove button, the link cannot be the root — nesting a <button>
+ // inside an <a> is invalid HTML (WCAG 4.1.2). Delegate to TokenLink, a
+ // non-presentational wrapper that renders a <span> container with the link
+ // and the remove button as siblings and wires up useClickableContainer so
+ // the whole token surface activates the link (including middle-click and
+ // cmd/ctrl-click to open in a new tab). Token itself stays presentational
+ // (no refs/effects) per the @astryx/presentational-component rule.
return (
- <LinkComponent
- ref={ref as React.Ref<HTMLAnchorElement>}
+ <TokenLink
+ ref={ref}
href={href as string}
- aria-disabled={isDisabled || undefined}
+ isDisabled={isDisabled}
+ LinkComponent={LinkComponent}
+ icon={icon}
+ endContent={endContent}
+ removeButton={removeButton}
+ linkStyleProps={stylex.props(styles.invisibleButton)}
+ labelContent={
+ <span
+ {...stylex.props(
+ styles.label,
+ isLabelHidden && styles.labelHidden,
+ )}>
+ {label}
+ </span>
+ }
{...sharedProps}
{...mergeProps(
themeProps('token', {color, size}),
@@ -394,14 +446,14 @@ export function Token({
sizeStyles[size],
colorStyles[color],
styles.interactive,
+ styles.focusVisibleOutline,
isDisabled && styles.disabled,
xstyle,
),
className,
style,
- )}>
- {content}
- </LinkComponent>
+ )}
+ />
);
}
@@ -448,19 +500,7 @@ export function Token({
</span>
</button>
{endContent}
- {onRemove != null && (
- <button
- type="button"
- aria-label={t('@astryx.token.remove', {label})}
- onClick={e => {
- e.stopPropagation();
- onRemove(e);
- }}
- disabled={isDisabled}
- {...stylex.props(styles.removeButton)}>
- <Icon icon="close" size="xsm" color="inherit" />
- </button>
- )}
+ {removeButton}
</span>
);
}
diff --git a/packages/core/src/Token/TokenLink.tsx b/packages/core/src/Token/TokenLink.tsx
new file mode 100644
index 0000000000..63532a5d19
--- /dev/null
+++ b/packages/core/src/Token/TokenLink.tsx
@@ -0,0 +1,107 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file TokenLink.tsx
+ * @input Rendered token pieces (icon, label, endContent, remove button) plus
+ * container/link styling props and the resolved LinkComponent
+ * @output Exports TokenLink, the interactive container for the href+onRemove Token variant
+ * @position Internal to Token; keeps Token.tsx presentational
+ *
+ * Token is a presentational component (see
+ * /internal/eslint-plugin-astryx/presentational-component.js) and must not use
+ * refs or effects. When a Token has both `href` and `onRemove`, the remove
+ * <button> must be a sibling of the link (nesting a button inside an anchor is
+ * invalid HTML — WCAG 4.1.2), so the surface becomes a clickable container that
+ * delegates to an inner link. That delegation needs refs, so it lives here.
+ *
+ * useClickableContainer gives the container middle-click and cmd/ctrl-click
+ * open-in-new-tab behavior for the link, ignores clicks on nested interactive
+ * elements (the remove button), and skips activation during text selection.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Token/Token.tsx (renders TokenLink for the href+onRemove case)
+ * - /packages/core/src/Token/Token.test.tsx (tests for delegated behavior)
+ */
+
+import type {ReactNode, CSSProperties, Ref, HTMLAttributes} from 'react';
+import {useRef} from 'react';
+import {mergeRefs} from '../utils';
+import {useClickableContainer} from '../hooks/useClickableContainer';
+import type {LinkComponentType} from '../Link/types';
+
+export interface TokenLinkProps extends HTMLAttributes<HTMLElement> {
+ /** Ref forwarded to the container element. */
+ ref?: Ref<HTMLElement>;
+ /** Link URL. */
+ href: string;
+ /** Whether the token is disabled. */
+ isDisabled: boolean;
+ /** Resolved link component (native `<a>` or a router link). */
+ LinkComponent: LinkComponentType;
+ /** `stylex.props()` output applied to the invisible inner link. */
+ linkStyleProps: {className?: string; style?: CSSProperties};
+ /** Visible (or visually hidden) label node rendered inside the link. */
+ labelContent: ReactNode;
+ /** Optional leading icon. */
+ icon?: ReactNode;
+ /** Content rendered after the label, before the remove button. */
+ endContent?: ReactNode;
+ /** The remove button node, rendered as a sibling of the link. */
+ removeButton: ReactNode;
+ /** Allow data-* attributes (e.g. data-testid, theme targets) on the container. */
+ [dataAttr: `data-${string}`]: unknown;
+}
+
+/**
+ * Interactive container for a Token that is both a link and removable.
+ *
+ * Renders a `<span>` wrapping an invisible inner link and the remove button as
+ * siblings. useClickableContainer delegates clicks on the surface to the link
+ * (including middle-click / cmd+click to open in a new tab) while the remove
+ * button keeps handling its own clicks.
+ */
+export function TokenLink({
+ ref,
+ href,
+ isDisabled,
+ LinkComponent,
+ linkStyleProps,
+ labelContent,
+ icon,
+ endContent,
+ removeButton,
+ ...containerProps
+}: TokenLinkProps) {
+ const containerRef = useRef<HTMLElement | null>(null);
+ const linkRef = useRef<HTMLElement | null>(null);
+
+ const {onClick, onMouseUp} = useClickableContainer({
+ containerRef,
+ interactiveRef: linkRef,
+ href,
+ disabled: isDisabled,
+ });
+
+ return (
+ <span
+ ref={mergeRefs(ref, containerRef)}
+ onClick={isDisabled ? undefined : onClick}
+ onMouseUp={isDisabled ? undefined : onMouseUp}
+ {...containerProps}>
+ {icon}
+ <LinkComponent
+ ref={linkRef as Ref<HTMLAnchorElement>}
+ href={href}
+ aria-disabled={isDisabled || undefined}
+ {...linkStyleProps}>
+ {labelContent}
+ </LinkComponent>
+ {endContent}
+ {removeButton}
+ </span>
+ );
+}
+
+TokenLink.displayName = 'TokenLink';