An open source design system that's fully customizable and agent ready
TypeScript
fix(core): render plain Link anchors inline so an ancestor Text clamp can truncate them (#6038)
Manohar Paturi6da9b3244f4f
diff --git a/.changeset/link-anchor-clamp.md b/.changeset/link-anchor-clamp.mdnew file mode 100644index 0000000000..a42509ef79--- /dev/null+++ b/.changeset/link-anchor-clamp.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Link: inside a `<Text maxLines>` the link now truncates with the text. There its root lays out inline, in the text's lines, so the clamp can cut through the link, and its keyboard focus ring is inset into each line, so the clamp keeps the ring's top and bottom edges visible. Elsewhere, and for a Link that sets its own `display` or `maxLines` or renders as a button, the root keeps its `inline-flex` box. A Link with block-level content, such as an `HStack` with an icon, is not supported inside a clamped Text, because it breaks the clamp; place that composition outside the clamp. (#6021)++@ManoharPaturidiff --git a/apps/storybook/stories/Link.stories.tsx b/apps/storybook/stories/Link.stories.tsxindex ba9603ff45..c6aaf9f369 100644--- a/apps/storybook/stories/Link.stories.tsx+++ b/apps/storybook/stories/Link.stories.tsx@@ -199,6 +199,38 @@ export const WrappedLines: Story = {),};+/**+ * A long Link inside `<Text maxLines={2}>` or `<Text maxLines={1}>` clamps+ * with the ancestor text and keeps an inset focus ring, while a composed Link+ * outside a clamp keeps its own box and focus ring.+ */+export const ClampedByAncestorText: Story = {+ tags: ['!autodocs'],+ render: () => (+ <div style={{display: 'grid', gap: 24, width: 220}}>+ <Text maxLines={2} data-testid="ancestor-clamp-text">+ <Link href="/changelog">+ Quarterly planning review with the product and research teams across+ every region, plus the follow up retrospective notes and the rollout+ summary+ </Link>{' '}+ and the closing remarks that follow the link in the same paragraph+ </Text>+ <Text maxLines={1} data-testid="ancestor-clamp-one-line">+ <Link href="/roadmap">+ Roadmap for the next two quarters with every milestone+ </Link>{' '}+ and the owners+ </Text>+ <p style={{margin: 0}} data-testid="composed-host">+ <Link href="/team" data-testid="composed-link">+ <strong>Team</strong> directory and roster listing for the whole org+ </Link>+ </p>+ </div>+ ),+};+export const AllVariants: Story = {render: () => (<divdiff --git a/docs/specs/components/Link/Link.spec.md b/docs/specs/components/Link/Link.spec.mdindex 59323fbfb3..3bf591a216 100644--- a/docs/specs/components/Link/Link.spec.md+++ b/docs/specs/components/Link/Link.spec.md@@ -15,6 +15,7 @@ verified_by:packages/core/src/Link/Link.test.tsx,packages/core/src/Link/__tests__/Link.a11y.test.tsx,packages/core/src/Link/__tests__/Link.a11y.chromium.spec.ts,+ packages/core/src/Link/__tests__/Link.ancestor-clamp.a11y.chromium.spec.ts,packages/core/src/Link/__tests__/Link.hoverColor.a11y.chromium.spec.ts,packages/core/src/Link/__tests__/Link.navigation.a11y.chromium.spec.ts,packages/core/src/Link/__tests__/Link.truncation.a11y.chromium.spec.ts,@@ -43,7 +44,7 @@ system_specs: [spec:AST-005, spec:AST-085]| Behavior | An enabled Link with `href` is a link rendered by `as`, then `LinkProvider`, then a native anchor. Otherwise it is a link-styled `<button>`, except that an inherited link role renders the link component, and a disabled Link with `href` and no `onClick` renders a plain anchor unless an inherited button role makes it a disabled `<button>` (FR1). A disabled Link stays focusable and inert. || End-user impact | People get one link look for navigation and link-styled actions. Keyboard and screen-reader users can reach a disabled Link and hear that it is disabled. External links without `label` announce that they open a new tab. || Builder impact | A theme restyles Link's label color through the `link` target; a `text` target color no longer reaches it. |-| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. A focused link that becomes disabled loses focus, caller attributes can replace Link's disabled exposure and `data-color`, and an ancestor Text line clamp cannot truncate a Link; all are listed under Current-state impact. |+| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. A focused link that becomes disabled loses focus, and caller attributes can replace Link's disabled exposure and `data-color`; both are listed under Current-state impact. || Review checks | Reject a disabled Link that navigates, runs `onClick`, or leaves the tab order; a `_blank` target without `noopener noreferrer`; an external link with no new-tab text; or a rejected destination that reaches a router. || Governing rules | `family:navigation-destinations` FR1–FR7; `spec:AST-005`; `spec:AST-085` FR1, FR2, FR4, FR5; `architecture:interaction-modality` INV1; `design:user-states` DR1, DR2. |@@ -111,7 +112,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR3 | An external Link that is not rendered as a button shows a trailing extra-small external-link icon that inherits the root's color, followed by visually hidden new-tab text: `newTabLabel`, else the localized default. | Current source and tests || FR4 | A destination reaches the link component only through the shared navigation rule; a rejected destination renders an inert anchor and never invokes a router. | `family:navigation-destinations` FR1–FR6; `spec:AST-005` || FR5 | A disabled Link stays focusable with `aria-disabled="true"`, never navigates, and never runs `onClick`. The disabled anchor form omits `href`, `target`, and `rel`, takes a Tab stop, and skips the custom link component. In every form, clicks are cancelled and stopped, Enter and Space are suppressed, other keys reach the caller's `onKeyDown`, and the Link paints at half opacity with no pointer events and no press paint. A focused Link that becomes disabled MUST keep focus and expose the change on that element (`spec:AST-085` FR4, FR5), and a caller `aria-disabled`, `role`, or `tabIndex` MUST NOT replace the disabled exposure (`architecture:public-component-api` INV5). Implementation gap: caller props spread after Link's own, so a caller `aria-disabled`, `role`, or `tabIndex` overrides them. Implementation gap: an enabled link renders through the safe link component and a disabled one as a plain anchor (or a `<button>` when it has `onClick`), so a focused link that becomes disabled (or re-enabled) is replaced and focus falls to the page. | `spec:AST-085` FR1, FR2, FR4, FR5; `family:navigation-destinations` FR7; current tests |-| FR6 | Children render inside Text with `type` (default `body`), `size`, `weight`, `color` (default `accent`; for a color the root paints, FR7, the label inherits it), `display` (default `inline`), and `maxLines` (default `0`). The root inherits font family, size, weight, line height, and text alignment and lays content out with a small gap; with `maxLines` above 0 it stops at its container, so its Text truncates inside a constrained line; `isStandalone` sets the body size and leading on the root. A Link inside a Text with `maxLines` MUST truncate with that text. Implementation gap: the root is `inline-flex`, so an ancestor Text clamp does not truncate it. | Current source and tests |+| FR6 | Children render inside Text with `type` (default `body`), `size`, `weight`, `color` (default `accent`; for a color the root paints, FR7, the label inherits it), `display` (default `inline`), and `maxLines` (default `0`). The root inherits font family, size, weight, line height, and text alignment and lays content out with a small gap; with `maxLines` above 0 it stops at its container, so its Text truncates inside a constrained line; `isStandalone` sets the body size and leading on the root. A Link inside a Text with `maxLines` MUST truncate with that text: there its root lays out inline, in the text's lines, unless the Link sets its own `display` or `maxLines` or renders as a button, and keeps its visible focus ring (an inset ring, `architecture:interaction-modality` INV1). A Link whose content is block-level is not supported inside a clamped Text, because it breaks the clamp. Link reads the enclosing Text's clamp, never its children (AV1). | Current source and tests || FR7 | The root paints the chosen color for the six built-in colors, which the underline and the external icon take. The label inherits the root's color at rest and on hover; a theme styles Link's color through the `link` target. On hover-capable pointers an enabled Link underlines on hover, and for `primary`, `secondary`, and `accent` the root color mixes in the hover tint, so the label, the underline, and the icon keep one color. `hasUnderline` underlines at rest. | Current source and tests || FR8 | Press feedback follows `design:user-states` DR1 and DR2 for Link's text surface: an enabled link or button form paints the pressed overlay, and a disabled Link does not. | `design:user-states` DR1, DR2; current tests || FR9 | `label`, when non-empty, becomes `aria-label` and replaces the content as the accessible name; a caller `aria-label` overrides it; otherwise the content is the name. | Current tests |@@ -189,19 +190,19 @@ carries no anatomy-theming map.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |-| FR1, AR1 | `Link.test.tsx` element-form, `as`, and provider cases; `Link.a11y.chromium.spec.ts` | Native, router, button form, disabled | A wrong element form or role fails. Evidence gap: no test renders Link under an inherited interactive role (FR1 (c)). | `audit:Link/anatomy` |-| FR2, FR3, AR3 | `Link.test.tsx` external, target, rel, and new-tab cases; `Link.a11y.chromium.spec.ts` external state | External; explicit `_blank`; custom label | A missing safety token, icon, or new-tab text fails. Evidence gap: no test checks the accessible name of an external link with `label`. Evidence gap: no test sets `referrerPolicy` or asserts the external icon's size or color. | `audit:Link/accessibility` |-| FR4 | `Link.navigation.a11y.chromium.spec.ts` | Rejected and ordinary schemes; native, router, downloads | A rejected destination that navigates or reaches a router fails. | `audit:Link/behavior` |-| FR5, AR2 | `Link.test.tsx` disabled cases | Disabled anchor; disabled button form; with `onClick` | Navigation, a consumer `onClick`, a lost Tab stop, or a custom component on a disabled link fails. Evidence gap: no test disables a focused link or passes a caller `aria-disabled`, `role`, or `tabIndex`. Evidence gap: no test asserts that other keys reach the caller's `onKeyDown`, or the half-opacity, no-pointer-events paint. | `audit:Link/accessibility` |-| FR6 (type) | `Link.test.tsx` text-type cases; `Link.wrappedLines.a11y.chromium.spec.ts` (wrapped text alignment) | Default `body`; `type="inherit"`; wrapped button and anchor forms in a start-aligned, right-to-left and centred line | A dropped Text `type` fails. `Link.truncation.a11y.chromium.spec.ts`: an anchor and a button Link with `maxLines={1}` in a fixed-width line stop at the line and draw an ellipsis. Evidence gap: no test asserts that `size`, `weight`, `color`, or `display` reach Text, or the `isStandalone` root size. A button form whose wrapped lines line up differently from the anchor form fails. | `audit:Link/visual` |-| FR6, FR7 (paint) | `Link.hoverColor.a11y.chromium.spec.ts` (the hovered label, root, and icon share one computed color; the resting color returns); evidence gap: the underline and standalone cases assert only that a link renders | Each color; `hasUnderline`; `isStandalone` | — | `audit:Link/visual` |-| FR8 | `Link.test.tsx` pressed-state suite | Link, button form, disabled | No press paint, or press paint on a disabled Link, fails. | `audit:Link/behavior` |-| FR9, FR11, AR4 | `Link.test.tsx` label, ref, and theme-class cases | With and without `label`; `data-color` | A missing or extra `aria-label`, target, `data-color`, or ref fails. The accessibility suites assert a passed `data-*` attribute and `aria-current` on the root, and the navigation suite asserts `download`. Evidence gap: no test passes both `label` and `aria-label`, or passes `className`, `style`, or `xstyle`. | `audit:Link/theming` |-| FR10 | Evidence gap: the tooltip case asserts only that the link renders | Tooltip | — | `audit:Link/accessibility` |-| ORD1–ORD3 | Covered by the FR1–FR3 rows | — | — | `audit:Link/behavior` |-| PR1, AR5 | Evidence gap: no test asserts the absence of per-link listeners or the focus indicator | — | — | `audit:Link/accessibility` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |+| FR1, AR1 | `Link.test.tsx` element-form, `as`, and provider cases; `Link.a11y.chromium.spec.ts` | Native, router, button form, disabled | A wrong element form or role fails. Evidence gap: no test renders Link under an inherited interactive role (FR1 (c)). | `audit:Link/anatomy` |+| FR2, FR3, AR3 | `Link.test.tsx` external, target, rel, and new-tab cases; `Link.a11y.chromium.spec.ts` external state | External; explicit `_blank`; custom label | A missing safety token, icon, or new-tab text fails. Evidence gap: no test checks the accessible name of an external link with `label`. Evidence gap: no test sets `referrerPolicy` or asserts the external icon's size or color. | `audit:Link/accessibility` |+| FR4 | `Link.navigation.a11y.chromium.spec.ts` | Rejected and ordinary schemes; native, router, downloads | A rejected destination that navigates or reaches a router fails. | `audit:Link/behavior` |+| FR5, AR2 | `Link.test.tsx` disabled cases | Disabled anchor; disabled button form; with `onClick` | Navigation, a consumer `onClick`, a lost Tab stop, or a custom component on a disabled link fails. Evidence gap: no test disables a focused link or passes a caller `aria-disabled`, `role`, or `tabIndex`. Evidence gap: no test asserts that other keys reach the caller's `onKeyDown`, or the half-opacity, no-pointer-events paint. | `audit:Link/accessibility` |+| FR6 (type) | `Link.test.tsx` text-type and clamp-display cases; `Link.wrappedLines.a11y.chromium.spec.ts` (wrapped text alignment); `Link.ancestor-clamp.a11y.chromium.spec.ts` (a default Link inside `<Text maxLines={2}>` is inline and the clamp cuts through it; a Link inside a one- and a two-line clamp shows the top and bottom edges of its inset focus ring; a composed Link outside a clamp keeps its box and focus outline) | Default `body`; `type="inherit"`; wrapped button and anchor forms in a start-aligned, right-to-left and centred line | A dropped Text `type` fails. `Link.truncation.a11y.chromium.spec.ts`: an anchor and a button Link with `maxLines={1}` in a fixed-width line stop at the line and draw an ellipsis. Evidence gap: no test asserts that `size`, `weight`, `color`, or `display` reach Text, or the `isStandalone` root size. A button form whose wrapped lines line up differently from the anchor form fails. | `audit:Link/visual` |+| FR6, FR7 (paint) | `Link.hoverColor.a11y.chromium.spec.ts` (the hovered label, root, and icon share one computed color; the resting color returns); evidence gap: the underline and standalone cases assert only that a link renders | Each color; `hasUnderline`; `isStandalone` | — | `audit:Link/visual` |+| FR8 | `Link.test.tsx` pressed-state suite | Link, button form, disabled | No press paint, or press paint on a disabled Link, fails. | `audit:Link/behavior` |+| FR9, FR11, AR4 | `Link.test.tsx` label, ref, and theme-class cases | With and without `label`; `data-color` | A missing or extra `aria-label`, target, `data-color`, or ref fails. The accessibility suites assert a passed `data-*` attribute and `aria-current` on the root, and the navigation suite asserts `download`. Evidence gap: no test passes both `label` and `aria-label`, or passes `className`, `style`, or `xstyle`. | `audit:Link/theming` |+| FR10 | Evidence gap: the tooltip case asserts only that the link renders | Tooltip | — | `audit:Link/accessibility` |+| ORD1–ORD3 | Covered by the FR1–FR3 rows | — | — | `audit:Link/behavior` |+| PR1, AR5 | Evidence gap: no test asserts the absence of per-link listeners or the focus indicator | — | — | `audit:Link/accessibility` |## Current-state impact@@ -212,8 +213,6 @@ carries no anatomy-theming map.is replaced by the plain disabled anchor, or by a `<button>` when it has`onClick`, so keyboard focus falls to the page and the change is not exposedon the focused element, against `spec:AST-085` FR4 and FR5.-- **Ancestor line clamp (FR6).** The root is inline-flex, so an ancestor Text- `maxLines` clamp does not truncate a Link inside it.- **Consumer docs.** `Link.doc.mjs` anatomy lists Left icon and Right iconparts; Link renders no icon slots, only caller content and the external icon(FR3).diff --git a/docs/specs/components/Text/Text.spec.md b/docs/specs/components/Text/Text.spec.mdindex e32d309b0c..50bf24357a 100644--- a/docs/specs/components/Text/Text.spec.md+++ b/docs/specs/components/Text/Text.spec.md@@ -80,6 +80,11 @@ Consumer migration instructions belong in consumer docs and release notes.- Type-based size, weight, and default color; size, color, and weightoverrides; and the text layout controls on that element.- Measuring truncation and deciding when to compose the truncation Tooltip.+- The clamp it provides to its content. A Link inside a clamped Text lays out+ inline so the clamp truncates it, and keeps its visible focus ring as an+ inset ring (`component:Link` FR6); Text provides that clamp through an+ internal context. Block-level content, such as a Link that composes a+ stack, is not supported inside a clamped Text, because it breaks the clamp.**Does not own / non-goals**diff --git a/packages/core/src/Link/Link.doc.mjs b/packages/core/src/Link/Link.doc.mjsindex 326a3a8c0f..6b8c5a77d5 100644--- a/packages/core/src/Link/Link.doc.mjs+++ b/packages/core/src/Link/Link.doc.mjs@@ -182,10 +182,13 @@ export const docs = {bestPractices: [{ guidance: true, description: 'Write descriptive, concise link text that clearly communicates the destination.' },{ guidance: true, description: 'Set `isStandalone` when the link appears outside of inline text, so it receives proper base font sizing.' },+ { guidance: true, description: 'Put a Link inside a <Text maxLines> to truncate it with the surrounding text; inside a clamped Text the link flows in the text\'s lines.' },{ guidance: true, description: 'Only set `label` when the link content is not descriptive text (e.g. an icon-only link). For text links, the visible text is already the accessible name; adding `label` overrides it for screen readers, which is harmful.' },{ guidance: false, description: 'Use Link for actions that do not navigate; use a Button instead.' },{ guidance: false, description: 'Use generic text like "click here" or "read more"; describe the destination.' },{ guidance: false, description: 'Set `label` on text links; `aria-label` prevents assistive technology from reading the actual link content.' },+ { guidance: false, description: 'Give a Link inside a clamped Text its own `display` or `maxLines`, or render it as a button (`onClick` with no `href`), and expect the outer clamp to cut it; that Link keeps its own box.' },+ { guidance: false, description: 'Put a Link with block-level content, such as an HStack with an icon, inside a clamped Text; block content breaks the clamp. Clamp a text-only Link, or place the composed Link outside the clamp.' },],anatomy: [{name: 'Label', required: true, description: 'The visible text of the link.'},@@ -314,10 +317,13 @@ export const docsZh = {bestPractices: [{ guidance: true, description: 'Write descriptive, concise link text that clearly communicates the destination.' },{ guidance: true, description: 'Set `isStandalone` when the link appears outside of inline text, so it receives proper base font sizing.' },+ { guidance: true, description: 'Put a Link inside a <Text maxLines> to truncate it with the surrounding text; inside a clamped Text the link flows in the text\'s lines.' },{ guidance: true, description: 'Only set `label` when the link content is not descriptive text (e.g. an icon-only link). For text links, the visible text is already the accessible name; adding `label` overrides it for screen readers, which is harmful.' },{ guidance: false, description: 'Use Link for actions that do not navigate; use a Button instead.' },{ guidance: false, description: 'Use generic text like "click here" or "read more"; describe the destination.' },{ guidance: false, description: 'Set `label` on text links; `aria-label` prevents assistive technology from reading the actual link content.' },+ { guidance: false, description: 'Give a Link inside a clamped Text its own `display` or `maxLines`, or render it as a button (`onClick` with no `href`), and expect the outer clamp to cut it; that Link keeps its own box.' },+ { guidance: false, description: 'Put a Link with block-level content, such as an HStack with an icon, inside a clamped Text; block content breaks the clamp. Clamp a text-only Link, or place the composed Link outside the clamp.' },],anatomy: [{name: 'Label', required: true, description: 'The visible text of the link.'},@@ -337,10 +343,13 @@ export const docsDense = {bestPractices: [{ guidance: true, description: 'Write descriptive, concise link text that clearly communicates the destination.' },{ guidance: true, description: 'Set `isStandalone` when the link appears outside of inline text, so it receives proper base font sizing.' },+ { guidance: true, description: 'Put a Link inside a <Text maxLines> to truncate it with the surrounding text; inside a clamped Text the link flows in the text\'s lines.' },{ guidance: true, description: 'Only set `label` when the link content is not descriptive text (e.g. an icon-only link). For text links, the visible text is already the accessible name; adding `label` overrides it for screen readers, which is harmful.' },{ guidance: false, description: 'Use Link for actions that do not navigate; use a Button instead.' },{ guidance: false, description: 'Use generic text like "click here" or "read more"; describe the destination.' },{ guidance: false, description: 'Set `label` on text links; `aria-label` prevents assistive technology from reading the actual link content.' },+ { guidance: false, description: 'Give a Link inside a clamped Text its own `display` or `maxLines`, or render it as a button (`onClick` with no `href`), and expect the outer clamp to cut it; that Link keeps its own box.' },+ { guidance: false, description: 'Put a Link with block-level content, such as an HStack with an icon, inside a clamped Text; block content breaks the clamp. Clamp a text-only Link, or place the composed Link outside the clamp.' },],anatomy: [{name: 'Label', required: true, description: 'The visible text of the link.'},diff --git a/packages/core/src/Link/Link.test.tsx b/packages/core/src/Link/Link.test.tsxindex 9e9a90a717..5d6df8aa58 100644--- a/packages/core/src/Link/Link.test.tsx+++ b/packages/core/src/Link/Link.test.tsx@@ -13,6 +13,9 @@ import {describe, it, expect, vi} from 'vitest';import {fireEvent, render, screen} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {hasPressedArm} from '../__tests__/pressState';+import type {ReactNode} from 'react';+import {LayerContentBoundary} from '../Layer/layerScopedContext';+import {Text} from '../Text/Text';import {Link} from './Link';import {LinkProvider} from './LinkProvider';@@ -485,6 +488,183 @@ describe('pressed state', () => {});});+// =============================================================================+// Display: inside a clamped Text the anchor joins the text's line boxes, so+// the clamp can truncate it. Everywhere else it keeps its inline-flex box.+// Link never reads its children to decide (Link AV1).+// =============================================================================++/**+ * Extracts class-name tokens from a CSS selector (e.g. the selectorText of+ * a CSSStyleRule), so callers can match against an element's classList by+ * exact token rather than by substring. Handles compound selectors+ * (`.a.b:hover`) and comma-separated selector lists (`.a, .b`).+ */+function classTokensFromSelector(selectorText: string): string[] {+ const tokens: string[] = [];+ const classRegex = /\.([-_a-zA-Z0-9]+)/g;+ let match: RegExpExecArray | null;+ while ((match = classRegex.exec(selectorText)) !== null) {+ tokens.push(match[1]);+ }+ return tokens;+}++/**+ * Recursively collects every CSSStyleRule from a rule list, descending into+ * grouping rules (e.g. `@media`) so declarations nested in a condition are+ * not missed.+ */+function collectStyleRules(rules: CSSRuleList, out: CSSStyleRule[]): void {+ for (const rule of Array.from(rules)) {+ if (rule instanceof CSSStyleRule) {+ out.push(rule);+ } else if ('cssRules' in rule && rule.cssRules) {+ collectStyleRules((rule as CSSGroupingRule).cssRules, out);+ }+ }+}++/**+ * Returns the `display` value of every injected CSS rule that targets `el`,+ * matched via the CSSOM (real selector tokens + real class list) rather than+ * substring checks on raw selector/body text — a hashed atomic class like+ * `x1a` can be a substring of an unrelated class like `x1a2b3c4`, so+ * string-based matching can both false-positive and false-negative.+ */+function displayDeclarationsFor(el: Element): string[] {+ const classes = new Set(Array.from(el.classList));+ const styleRules: CSSStyleRule[] = [];+ for (const sheet of Array.from(document.styleSheets)) {+ let rules: CSSRuleList;+ try {+ rules = sheet.cssRules;+ } catch {+ continue;+ }+ collectStyleRules(rules, styleRules);+ }++ const declarations: string[] = [];+ for (const rule of styleRules) {+ const matchesElement = classTokensFromSelector(rule.selectorText).some(+ token => classes.has(token),+ );+ if (!matchesElement) {+ continue;+ }+ const display = rule.style.getPropertyValue('display');+ if (display) {+ declarations.push(display.trim());+ }+ }+ return declarations;+}++describe('Link display', () => {+ const inClamp = (link: ReactNode) => (+ <Text maxLines={2} hasTruncateTooltip={false}>+ Lead text {link} tail text+ </Text>+ );++ it('keeps its inline-flex box outside a clamped Text', () => {+ const {container} = render(<Link href="/docs">Documentation</Link>);+ expect(displayDeclarationsFor(container.querySelector('a')!)).toContain(+ 'inline-flex',+ );+ });++ it('keeps its inline-flex box inside a Text that does not clamp', () => {+ const {container} = render(+ <Text>+ <Link href="/docs">Documentation</Link>+ </Text>,+ );+ expect(displayDeclarationsFor(container.querySelector('a')!)).toContain(+ 'inline-flex',+ );+ });++ it('is inline inside a clamped Text, so the clamp can truncate it', () => {+ const {container} = render(+ inClamp(<Link href="/docs">Documentation</Link>),+ );+ const anchor = container.querySelector('a')!;+ expect(displayDeclarationsFor(anchor)).toContain('inline');+ });++ it('decides from the clamp, not the children: composed content is inline too', () => {+ const {container} = render(+ inClamp(+ <Link href="/docs">+ <strong>Docs</strong> home+ </Link>,+ ),+ );+ expect(displayDeclarationsFor(container.querySelector('a')!)).toContain(+ 'inline',+ );+ });++ it('is inline inside a clamped Text for the external-link form', () => {+ const {container} = render(+ inClamp(+ <Link href="https://example.com" isExternalLink>+ External docs+ </Link>,+ ),+ );+ expect(displayDeclarationsFor(container.querySelector('a')!)).toContain(+ 'inline',+ );+ });++ it('keeps its own box inside a clamped Text when it sets display or maxLines', () => {+ const {container} = render(+ inClamp(+ <>+ <Link href="/block" display="block">+ Block+ </Link>+ <Link href="/self" maxLines={1}>+ Self clamped+ </Link>+ </>,+ ),+ );+ for (const anchor of Array.from(container.querySelectorAll('a'))) {+ expect(displayDeclarationsFor(anchor)).not.toContain('inline');+ }+ });++ it('keeps the button form as an inline-flex box inside a clamped Text', () => {+ const {container} = render(+ inClamp(+ <Link onClick={() => {}} role="button">+ Action+ </Link>,+ ),+ );+ expect(+ displayDeclarationsFor(container.querySelector('button')!),+ ).not.toContain('inline');+ });++ it('keeps its own box in a layer opened inside a clamped Text', () => {+ const {container} = render(+ inClamp(+ <LayerContentBoundary>+ <Link href="/docs">In a layer</Link>+ </LayerContentBoundary>,+ ),+ );+ expect(displayDeclarationsFor(container.querySelector('a')!)).not.toContain(+ 'inline',+ );+ });+});+describe('Link label color', () => {it('lets the label inherit the root color, so a theme styles Link through the link target', () => {for (const color of ['accent', 'primary', 'secondary'] as const) {diff --git a/packages/core/src/Link/Link.tsx b/packages/core/src/Link/Link.tsxindex 84da814978..50bb55cd55 100644--- a/packages/core/src/Link/Link.tsx+++ b/packages/core/src/Link/Link.tsx@@ -16,7 +16,7 @@* - /packages/cli/assets/templates/blocks/components/Link/ (showcase blocks)*/-import type {ReactNode} from 'react';+import {use, type ReactNode} from 'react';import type {BaseProps} from '../BaseProps';import * as stylex from '@stylexjs/stylex';@@ -24,12 +24,14 @@ import {colorVars,durationVars,easeVars,+ focusVars,spacingVars,typeScaleVars,} from '../theme/tokens.stylex';import {Icon} from '../Icon';import {Tooltip} from '../Tooltip';import {Text} from '../Text';+import {TextClampContext} from '../Text/textClampContext';import {VisuallyHidden} from '../VisuallyHidden';import type {TextType,@@ -104,6 +106,18 @@ const styles = stylex.create({pointerEvents: 'auto',position: 'relative',},+ // Inside a clamped Text the root joins the text's line boxes, so the+ // clamp can cut through the link. An inline-flex box is atomic: a clamp+ // cannot truncate it. The clamp also clips at the line edges, so the ring+ // sits inside each line box.+ inClampedText: {+ display: 'inline',+ outlineOffset: `calc(-1 * ${focusVars['--focus-outline-width']})`,+ },+ externalIconInClampedText: {+ marginInlineStart: spacingVars['--spacing-0-5'],+ verticalAlign: 'middle',+ },hasUnderline: {textDecoration: 'underline',},@@ -343,6 +357,11 @@ export function Link({// render as a <button> with link styling for semantic correctness.const renderAsButton =role === 'button' || (role === 'inert' && href == null);+ const isExternalWithIcon = isExternalLink && !renderAsButton;+ // Link reads the enclosing Text's clamp, never its own children (AV1). A+ // Link with its own display or clamp keeps its own box.+ const isInClampedText =+ use(TextClampContext) && display === 'inline' && maxLines === 0;// The reflected theme attributes win over a caller's same-named `data-*`, so// theme targeting always sees the real value (public-component-api INV5).@@ -363,9 +382,14 @@ export function Link({maxLines={maxLines}>{children}</Text>- {isExternalLink && !renderAsButton && (+ {isExternalWithIcon && (<>- <Icon icon="externalLink" size="xsm" color="inherit" />+ <Icon+ icon="externalLink"+ size="xsm"+ color="inherit"+ xstyle={isInClampedText && styles.externalIconInClampedText}+ /><VisuallyHidden>{newTabLabel}</VisuallyHidden></>)}@@ -426,6 +450,7 @@ export function Link({themeProps('link', {color}),focusOutlineProps.focusVisible(styles.base,+ isInClampedText && styles.inClampedText,linkColorStyles[color],hasUnderline && styles.hasUnderline,isStandalone && styles.standalone,@@ -458,6 +483,7 @@ export function Link({themeProps('link', {color}),focusOutlineProps.focusVisible(styles.base,+ isInClampedText && styles.inClampedText,linkColorStyles[color],!isDisabled && interactionOverlayStyles.pressedBackgroundColor,hasUnderline && styles.hasUnderline,diff --git a/packages/core/src/Link/__tests__/Link.ancestor-clamp.a11y.chromium.spec.ts b/packages/core/src/Link/__tests__/Link.ancestor-clamp.a11y.chromium.spec.tsnew file mode 100644index 0000000000..de6c49b687--- /dev/null+++ b/packages/core/src/Link/__tests__/Link.ancestor-clamp.a11y.chromium.spec.ts@@ -0,0 +1,168 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope ^(packages/core/src/Link/|packages/core/src/Text/|apps/storybook/stories/Link\.stories)++/**+ * Real-browser evidence for the ancestor clamp split: a text-only Link inside+ * `<Text maxLines={2}>` participates in the clamped lines, a Link inside a+ * one- or two-line clamp shows the top and bottom edges of its keyboard focus+ * ring inside the clamp, and a composed Link keeps its inline-flex root and paints a keyboard+ * focus outline.+ */++import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => storybook?.close());++test('a text-only Link clamps inside an ancestor Text maxLines={2}', async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-link--clamped-by-ancestor-text&viewMode=story`,+ );+ const paragraph = page.getByTestId('ancestor-clamp-text');+ await expect(paragraph).toBeVisible();+ const measured = await paragraph.evaluate(el => {+ const root = el as HTMLElement;+ const anchor = root.querySelector('a') as HTMLElement | null;+ if (!anchor) {+ return null;+ }+ const anchorBox = anchor.getBoundingClientRect();+ const rootBox = root.getBoundingClientRect();+ const rootStyle = getComputedStyle(root) as CSSStyleDeclaration & {+ webkitLineClamp?: string;+ };+ return {+ display: getComputedStyle(anchor).display,+ clamp: rootStyle.webkitLineClamp,+ overflowed: root.scrollHeight > root.clientHeight + 1,+ // The clamp cuts the link mid text: the anchor starts inside the two+ // visible lines and its box extends past the visible bottom edge.+ anchorTopInside:+ anchorBox.top >= rootBox.top - 1 && anchorBox.top <= rootBox.bottom - 1,+ anchorBottomPastClamp: anchorBox.bottom > rootBox.bottom + 1,+ };+ });+ expect(measured).not.toBeNull();+ // The anchor flows inside the clamped lines rather than forming its own box.+ expect(measured?.display).toBe('inline');+ // The ancestor clamps to two lines, and the link's own text runs past them+ // so the clamp cuts the link itself, not just the paragraph after it.+ expect(measured?.clamp).toBe('2');+ expect(measured?.overflowed).toBe(true);+ expect(measured?.anchorTopInside).toBe(true);+ expect(measured?.anchorBottomPastClamp).toBe(true);+});++/** The painted color at one viewport point, read from a real screenshot. */+async function pixel(page: Page, x: number, y: number) {+ const shot = await page.screenshot({clip: {x, y, width: 1, height: 1}});+ return page.evaluate(async base64 => {+ const blob = await (await fetch(`data:image/png;base64,${base64}`)).blob();+ const bitmap = await createImageBitmap(blob);+ const canvas = new OffscreenCanvas(1, 1);+ const context = canvas.getContext(+ '2d',+ ) as OffscreenCanvasRenderingContext2D;+ context.drawImage(bitmap, 0, 0);+ const [r, g, b] = context.getImageData(0, 0, 1, 1).data;+ return [r, g, b] as const;+ }, shot.toString('base64'));+}++for (const [testId, tabs] of [+ ['ancestor-clamp-text', 1],+ ['ancestor-clamp-one-line', 2],+] as const) {+ test(`${testId}: a Link inside the clamp shows the top and bottom edges of its keyboard focus ring`, async ({+ page,+ }) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-link--clamped-by-ancestor-text&viewMode=story`,+ );+ const link = page.getByTestId(testId).locator('a');+ await expect(link).toBeVisible();+ for (let i = 0; i < tabs; i++) {+ await page.keyboard.press('Tab');+ }+ await expect(link).toBeFocused();+ const ring = await link.evaluate(el => {+ const style = getComputedStyle(el);+ const probe = document.createElement('span');+ probe.style.color = style.outlineColor;+ document.body.append(probe);+ const color = (getComputedStyle(probe).color.match(/[\d.]+/g) ?? [])+ .slice(0, 3)+ .map(Number);+ probe.remove();+ const line = el.getClientRects()[0];+ return {+ style: style.outlineStyle,+ color,+ line: {+ x: line.left + line.width / 2,+ top: line.top,+ bottom: line.bottom,+ },+ };+ });+ expect(ring.style).not.toBe('none');+ // The top and the bottom edge of the link's first line box show the ring:+ // the clamp clips at its line edges, so an outside ring loses them.+ for (const [edge, y] of [+ ['top', ring.line.top + 1],+ ['bottom', ring.line.bottom - 1.5],+ ] as const) {+ const painted = await pixel(page, Math.floor(ring.line.x), Math.floor(y));+ const distance = Math.hypot(+ painted[0] - ring.color[0],+ painted[1] - ring.color[1],+ painted[2] - ring.color[2],+ );+ expect(distance, `${edge} edge`).toBeLessThan(40);+ }+ });+}++test('a composed Link keeps its box and paints a keyboard focus outline', async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-link--clamped-by-ancestor-text&viewMode=story`,+ );+ const link = page.getByTestId('composed-link');+ await expect(link).toBeVisible();+ // The two clamped links come first in tab order; the composed link is the+ // next stop, so keyboard focus reaches it visibly.+ await page.keyboard.press('Tab');+ await page.keyboard.press('Tab');+ await page.keyboard.press('Tab');+ await expect(link).toBeFocused();++ const measured = await link.evaluate(el => {+ const style = getComputedStyle(el);+ const box = el.getBoundingClientRect();+ return {+ display: style.display,+ outlineStyle: style.outlineStyle,+ outlineWidth: style.outlineWidth,+ height: box.height,+ };+ });+ expect(measured.display).toBe('inline-flex');+ expect(measured.outlineStyle).not.toBe('none');+ expect(parseFloat(measured.outlineWidth)).toBeGreaterThan(0);+});diff --git a/packages/core/src/Text/Text.test.tsx b/packages/core/src/Text/Text.test.tsxindex b6bf6f5a9b..ae3365aea7 100644--- a/packages/core/src/Text/Text.test.tsx+++ b/packages/core/src/Text/Text.test.tsx@@ -436,3 +436,37 @@ describe('Text maxLines without a truncation tooltip', () => {expect(reads).toBeGreaterThan(0);});});++describe('Text keeps its children mounted when maxLines changes', () => {+ it('keeps the same child elements, focus, and input values across a clamp toggle', () => {+ const {rerender} = render(+ <Text maxLines={2} hasTruncateTooltip={false}>+ Lead text <input aria-label="Note" defaultValue="" />+ </Text>,+ );+ const input = screen.getByRole<HTMLInputElement>('textbox', {+ name: 'Note',+ });+ input.value = 'typed';+ input.focus();++ rerender(+ <Text maxLines={0} hasTruncateTooltip={false}>+ Lead text <input aria-label="Note" defaultValue="" />+ </Text>,+ );+ const after = screen.getByRole<HTMLInputElement>('textbox', {+ name: 'Note',+ });+ expect(after).toBe(input);+ expect(after.value).toBe('typed');+ expect(document.activeElement).toBe(after);++ rerender(+ <Text maxLines={2} hasTruncateTooltip={false}>+ Lead text <input aria-label="Note" defaultValue="" />+ </Text>,+ );+ expect(screen.getByRole('textbox', {name: 'Note'})).toBe(input);+ });+});diff --git a/packages/core/src/Text/Text.tsx b/packages/core/src/Text/Text.tsxindex 9a20d0cb16..7c4b08f143 100644--- a/packages/core/src/Text/Text.tsx+++ b/packages/core/src/Text/Text.tsx@@ -16,7 +16,7 @@* - /packages/cli/assets/templates/blocks/components/Text/ (showcase blocks)*/-import {lazy, Suspense, useRef, type ReactNode} from 'react';+import {lazy, Suspense, use, useRef, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import type {TextType,@@ -52,6 +52,7 @@ import {mergeProps} from '../utils/mergeProps';import {useMergedRefs} from '../hooks/useMergedRefs';import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';+import {TextClampContext} from './textClampContext';const LazyXDSTooltip = lazy(async () =>import('../Tooltip/Tooltip').then(mod => ({default: mod.Tooltip})),@@ -278,6 +279,9 @@ export function Text({// Keep the merged ref stable across rerenders.const mergedRef = useMergedRefs(ref, truncation.ref, textRef);+ const isInClampedText = use(TextClampContext);+ // A capsize block removes a multi-line clamp.+ const isClamped = maxLines === 1 || (maxLines > 1 && !hasCapsize);// Build inline style for -webkit-line-clamp (dynamic value)const inlineStyle = maxLines > 1 ? {WebkitLineClamp: maxLines} : undefined;@@ -318,7 +322,10 @@ export function Text({{...style, ...inlineStyle},)}{...props}>- {children}+ {/* Always mounted, so a change of maxLines keeps every child mounted. */}+ <TextClampContext value={isClamped || isInClampedText}>+ {children}+ </TextClampContext></Component>{tooltipEnabled && (<Suspense fallback={null}>diff --git a/packages/core/src/Text/textClampContext.ts b/packages/core/src/Text/textClampContext.tsnew file mode 100644index 0000000000..9b4522a324--- /dev/null+++ b/packages/core/src/Text/textClampContext.ts@@ -0,0 +1,17 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file textClampContext.ts+ * @input Uses createLayerScopedContext+ * @output TextClampContext: true inside a Text that clamps its lines+ * @position Internal; Text provides it and Link reads it+ *+ * A layer boundary resets it to false, because content in a layer is not+ * inside the clamped text box.+ */++import {createLayerScopedContext} from '../Layer/layerScopedContext';++export const TextClampContext = createLayerScopedContext(false);