An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): add LineClamp — clamp arbitrary content to N lines (#4259)
Ojas Mutreja611382ee1fb1
diff --git a/.changeset/line-clamp-core-internal.md b/.changeset/line-clamp-core-internal.mdnew file mode 100644index 0000000000..943d942890--- /dev/null+++ b/.changeset/line-clamp-core-internal.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: the undocumented `@astryxdesign/core/internal/line-clamp` entry gives Lab's `LineClamp` Core's focusable selector, the shared mutation observer and its flush, and the shared truncation tooltip. The shared mutation observer now passes each registration the records that reached it, and existing callers ignore them, so their behaviour is unchanged. Internal entries are outside the public API and its compatibility promise.++@HelloOjasMutreja+@cixzhangdiff --git a/.changeset/line-clamp-official-packages.md b/.changeset/line-clamp-official-packages.mdnew file mode 100644index 0000000000..3cbc08c580--- /dev/null+++ b/.changeset/line-clamp-official-packages.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[feat] The official-packages discovery list now includes the Lab `LineClamp` component, so `astryx` can find and describe it.++@HelloOjasMutrejadiff --git a/apps/storybook/stories/LineClamp.stories.tsx b/apps/storybook/stories/LineClamp.stories.tsxnew file mode 100644index 0000000000..94b11ff382--- /dev/null+++ b/apps/storybook/stories/LineClamp.stories.tsx@@ -0,0 +1,106 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {LineClamp} from '@astryxdesign/lab/LineClamp';++const LONG_TEXT =+ 'Astryx is an open source design system that grew inside Meta over the last eight years, where it became the most-used and largest design system in the company — powering thousands of apps and shaped by the engineers, designers, and product teams who depend on it every day.';++const meta: Meta<typeof LineClamp> = {+ title: 'Lab/LineClamp',+ component: LineClamp,+ tags: ['autodocs'],+ argTypes: {+ maxLines: {+ control: {type: 'number', min: 1, max: 6, step: 1},+ description: 'Maximum number of lines before clamping',+ },+ hasTruncateTooltip: {+ control: 'boolean',+ description: 'Show full content in a tooltip when clamped',+ },+ truncateTooltipPlacement: {+ control: 'select',+ options: ['above', 'below', 'start', 'end'],+ description: 'Where the truncation tooltip opens',+ },+ as: {+ control: 'select',+ options: ['div', 'span', 'p'],+ description: 'HTML element to render',+ },+ },+ decorators: [+ Story => (+ <div style={{maxWidth: 320}}>+ <Story />+ </div>+ ),+ ],+};++export default meta;+type Story = StoryObj<typeof meta>;++export const Default: Story = {+ args: {+ maxLines: 3,+ children: LONG_TEXT,+ },+};++export const TwoLines: Story = {+ args: {+ maxLines: 2,+ children: LONG_TEXT,+ },+};++export const SingleLine: Story = {+ args: {+ maxLines: 1,+ children: LONG_TEXT,+ },+};++export const WithoutTooltip: Story = {+ args: {+ maxLines: 2,+ hasTruncateTooltip: false,+ children: LONG_TEXT,+ },+};++export const MixedContent: Story = {+ args: {+ maxLines: 2,+ children: (+ <>+ This card description mixes <strong>bold</strong>, <em>italic</em>, and+ plain text. LineClamp clamps all of it as one block and adds no+ typography of its own.+ </>+ ),+ },+};++export const ShortContentNotClamped: Story = {+ args: {+ maxLines: 3,+ children: 'This content is short enough that it never clamps.',+ },+};++export const WithClippedLink: Story = {+ args: {+ maxLines: 2,+ children: (+ <>+ {LONG_TEXT}{' '}+ <a href="https://example.com" data-testid="trailing-link">+ Read the full story+ </a>+ </>+ ),+ },+};diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex f76fbf320a..7fea2c9e01 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -612,6 +612,11 @@"path": "components/lab/emoji-picker","aliases": []},+ {+ "name": "component-lab-line-clamp",+ "path": "components/lab/line-clamp",+ "aliases": []+ },{"name": "component-lab-list-input","path": "components/lab/list-input",diff --git a/packages/cli/assets/discover/official-packages.json b/packages/cli/assets/discover/official-packages.jsonindex 3b5d5fe07e..7344878198 100644--- a/packages/cli/assets/discover/official-packages.json+++ b/packages/cli/assets/discover/official-packages.json@@ -136,6 +136,10 @@"kind": "component","name": "EmojiPicker"},+ {+ "kind": "component",+ "name": "LineClamp"+ },{"kind": "component","name": "ListInput"diff --git a/packages/core/package.json b/packages/core/package.jsonindex 59ef0a140c..01bac0aa56 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -868,6 +868,11 @@"source": "./src/internal/scroll-anchoring.ts","types": "./dist/internal/scroll-anchoring.d.ts","default": "./dist/internal/scroll-anchoring.js"+ },+ "./internal/line-clamp": {+ "source": "./src/internal/line-clamp.ts",+ "types": "./dist/internal/line-clamp.d.ts",+ "default": "./dist/internal/line-clamp.js"}},"files": [diff --git a/packages/core/src/Text/TruncationTooltip.tsx b/packages/core/src/Text/TruncationTooltip.tsxindex 023b3d7b0a..66e5a451df 100644--- a/packages/core/src/Text/TruncationTooltip.tsx+++ b/packages/core/src/Text/TruncationTooltip.tsx@@ -8,7 +8,8 @@* @output Exports `useTruncationTooltipInterest`, which loads the Tooltip* module once text is truncated and tracks the first hover, tap or focus on* it, and `TruncationTooltip`, the Tooltip that mounts on that interaction- * @position Shared by Text and Heading. Until the first interaction a page of+ * @position Shared by Text, Heading and Lab's LineClamp (through Core's internal+ * line-clamp entry). Until the first interaction a page of* truncated text mounts no tooltip layers, and the tooltip that then mounts* answers that interaction as it would once mounted.*/diff --git a/packages/core/src/internal/line-clamp.ts b/packages/core/src/internal/line-clamp.tsnew file mode 100644index 0000000000..f2c060d7ae--- /dev/null+++ b/packages/core/src/internal/line-clamp.ts@@ -0,0 +1,24 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file line-clamp.ts+ * @input Core's canonical focusable selector and the shared mutation observer+ * @output `@astryxdesign/core/internal/line-clamp`: FOCUSABLE_SELECTOR,+ * observeMutations, flushMutations, TruncationTooltip and+ * useTruncationTooltipInterest, re-exported by name for Lab's LineClamp+ * @position An internal entry reserved for Astryx's own packages:+ * undocumented, outside the public API and its compatibility promise,+ * versioned in lockstep with Core, and allowed only in Core and Lab by the+ * `@astryx/no-core-internal-import` lint rule. Core components import the+ * same modules by relative path. Named re-exports only.+ *+ * SYNC: When modified, update scripts/sync-exports.js.+ */+export {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector';+export {+ flushMutations,+ observeMutations,+} from '../utils/sharedMutationObserver';+export {+ TruncationTooltip,+ useTruncationTooltipInterest,+} from '../Text/TruncationTooltip';diff --git a/packages/core/src/utils/sharedMutationObserver.test.ts b/packages/core/src/utils/sharedMutationObserver.test.tsindex 4a070fd548..8fa0b825ed 100644--- a/packages/core/src/utils/sharedMutationObserver.test.ts+++ b/packages/core/src/utils/sharedMutationObserver.test.ts@@ -56,6 +56,67 @@ describe('observeContent', () => {});});+describe('observeMutations records', () => {+ it('hands a registration the records that reached its element', async () => {+ const element = document.createElement('div');+ const child = document.createElement('span');+ element.append(child);+ const callback = vi.fn();+ const unsubscribe = observeMutations(+ element,+ {+ attributes: true,+ attributeFilter: ['inert'],+ attributeOldValue: true,+ subtree: true,+ },+ callback,+ );++ child.setAttribute('inert', '');+ child.setAttribute('inert', '');+ await flush();++ expect(callback).toHaveBeenCalledTimes(1);+ const records = callback.mock.calls[0][0] as MutationRecord[];+ expect(records.map(record => record.oldValue)).toEqual([null, '']);+ expect(records.every(record => record.target === child)).toBe(true);+ unsubscribe();+ });++ it('keeps a registration that asks for old values apart from one that does not', async () => {+ const element = document.createElement('div');+ const withOld = vi.fn();+ const withoutOld = vi.fn();+ const unsubscribeWith = observeMutations(+ element,+ {attributes: true, attributeOldValue: true},+ withOld,+ );+ const other = document.createElement('div');+ const unsubscribeWithout = observeMutations(+ other,+ {attributes: true},+ withoutOld,+ );++ element.setAttribute('dir', 'rtl');+ element.setAttribute('dir', 'ltr');+ other.setAttribute('dir', 'rtl');+ other.setAttribute('dir', 'ltr');+ await flush();++ expect(+ (withOld.mock.calls[0][0] as MutationRecord[]).map(r => r.oldValue),+ ).toEqual([null, 'rtl']);+ expect(+ (withoutOld.mock.calls[0][0] as MutationRecord[]).map(r => r.oldValue),+ ).toEqual([null, null]);+ unsubscribeWith();+ unsubscribeWithout();+ });+});+describe('observeMutations', () => {it('shares one observer across registrations with the same options', async () => {const Native = globalThis.MutationObserver;diff --git a/packages/core/src/utils/sharedMutationObserver.ts b/packages/core/src/utils/sharedMutationObserver.tsindex 2ec6f51505..1dbe9809e4 100644--- a/packages/core/src/utils/sharedMutationObserver.ts+++ b/packages/core/src/utils/sharedMutationObserver.ts@@ -14,7 +14,12 @@* repeated cell, row or region does not create one observer per instance.*/-type MutationCallback = () => void;+/**+ * Called once per batch with the records that reached the registration: those+ * whose target is its element or, with `subtree`, one of its descendants.+ * A caller that needs only to know that something changed ignores them.+ */+type MutationCallback = (records: ReadonlyArray<MutationRecord>) => void;const CONTENT_OPTIONS: MutationObserverInit = {characterData: true,@@ -41,6 +46,7 @@ function optionsKey(options: MutationObserverInit): string {options.attributeFilter == null? null: [...options.attributeFilter].sort(),+ options.attributeOldValue === true,options.characterData === true,options.childList === true,options.subtree === true,@@ -54,23 +60,30 @@ function createSharedObserver(options: MutationObserverInit): SharedObserver {// One call per callback per batch, however many records it received.// With `subtree`, a record's target can be any descendant, so walk up to// the observed roots; without it, the target is the observed node.- const pending = new Set<MutationCallback>();+ const pending = new Map<MutationCallback, MutationRecord[]>();for (const record of records) {+ const due = new Set<MutationCallback>();if (!isSubtree) {- callbacks- .get(record.target)- ?.forEach(callback => pending.add(callback));- continue;- }- for (- let node: Node | null = record.target;- node;- node = node.parentNode- ) {- callbacks.get(node)?.forEach(callback => pending.add(callback));+ callbacks.get(record.target)?.forEach(callback => due.add(callback));+ } else {+ for (+ let node: Node | null = record.target;+ node;+ node = node.parentNode+ ) {+ callbacks.get(node)?.forEach(callback => due.add(callback));+ }}+ due.forEach(callback => {+ const received = pending.get(callback);+ if (received) {+ received.push(record);+ } else {+ pending.set(callback, [record]);+ }+ });}- pending.forEach(callback => callback());+ pending.forEach((received, callback) => callback(received));};return {observer: new MutationObserver(deliver), callbacks, deliver};}diff --git a/packages/lab/src/LineClamp/LineClamp.doc.mjs b/packages/lab/src/LineClamp/LineClamp.doc.mjsnew file mode 100644index 0000000000..07bbfb319e--- /dev/null+++ b/packages/lab/src/LineClamp/LineClamp.doc.mjs@@ -0,0 +1,185 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */++export const docs = {+ name: 'LineClamp',+ displayName: 'Line Clamp',+ category: 'Layout',+ keywords: [+ 'clamp',+ 'truncate',+ 'ellipsis',+ 'overflow',+ 'lines',+ 'multiline',+ 'text',+ ],+ props: [+ {+ name: 'children',+ type: 'ReactNode',+ description:+ 'Content to clamp: mixed inline content, nested elements, anything you would rather not wrap in a single Text.',+ required: true,+ },+ {+ name: 'maxLines',+ type: 'number',+ description:+ 'Maximum number of lines to show before clamping with an ellipsis.',+ required: true,+ },+ {+ name: 'hasTruncateTooltip',+ type: 'boolean',+ description:+ "Show a tooltip with the full text content on hover or keyboard focus when clamped. A clamped root is focusable (tabindex 0) so keyboard users can reach the tooltip; a tabIndex you pass wins. The tooltip props follow Text's: when Text's hasTruncateTooltip is renamed in a minor, LineClamp follows.",+ default: 'true',+ },+ {+ name: 'truncateTooltipPlacement',+ type: "'above' | 'below' | 'start' | 'end'",+ description: 'Where the truncation tooltip opens.',+ default: "'above'",+ },+ {+ name: 'as',+ type: "'div' | 'span' | 'p'",+ description: 'HTML element to render.',+ default: "'div'",+ },+ ],+ usage: {+ description:+ "Clamps arbitrary content to a fixed number of lines with an ellipsis. Text's maxLines clamps a Text element; LineClamp clamps whatever it wraps and adds no typography of its own, so it suits mixed inline content and nested elements without changing their font, color or wrapping. Truncation detection reuses useTruncation (the same hook Text uses), so overflow is measured correctly even while -webkit-line-clamp clips scrollHeight.",+ bestPractices: [+ {+ guidance: true,+ description:+ 'Use LineClamp when clamping a block of mixed or composed content (not a single Text node).',+ },+ {+ guidance: true,+ description:+ "Use Text's own maxLines prop when clamping a single Text node — no need to wrap it in LineClamp.",+ },+ {+ guidance: true,+ description:+ 'Disable the tooltip (hasTruncateTooltip={false}) when the clamped content is already reachable elsewhere on the page, to avoid a redundant announcement.',+ },+ {+ guidance: true,+ description:+ "LineClamp makes a focusable descendant inert only when both hold: (1) it is in the clamp's own flow. A positioned element is in that flow when its containing block is an element inside the clamp that is itself in the flow, as a control's own positioned wrapper is; the line test then applies to that containing block's box. A fixed element, an absolute element whose containing block is the clamp itself or lies outside it, a top-layer element (a popover or dialog), and anything rendered elsewhere through a portal each start a subtree that is never made inert, at any depth. (2) its box lies wholly beyond the clamp's last visible line. A control any part of which is visible stays reachable. A focusable with no box when LineClamp checks is treated as beyond the last line until it gains a box; LineClamp re-checks then. LineClamp re-checks when its size, its content or its fonts change. Gap: an absolutely placed control that the clamp itself clips stays a tab stop; the author owns positioned content inside a clamp. Inert takes such a control out of the Tab order and the accessibility tree. LineClamp never rewrites your own tabIndex or aria-hidden, and the element that holds focus is never made inert.",+ },+ ],+ },+};++/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */+export const docsZh = {+ name: 'LineClamp',+ displayName: 'Line Clamp',+ props: [+ {+ name: 'children',+ type: 'ReactNode',+ description:+ '要截断的内容。LineClamp 包裹任意子节点(混合内联内容、嵌套元素)并截断整个区块,而不是单个 Text 组件。',+ required: true,+ },+ {+ name: 'maxLines',+ type: 'number',+ description: '截断前显示的最大行数。',+ required: true,+ },+ {+ name: 'hasTruncateTooltip',+ type: 'boolean',+ description:+ '截断时在悬停或键盘聚焦时显示完整文本的工具提示;被截断的根元素可聚焦(tabindex 0),你传入的 tabIndex 优先。工具提示相关属性与 Text 保持一致:Text 的 hasTruncateTooltip 在次版本中改名时,LineClamp 随之改名。',+ default: 'true',+ },+ {+ name: 'truncateTooltipPlacement',+ type: "'above' | 'below' | 'start' | 'end'",+ description: '截断工具提示的打开位置。',+ default: "'above'",+ },+ {+ name: 'as',+ type: "'div' | 'span' | 'p'",+ description: '要渲染的 HTML 元素。',+ default: "'div'",+ },+ ],+ usage: {+ description:+ '将任意内容截断为固定行数并显示省略号。Text 的 maxLines 截断 Text 组件自身的内容;LineClamp 是可组合版本 —— 用它包裹任意子节点(混合内联内容、嵌套元素)即可将整个区块截断为 N 行。',+ bestPractices: [+ {+ guidance: true,+ description:+ '当需要截断混合或组合内容(而非单个 Text 节点)时使用 LineClamp。',+ },+ {+ guidance: true,+ description:+ '截断单个 Text 节点时使用 Text 自身的 maxLines 属性,无需用 LineClamp 包裹。',+ },+ {+ guidance: true,+ description:+ '当截断内容已在页面其他位置可访问时,禁用工具提示(hasTruncateTooltip={false})以避免重复播报。',+ },+ {+ guidance: true,+ description:+ '只有同时满足以下两点时,LineClamp 才会把可聚焦的后代设为 inert:(1) 它在截断容器自己的文档流中。若定位元素的包含块是容器内同样处于文档流中的元素(例如控件自己的定位包装元素),该定位元素也算在文档流中,此时按该包含块的盒子判断是否越过最后一行。fixed 元素、包含块是容器本身或位于容器之外的 absolute 元素、顶层元素(popover 或 dialog),以及通过 portal 渲染到别处的内容,各自开启一个无论多深都不会被设为 inert 的子树。(2) 它的盒子完全位于最后一个可见行之外。只要有一部分可见,控件就保持可达。检查时没有盒子的可聚焦元素会被视为位于最后一行之外,直到它获得盒子;届时 LineClamp 会重新检查。LineClamp 会在尺寸、内容或字体变化时重新检查。已知缺口:被容器本身截断的绝对定位控件仍是一个 Tab 停靠点;容器内的定位内容由作者负责。LineClamp 不会改写你自己设置的 tabIndex 或 aria-hidden,持有焦点的元素也不会被设为 inert。',+ },+ ],+ },+};++/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */+export const docsDense = {+ description:+ 'Clamps arbitrary content to N lines with an ellipsis; composable version of Text maxLines.',+ usage: {+ description:+ 'Wrap any children (mixed inline content, nested elements) to clamp the whole block to N lines. Reuses useTruncation for overflow detection.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Use for clamping a block of mixed/composed content, not a single Text node.',+ },+ {+ guidance: true,+ description: "Use Text's own maxLines for a single Text node instead.",+ },+ {+ guidance: true,+ description:+ 'Disable tooltip when content is reachable elsewhere, to avoid redundant announcement.',+ },+ {+ guidance: true,+ description:+ "Inert only for a focusable in the clamp's own flow whose box lies wholly past the last visible line (a positioned element placed against an in-flow containing block in the clamp, like a control's own wrapper, is in the flow and judged by that block's box); never inside a fixed, escaping absolute, top-layer or portaled subtree; a partly visible control stays reachable; a focusable with no box counts as past the last line until it gains a box; re-checked on size, content and font changes. Gap: an absolutely placed control the clamp clips stays a tab stop. Never the focused element, never your own tabIndex or aria-hidden.",+ },+ ],+ },+ propDescriptions: {+ children:+ 'Content to clamp. Composable version of maxLines — wraps arbitrary children.',+ maxLines: 'Max lines before clamping with ellipsis.',+ hasTruncateTooltip:+ "Tooltip with full text on hover or focus when clamped. Clamped root is focusable. Follows Text's prop name.",+ truncateTooltipPlacement: "Tooltip placement. Default 'above'.",+ as: "HTML element to render. Default 'div'.",+ },+};diff --git a/packages/lab/src/LineClamp/LineClamp.test.tsx b/packages/lab/src/LineClamp/LineClamp.test.tsxnew file mode 100644index 0000000000..f318b8d2f4--- /dev/null+++ b/packages/lab/src/LineClamp/LineClamp.test.tsx@@ -0,0 +1,1287 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file LineClamp.test.tsx+ * @input Uses vitest, @testing-library/react, LineClamp component+ * @output Unit tests for LineClamp component behavior+ * @position Testing; validates LineClamp.tsx implementation+ *+ * SYNC: When LineClamp.tsx changes, update tests to match new behavior+ */++import {describe, it, expect, vi, afterEach} from 'vitest';+import {useState} from 'react';+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@testing-library/react';+import {CheckboxInput} from '@astryxdesign/core/CheckboxInput';+import {Switch} from '@astryxdesign/core/Switch';+import {LineClamp} from './LineClamp';++// jsdom has no layout engine, so content never actually overflows and+// isTruncated stays false, the same constraint core's Text.test.tsx works+// under for the same useTruncation hook. These tests cover the+// non-truncated (default) rendering path; the tooltip-on-truncation path is+// exercised manually in Storybook.+describe('LineClamp', () => {+ it('renders children', () => {+ render(<LineClamp maxLines={2}>Some clamped content</LineClamp>);+ expect(screen.getByText('Some clamped content')).toBeInTheDocument();+ });++ it('renders arbitrary mixed children, not just plain text', () => {+ render(+ <LineClamp maxLines={2}>+ Some <strong>mixed</strong> inline content+ </LineClamp>,+ );+ expect(screen.getByText('mixed')).toBeInTheDocument();+ });++ it('renders as a div by default', () => {+ render(<LineClamp maxLines={2}>Content</LineClamp>);+ expect(screen.getByText('Content').tagName).toBe('DIV');+ });++ it('renders as the element passed via `as`', () => {+ render(+ <LineClamp maxLines={2} as="span">+ Content+ </LineClamp>,+ );+ expect(screen.getByText('Content').tagName).toBe('SPAN');+ });++ it('applies -webkit-line-clamp with the given maxLines', () => {+ render(<LineClamp maxLines={3}>Content</LineClamp>);+ const el = screen.getByText('Content');+ expect(el.style.webkitLineClamp).toBe('3');+ });++ it('does not set a title/tooltip when content is not truncated', () => {+ render(<LineClamp maxLines={2}>Short</LineClamp>);+ expect(screen.getByText('Short')).not.toHaveAttribute('title');+ });++ it('forwards ref to the root element', () => {+ const ref = vi.fn();+ render(+ <LineClamp maxLines={2} ref={ref}>+ Content+ </LineClamp>,+ );+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLElement));+ });++ it('forwards xstyle/className/style to the root element', () => {+ render(+ <LineClamp maxLines={2} className="custom-class">+ Content+ </LineClamp>,+ );+ expect(screen.getByText('Content')).toHaveClass('custom-class');+ });++ // jsdom still can't lay out real text, so `-webkit-line-clamp` never+ // actually clips anything here, but the tab-order fix reacts to+ // plain geometry (getBoundingClientRect), not to useTruncation's+ // isTruncated flag, so it's fully testable by mocking that geometry: a+ // container rect and a descendant rect are all the effect ever reads.+ // Each mock is installed and only then followed by a `rerender` (never+ // relying on the initial `render`'s own effect pass), since jsdom's+ // default all-zero rects would otherwise make the very first pass see a+ // coincidental "clipped" reading (0 >= 0) regardless of scenario.+ describe('keeps a clipped focusable descendant out of the tab order (#4259)', () => {+ function mockRects(rects: Map<Element, {top: number; bottom: number}>) {+ // A mapped element has a box; an unmapped one has none, as with+ // `display: none`.+ vi.spyOn(Element.prototype, 'getClientRects').mockImplementation(+ function (this: Element) {+ return (rects.has(this)+ ? [this.getBoundingClientRect()]+ : []) as unknown as DOMRectList;+ },+ );+ return vi+ .spyOn(Element.prototype, 'getBoundingClientRect')+ .mockImplementation(function (this: Element) {+ const rect = rects.get(this) ?? {top: 0, bottom: 0};+ return {+ ...rect,+ left: 0,+ right: 0,+ width: 0,+ height: rect.bottom - rect.top,+ x: 0,+ y: rect.top,+ toJSON() {+ return this;+ },+ } as DOMRect;+ });+ }++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('hides a link whose top falls at or past the clamp box bottom edge', () => {+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );+ const container = screen.getByTestId('clamp');+ const link = screen.getByText('Read more');+ mockRects(+ new Map([+ [container, {top: 0, bottom: 40}],+ [link, {top: 40, bottom: 56}], // top === container's bottom: clipped+ ]),+ );+ rerender(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );++ expect(link).toHaveAttribute('inert');+ });++ it('leaves a visible link in the tab order untouched', () => {+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );+ const container = screen.getByTestId('clamp');+ const link = screen.getByText('Read more');+ mockRects(+ new Map([+ [container, {top: 0, bottom: 40}],+ [link, {top: 20, bottom: 36}], // fully above the bottom edge: visible+ ]),+ );+ rerender(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );++ expect(link).not.toHaveAttribute('inert');+ });++ it('makes a link reachable again once it is no longer clipped', () => {+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );+ const container = screen.getByTestId('clamp');+ const link = screen.getByText('Read more');+ const rectMap = new Map([+ [container, {top: 0, bottom: 40}],+ [link, {top: 40, bottom: 56}],+ ]);+ mockRects(rectMap);+ rerender(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );+ expect(link).toHaveAttribute('inert');++ // Move the link above the fold and force another render.+ rectMap.set(link, {top: 10, bottom: 26});+ rerender(+ <LineClamp maxLines={2} data-testid="clamp" hasTruncateTooltip={false}>+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );++ expect(link).not.toHaveAttribute('inert');+ expect(link).not.toHaveAttribute('data-line-clamp-hidden');+ });++ it('checks again when a link crosses the clip edge with no resize, mutation, render or font event', () => {+ const observers: Array<{+ callback: IntersectionObserverCallback;+ options?: IntersectionObserverInit;+ targets: Set<Element>;+ }> = [];+ class FakeIntersectionObserver {+ targets = new Set<Element>();+ constructor(+ public callback: IntersectionObserverCallback,+ public options?: IntersectionObserverInit,+ ) {+ observers.push(this);+ }+ observe(el: Element) {+ this.targets.add(el);+ }+ unobserve(el: Element) {+ this.targets.delete(el);+ }+ disconnect() {+ this.targets.clear();+ }+ takeRecords() {+ return [];+ }+ }+ vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);+ const crossEdge = (link: Element) => {+ for (const observer of observers) {+ if (observer.targets.has(link)) {+ observer.callback([], observer as unknown as IntersectionObserver);+ }+ }+ };+ try {+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );+ const container = screen.getByTestId('clamp');+ const link = screen.getByText('Read more');+ const rectMap = new Map([+ [container, {top: 0, bottom: 40}],+ [link, {top: 20, bottom: 36}],+ ]);+ mockRects(rectMap);+ rerender(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );+ expect(link).not.toHaveAttribute('inert');++ // The lines re-wrap at the same box size: the link moves past the+ // edge, and only the edge observer reports it.+ rectMap.set(link, {top: 40, bottom: 56});+ act(() => crossEdge(link));+ expect(link).toHaveAttribute('inert');++ rectMap.set(link, {top: 10, bottom: 26});+ act(() => crossEdge(link));+ expect(link).not.toHaveAttribute('inert');++ // A link whose top lands exactly on the edge intersects at ratio 0,+ // so the observer must also report at a threshold just above 0.+ const thresholds = [observers[0]?.options?.threshold ?? 0].flat();+ expect(thresholds).toContain(0);+ expect(thresholds.some(value => value > 0 && value < 0.01)).toBe(true);+ rectMap.set(link, {top: 40, bottom: 56});+ act(() => crossEdge(link));+ expect(link).toHaveAttribute('inert');+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it('hides a link a child shows past the edge by removing hidden', async () => {+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text{' '}+ <a href="/more" hidden>+ Read more+ </a>+ </LineClamp>,+ );+ const container = screen.getByTestId('clamp');+ const link = screen.getByText('Read more');+ const rectMap = new Map([+ [container, {top: 0, bottom: 40}],+ [link, {top: 20, bottom: 36}],+ ]);+ mockRects(rectMap);+ rerender(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text{' '}+ <a href="/more" hidden>+ Read more+ </a>+ </LineClamp>,+ );+ expect(link).not.toHaveAttribute('inert');++ // A child shows it past the edge with no render.+ rectMap.set(link, {top: 40, bottom: 56});+ link.removeAttribute('hidden');+ await waitFor(() => expect(link).toHaveAttribute('inert'));+ });++ it('releases a hidden link a class change turns into display: contents on a visible line', async () => {+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );+ const container = screen.getByTestId('clamp');+ const link = screen.getByText('Read more');+ const rectMap = new Map([+ [container, {top: 0, bottom: 40}],+ [link, {top: 40, bottom: 56}],+ ]);+ mockRects(rectMap);+ rerender(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );+ expect(link).toHaveAttribute('inert');++ // A style change makes it `display: contents` on the first line: it has+ // no box of its own.+ rectMap.delete(link);+ link.style.display = 'contents';+ await waitFor(() => expect(link).not.toHaveAttribute('inert'));+ });++ it('keeps a 0×0 focusable on a visible line reachable', () => {+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp">+ <label>+ <input type="checkbox" data-testid="box" /> Notify me+ </label>+ </LineClamp>,+ );+ const container = screen.getByTestId('clamp');+ const box = screen.getByTestId('box');+ mockRects(+ new Map([+ [container, {top: 0, bottom: 40}],+ [box, {top: 10, bottom: 10}], // 0×0, on the first line+ ]),+ );+ rerender(+ <LineClamp maxLines={2} data-testid="clamp">+ <label>+ <input type="checkbox" data-testid="box" /> Notify me+ </label>+ </LineClamp>,+ );+ expect(box).not.toHaveAttribute('inert');+ });++ it('leaves a display: contents focusable on a visible line reachable', () => {+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text{' '}+ <span tabIndex={0} style={{display: 'contents'}} data-testid="wrap">+ <a href="/more">Read more</a>+ </span>+ </LineClamp>,+ );+ const container = screen.getByTestId('clamp');+ const wrap = screen.getByTestId('wrap');+ const link = screen.getByText('Read more');+ mockRects(+ new Map([+ [container, {top: 0, bottom: 40}],+ [link, {top: 20, bottom: 36}],+ ]),+ );+ rerender(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text{' '}+ <span tabIndex={0} style={{display: 'contents'}} data-testid="wrap">+ <a href="/more">Read more</a>+ </span>+ </LineClamp>,+ );+ expect(wrap).not.toHaveAttribute('inert');+ expect(link).not.toHaveAttribute('inert');+ });++ it('keeps a link inert while a class on an ancestor outside the clamp hides it, and releases it once it shows on a visible line', () => {+ const observers: Array<{+ callback: IntersectionObserverCallback;+ targets: Set<Element>;+ }> = [];+ class FakeIntersectionObserver {+ targets = new Set<Element>();+ constructor(public callback: IntersectionObserverCallback) {+ observers.push(this);+ }+ observe(el: Element) {+ this.targets.add(el);+ }+ unobserve(el: Element) {+ this.targets.delete(el);+ }+ disconnect() {+ this.targets.clear();+ }+ takeRecords() {+ return [];+ }+ }+ vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);+ try {+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );+ const container = screen.getByTestId('clamp');+ const link = screen.getByText('Read more');+ // An ancestor class outside the clamp hides the link: no box.+ const rectMap = new Map([[container, {top: 0, bottom: 40}]]);+ mockRects(rectMap);+ rerender(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );+ expect(link).toHaveAttribute('inert');++ // The class goes away and the link shows past the edge: still inert.+ rectMap.set(link, {top: 40, bottom: 56});+ act(() => {+ for (const observer of observers) {+ observer.callback([], observer as unknown as IntersectionObserver);+ }+ });+ expect(link).toHaveAttribute('inert');++ // It shows on a visible line: the edge observer releases it.+ rectMap.set(link, {top: 10, bottom: 26});+ act(() => {+ for (const observer of observers) {+ observer.callback([], observer as unknown as IntersectionObserver);+ }+ });+ expect(link).not.toHaveAttribute('inert');+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it('leaves a display: contents link alone while the clamp is scrolled above the viewport', () => {+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp">+ <a href="/more" style={{display: 'contents'}}>+ Read more+ </a>+ </LineClamp>,+ );+ const container = screen.getByTestId('clamp');+ const link = screen.getByText('Read more');+ mockRects(new Map([[container, {top: -200, bottom: -160}]]));+ rerender(+ <LineClamp maxLines={2} data-testid="clamp">+ <a href="/more" style={{display: 'contents'}}>+ Read more+ </a>+ </LineClamp>,+ );+ expect(link).not.toHaveAttribute('inert');+ });++ it('runs no pass for decorative style changes inside the clamp', async () => {+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp">+ <span data-testid="spark">*</span> Some text{' '}+ <a href="/more">Read more</a>+ </LineClamp>,+ );+ const container = screen.getByTestId('clamp');+ const link = screen.getByText('Read more');+ const spark = screen.getByTestId('spark');+ const rects = mockRects(+ new Map([+ [container, {top: 0, bottom: 40}],+ [link, {top: 20, bottom: 36}],+ ]),+ );+ rerender(+ <LineClamp maxLines={2} data-testid="clamp">+ <span data-testid="spark">*</span> Some text{' '}+ <a href="/more">Read more</a>+ </LineClamp>,+ );+ // Let the records from the clamp's own setup arrive first.+ await act(async () => {+ await Promise.resolve();+ });+ rects.mockClear();+ spark.style.opacity = '0.5';+ spark.style.opacity = '0.6';+ await act(async () => {+ await Promise.resolve();+ });+ // The clipping pass reads every candidate's rect. Truncation+ // measurement may read the clamp's own box, so only the link counts.+ expect(rects.mock.contexts).not.toContain(link);+ });++ it('leaves the controls of a popover inside the clamp alone', () => {+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text+ <div popover="manual">+ <button type="button">Delete</button>+ </div>+ </LineClamp>,+ );+ const container = screen.getByTestId('clamp');+ const button = screen.getByText('Delete');+ mockRects(+ new Map([+ [container, {top: 0, bottom: 40}],+ [button, {top: 60, bottom: 76}], // in the top layer, below the edge+ ]),+ );+ rerender(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text+ <div popover="manual">+ <button type="button">Delete</button>+ </div>+ </LineClamp>,+ );+ expect(button).not.toHaveAttribute('inert');+ });++ it('never makes a control in a positioned subtree inert, at any depth', () => {+ const ui = () => (+ <LineClamp maxLines={2} data-testid="clamp">+ Some text+ <span style={{position: 'absolute'}}>+ <a href="/share">Share</a>+ <ul>+ <li>+ <a href="/report">Report</a>+ </li>+ </ul>+ </span>+ <span style={{position: 'fixed'}}>+ <button type="button">Help</button>+ </span>+ </LineClamp>+ );+ const {rerender} = render(ui());+ const container = screen.getByTestId('clamp');+ const share = screen.getByText('Share');+ const report = screen.getByText('Report');+ const help = screen.getByText('Help');+ mockRects(+ new Map([+ [container, {top: 0, bottom: 40}],+ [share, {top: 60, bottom: 76}],+ [report, {top: 80, bottom: 96}], // a submenu link, deeper in+ [help, {top: 60, bottom: 76}],+ ]),+ );+ rerender(ui());+ expect(share).not.toHaveAttribute('inert');+ expect(report).not.toHaveAttribute('inert');+ expect(help).not.toHaveAttribute('inert');+ });++ it('keeps a partly visible link reachable', () => {+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );+ const container = screen.getByTestId('clamp');+ const link = screen.getByText('Read more');+ mockRects(+ new Map([+ [container, {top: 0, bottom: 40}],+ [link, {top: 30, bottom: 56}], // its first line is visible+ ]),+ );+ rerender(+ <LineClamp maxLines={2} data-testid="clamp">+ Some text <a href="/more">Read more</a>+ </LineClamp>,+ );+ expect(link).not.toHaveAttribute('inert');+ });++ it('leaves a positioned control inside an escaping panel alone', () => {+ const ui = () => (+ <LineClamp maxLines={2} data-testid="clamp">+ Some text+ <span style={{position: 'absolute'}} data-testid="panel">+ <span style={{position: 'absolute'}} data-testid="close">+ <button type="button">Close</button>+ </span>+ </span>+ </LineClamp>+ );+ const {rerender} = render(ui());+ const container = screen.getByTestId('clamp');+ const panel = screen.getByTestId('panel');+ const close = screen.getByText('Close');+ // The Close button is placed against the panel, and the panel escapes+ // the clamp: neither containing block is the clamp.+ Object.defineProperty(panel, 'offsetParent', {value: document.body});+ Object.defineProperty(screen.getByTestId('close'), 'offsetParent', {+ value: panel,+ });+ mockRects(+ new Map([+ [container, {top: 0, bottom: 40}],+ [close, {top: 60, bottom: 76}],+ ]),+ );+ rerender(ui());+ expect(close).not.toHaveAttribute('inert');+ });++ it.each([+ ['CheckboxInput', 'past the last line', {top: 60, bottom: 84}, true],+ ['CheckboxInput', 'on a visible line', {top: 10, bottom: 34}, false],+ ['Switch', 'past the last line', {top: 60, bottom: 84}, true],+ ['Switch', 'on a visible line', {top: 10, bottom: 34}, false],+ ] as const)(+ "judges a %s's positioned native input by its wrapper (%s)",+ (kind, _where, rect, isInert) => {+ const control = () =>+ kind === 'CheckboxInput' ? (+ <CheckboxInput label="Notify" value={false} onChange={() => {}} />+ ) : (+ <Switch label="Wifi" value={false} onChange={() => {}} />+ );+ const ui = () => (+ <LineClamp maxLines={2} data-testid="clamp">+ Some text {control()}+ </LineClamp>+ );+ const {rerender} = render(ui());+ const container = screen.getByTestId('clamp');+ const input = container.querySelector('input')!;+ const wrapper = input.parentElement!;+ // The native input is placed against its own positioned wrapper,+ // which sits in the clamp's flow.+ Object.defineProperty(input, 'offsetParent', {value: wrapper});+ mockRects(+ new Map([+ [container, {top: 0, bottom: 40}],+ [wrapper, rect],+ [input, rect],+ ]),+ );+ rerender(ui());+ if (isInert) {+ expect(input).toHaveAttribute('inert');+ } else {+ expect(input).not.toHaveAttribute('inert');+ }+ },+ );++ it('keeps a hidden CheckboxInput inert when a change outside the clamp shows it past the edge', () => {+ const ui = () => (+ <LineClamp maxLines={2} data-testid="clamp">+ Some text{' '}+ <CheckboxInput label="Notify" value={false} onChange={() => {}} />+ </LineClamp>+ );+ const {rerender} = render(ui());+ const container = screen.getByTestId('clamp');+ const input = container.querySelector('input')!;+ const wrapper = input.parentElement!;+ // An ancestor outside the clamp hides it: no box, no offsetParent.+ const rectMap = new Map([[container, {top: 0, bottom: 40}]]);+ mockRects(rectMap);+ rerender(ui());+ expect(input).toHaveAttribute('inert');++ // The outside change shows it past the edge, and no pass runs.+ rectMap.set(wrapper, {top: 60, bottom: 84});+ rectMap.set(input, {top: 60, bottom: 84});+ Object.defineProperty(input, 'offsetParent', {value: wrapper});+ expect(input).toHaveAttribute('inert');+ });++ it('hides a descendant a child re-enables past the fold after mount', async () => {+ // Only the late link is placed past the fold; everything else sits+ // above it. Enabling it changes an attribute only: no text change, no+ // LineClamp render, no resize, so only the mutation observer can see it.+ vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(+ function (this: Element) {+ const isLate = this.textContent === 'Late link';+ const isClamp = this.getAttribute('data-testid') === 'clamp';+ const top = isLate ? 40 : 0;+ const bottom = isClamp ? 40 : top + 16;+ return {+ top,+ bottom,+ left: 0,+ right: 0,+ width: 0,+ height: 16,+ } as DOMRect;+ },+ );+ function Late() {+ const [on, setOn] = useState(false);+ return (+ <>+ <button type="button" onClick={() => setOn(true)}>+ Reveal+ </button>+ <a href={on ? '/late' : undefined}>Late link</a>+ </>+ );+ }+ render(+ <LineClamp maxLines={2} data-testid="clamp">+ <Late />+ </LineClamp>,+ );+ fireEvent.click(screen.getByText('Reveal'));+ const late = screen.getByText('Late link');+ await waitFor(() => {+ expect(late).toHaveAttribute('inert');+ });+ });++ it("never rewrites a caller's tabIndex or aria-hidden, clipped or not", () => {+ const rectMap = new Map<Element, {top: number; bottom: number}>();+ const props = {+ maxLines: 2,+ 'data-testid': 'clamp',+ hasTruncateTooltip: false,+ };+ const link = (+ <a href="/more" tabIndex={-1} aria-hidden="true">+ Read more+ </a>+ );+ const {rerender} = render(<LineClamp {...props}>{link}</LineClamp>);+ const anchor = screen.getByText('Read more');+ rectMap.set(screen.getByTestId('clamp'), {top: 0, bottom: 40});+ rectMap.set(anchor, {top: 40, bottom: 56});+ mockRects(rectMap);+ rerender(<LineClamp {...props}>{link}</LineClamp>);+ expect(anchor).toHaveAttribute('inert');+ expect(anchor).toHaveAttribute('tabindex', '-1');+ expect(anchor).toHaveAttribute('aria-hidden', 'true');++ rectMap.set(anchor, {top: 10, bottom: 26});+ rerender(+ <LineClamp {...props} maxLines={3}>+ {link}+ </LineClamp>,+ );+ expect(anchor).not.toHaveAttribute('inert');+ expect(anchor).toHaveAttribute('tabindex', '-1');+ expect(anchor).toHaveAttribute('aria-hidden', 'true');+ });++ it('hides a link that was clipped while it held focus once focus leaves it', () => {+ const rectMap = new Map<Element, {top: number; bottom: number}>();+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp" hasTruncateTooltip={false}>+ <a href="/more">Read more</a>+ </LineClamp>,+ );+ const link = screen.getByText('Read more');+ link.focus();+ rectMap.set(screen.getByTestId('clamp'), {top: 0, bottom: 40});+ rectMap.set(link, {top: 40, bottom: 56});+ mockRects(rectMap);+ rerender(+ <LineClamp maxLines={2} data-testid="clamp" hasTruncateTooltip={false}>+ <a href="/more">Read more</a>+ </LineClamp>,+ );+ // Skipped while it holds focus.+ expect(link).not.toHaveAttribute('inert');++ link.blur();+ expect(link).toHaveAttribute('inert');+ });++ it('hides a clipped summary and a clipped contenteditable, which Core counts as focusable', () => {+ const rectMap = new Map<Element, {top: number; bottom: number}>();+ const props = {+ maxLines: 2,+ 'data-testid': 'clamp',+ hasTruncateTooltip: false,+ };+ const {rerender} = render(+ <LineClamp {...props}>+ <details>+ <summary>More</summary>+ Body+ </details>+ <span contentEditable suppressContentEditableWarning>+ Edit+ </span>+ </LineClamp>,+ );+ const summary = screen.getByText('More');+ const editable = screen.getByText('Edit');+ rectMap.set(screen.getByTestId('clamp'), {top: 0, bottom: 40});+ rectMap.set(summary, {top: 40, bottom: 56});+ rectMap.set(editable, {top: 60, bottom: 76});+ mockRects(rectMap);+ rerender(+ <LineClamp {...props}>+ <details>+ <summary>More</summary>+ Body+ </details>+ <span contentEditable suppressContentEditableWarning>+ Edit+ </span>+ </LineClamp>,+ );++ expect(summary).toHaveAttribute('inert');+ expect(editable).toHaveAttribute('inert');+ });++ it('keeps a link inert that the clamp restored and hid again in one task', async () => {+ const rectMap = new Map<Element, {top: number; bottom: number}>();+ const props = {+ maxLines: 2,+ 'data-testid': 'clamp',+ hasTruncateTooltip: false,+ };+ // A fresh element each time, so React renders again and the clamp syncs.+ const content = () => (+ <LineClamp {...props}>+ <a href="/more">Read more</a>+ </LineClamp>+ );+ const {rerender} = render(content());+ const link = screen.getByText('Read more');+ rectMap.set(screen.getByTestId('clamp'), {top: 0, bottom: 40});+ rectMap.set(link, {top: 40, bottom: 56});+ mockRects(rectMap);+ rerender(content());+ await waitFor(() => {+ expect(link).toHaveAttribute('inert');+ });++ // Visible and clipped again before the observer reports either write.+ rectMap.set(link, {top: 10, bottom: 26});+ rerender(content());+ expect(link).not.toHaveAttribute('inert');+ rectMap.set(link, {top: 40, bottom: 56});+ rerender(content());+ await act(async () => {+ await Promise.resolve();+ });++ expect(link).toHaveAttribute('inert');+ expect(link).toHaveAttribute('data-line-clamp-hidden');++ // Visible for good: the clamp still owns the attribute and takes it off.+ rectMap.set(link, {top: 10, bottom: 26});+ rerender(content());+ expect(link).not.toHaveAttribute('inert');+ expect(link).not.toHaveAttribute('data-line-clamp-hidden');+ });++ it('still calls a caller onBlur', () => {+ const onBlur = vi.fn();+ render(+ <LineClamp maxLines={2} data-testid="clamp" onBlur={onBlur}>+ <a href="/more">Read more</a>+ </LineClamp>,+ );++ fireEvent.blur(screen.getByText('Read more'));++ expect(onBlur).toHaveBeenCalledTimes(1);+ });++ it('leaves a link in a nested clamp to the nested clamp', async () => {+ const rectMap = new Map<Element, {top: number; bottom: number}>();+ const content = () => (+ <LineClamp maxLines={5} data-testid="outer" hasTruncateTooltip={false}>+ <LineClamp+ maxLines={2}+ data-testid="inner"+ hasTruncateTooltip={false}>+ <a href="/more">Read more</a>+ </LineClamp>+ </LineClamp>+ );+ const {rerender} = render(content());+ const link = screen.getByText('Read more');+ // Clipped by the inner clamp, well inside the outer clamp's box.+ rectMap.set(screen.getByTestId('outer'), {top: 0, bottom: 200});+ rectMap.set(screen.getByTestId('inner'), {top: 0, bottom: 40});+ rectMap.set(link, {top: 40, bottom: 56});+ mockRects(rectMap);+ rerender(content());+ await act(async () => {+ await Promise.resolve();+ });+ expect(link).toHaveAttribute('inert');++ // The inner clamp grows: its link is on screen and reachable again.+ rectMap.set(screen.getByTestId('inner'), {top: 0, bottom: 80});+ rerender(content());+ await act(async () => {+ await Promise.resolve();+ });+ expect(link).not.toHaveAttribute('inert');+ expect(link).not.toHaveAttribute('data-line-clamp-hidden');+ });++ it('releases a link in a clamp that mounts inside one already on screen', async () => {+ const rectMap = new Map<Element, {top: number; bottom: number}>();+ const content = (withInner: boolean) => (+ <LineClamp maxLines={5} data-testid="outer" hasTruncateTooltip={false}>+ Text+ {withInner && (+ <LineClamp+ maxLines={2}+ data-testid="inner"+ hasTruncateTooltip={false}>+ <a href="/more">Read more</a>+ </LineClamp>+ )}+ </LineClamp>+ );+ const {rerender} = render(content(false));+ rectMap.set(screen.getByTestId('outer'), {top: 0, bottom: 200});+ mockRects(rectMap);+ // The inner clamp mounts clipped, so it writes `inert` as it mounts.+ rerender(content(true));+ const link = screen.getByText('Read more');+ rectMap.set(screen.getByTestId('inner'), {top: 0, bottom: 40});+ rectMap.set(link, {top: 40, bottom: 56});+ rerender(content(true));+ await act(async () => {+ await Promise.resolve();+ });+ expect(link).toHaveAttribute('inert');++ // It scrolls into view: the clamp still owns the attribute.+ rectMap.set(link, {top: 10, bottom: 26});+ rerender(content(true));+ await act(async () => {+ await Promise.resolve();+ });+ expect(link).not.toHaveAttribute('inert');+ });++ it("still releases a link it hid across renders with a caller's inline callback ref", async () => {+ const rectMap = new Map<Element, {top: number; bottom: number}>();+ // A new function every render, so the merged ref changes every render.+ const content = () => (+ <>+ <LineClamp+ maxLines={2}+ data-testid="clamp"+ hasTruncateTooltip={false}+ ref={() => {}}>+ <a href="/more">Read more</a>+ </LineClamp>+ <LineClamp maxLines={2} hasTruncateTooltip={false} ref={() => {}}>+ Other+ </LineClamp>+ </>+ );+ const {rerender} = render(content());+ const link = screen.getByText('Read more');+ rectMap.set(screen.getByTestId('clamp'), {top: 0, bottom: 40});+ rectMap.set(link, {top: 10, bottom: 26});+ mockRects(rectMap);+ rerender(content());+ await act(async () => {+ await Promise.resolve();+ });+ expect(link).not.toHaveAttribute('inert');+ // Hide the link, then render again before the observer reports the write.+ rectMap.set(link, {top: 40, bottom: 56});+ rerender(content());+ rerender(content());+ await act(async () => {+ await Promise.resolve();+ });+ expect(link).toHaveAttribute('inert');++ // It scrolls into view for good: the clamp still owns the attribute.+ rectMap.set(link, {top: 10, bottom: 26});+ rerender(content());+ await act(async () => {+ await Promise.resolve();+ });+ expect(link).not.toHaveAttribute('inert');+ });++ it("keeps a caller's inert that is set while the link is clipped", async () => {+ const rectMap = new Map<Element, {top: number; bottom: number}>();+ const props = {+ maxLines: 2,+ 'data-testid': 'clamp',+ hasTruncateTooltip: false,+ };+ const {rerender} = render(+ <LineClamp {...props}>+ <a href="/more">Read more</a>+ </LineClamp>,+ );+ const link = screen.getByText('Read more');+ rectMap.set(screen.getByTestId('clamp'), {top: 0, bottom: 40});+ rectMap.set(link, {top: 40, bottom: 56});+ mockRects(rectMap);+ rerender(+ <LineClamp {...props}>+ <a href="/more">Read more</a>+ </LineClamp>,+ );+ expect(link).toHaveAttribute('data-line-clamp-hidden');++ // The caller makes the link inert while it is clipped.+ rerender(+ <LineClamp {...props}>+ <a href="/more" inert>+ Read more+ </a>+ </LineClamp>,+ );+ await waitFor(() => {+ expect(link).not.toHaveAttribute('data-line-clamp-hidden');+ });++ // The clamp widens: the link is visible, and still inert.+ rectMap.set(link, {top: 10, bottom: 26});+ rerender(+ <LineClamp {...props} maxLines={3}>+ <a href="/more" inert>+ Read more+ </a>+ </LineClamp>,+ );+ expect(link).toHaveAttribute('inert');+ });++ it("keeps a caller's inert across an inline-ref render when it is the only clamp", async () => {+ const rectMap = new Map<Element, {top: number; bottom: number}>();+ // A new ref function every render: the observers re-subscribe in each+ // commit, and with no other clamp mounted the shared observer+ // disconnects in between.+ const content = (isInert: boolean, maxLines = 2) => (+ <LineClamp+ maxLines={maxLines}+ data-testid="clamp"+ hasTruncateTooltip={false}+ ref={() => {}}>+ <a href="/more" inert={isInert}>+ Read more+ </a>+ </LineClamp>+ );+ const {rerender} = render(content(false));+ const link = screen.getByText('Read more');+ rectMap.set(screen.getByTestId('clamp'), {top: 0, bottom: 40});+ rectMap.set(link, {top: 40, bottom: 56});+ mockRects(rectMap);+ rerender(content(false));+ expect(link).toHaveAttribute('data-line-clamp-hidden');++ // The caller makes the clipped link inert, and the next render comes+ // before the observer reports that write.+ rerender(content(true));+ rerender(content(true));+ await act(async () => {+ await Promise.resolve();+ });++ // The clamp widens: the link is visible, and still inert.+ rectMap.set(link, {top: 10, bottom: 26});+ rerender(content(true, 3));+ await act(async () => {+ await Promise.resolve();+ });+ expect(link).toHaveAttribute('inert');+ });++ it("keeps a caller's inert that is set in the render that un-clips the link", async () => {+ const rectMap = new Map<Element, {top: number; bottom: number}>();+ const content = (isInert: boolean, maxLines = 2) => (+ <LineClamp+ maxLines={maxLines}+ data-testid="clamp"+ hasTruncateTooltip={false}>+ <a href="/more" inert={isInert}>+ Read more+ </a>+ </LineClamp>+ );+ const {rerender} = render(content(false));+ const link = screen.getByText('Read more');+ rectMap.set(screen.getByTestId('clamp'), {top: 0, bottom: 40});+ rectMap.set(link, {top: 40, bottom: 56});+ mockRects(rectMap);+ rerender(content(false));+ expect(link).toHaveAttribute('data-line-clamp-hidden');++ // One render widens the clamp and makes the link inert.+ rectMap.set(link, {top: 10, bottom: 26});+ rerender(content(true, 3));+ expect(link).toHaveAttribute('inert');+ await act(async () => {+ await Promise.resolve();+ });+ expect(link).toHaveAttribute('inert');+ expect(link).not.toHaveAttribute('data-line-clamp-hidden');+ });++ it('never hides the element that holds focus', () => {+ const rectMap = new Map<Element, {top: number; bottom: number}>();+ const {rerender} = render(+ <LineClamp maxLines={2} data-testid="clamp" hasTruncateTooltip={false}>+ <a href="/more">Read more</a>+ </LineClamp>,+ );+ const link = screen.getByText('Read more');+ link.focus();+ rectMap.set(screen.getByTestId('clamp'), {top: 0, bottom: 40});+ rectMap.set(link, {top: 40, bottom: 56});+ mockRects(rectMap);+ rerender(+ <LineClamp maxLines={2} data-testid="clamp" hasTruncateTooltip={false}>+ <a href="/more">Read more</a>+ </LineClamp>,+ );+ expect(link).toHaveFocus();+ expect(link).not.toHaveAttribute('inert');+ });+ });++ describe('observers', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ function countMutationObservers(clamps: number) {+ const Native = MutationObserver;+ let created = 0;+ vi.stubGlobal(+ 'MutationObserver',+ class extends Native {+ constructor(callback: MutationCallback) {+ super(callback);+ created += 1;+ }+ },+ );+ const {unmount} = render(+ <>+ {Array.from({length: clamps}, (_, i) => (+ <LineClamp key={i} maxLines={2}>+ Row {i} <a href="/more">more</a>+ </LineClamp>+ ))}+ </>,+ );+ unmount();+ vi.unstubAllGlobals();+ return created;+ }++ it('shares one MutationObserver across every clamp', () => {+ expect(countMutationObservers(20)).toBe(countMutationObservers(1));+ });+ });++ describe('keyboard access to the full text', () => {+ function mockOverflow() {+ vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockReturnValue(+ 100,+ );+ vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(+ 20,+ );+ }++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('makes a truncated clamp a tab stop, and leaves a fitting one alone', async () => {+ mockOverflow();+ render(+ <LineClamp maxLines={2} data-testid="clamp">+ Long text+ </LineClamp>,+ );+ await waitFor(() => {+ expect(screen.getByTestId('clamp')).toHaveAttribute('tabindex', '0');+ });+ cleanup();+ vi.restoreAllMocks();+ render(+ <LineClamp maxLines={2} data-testid="clamp">+ Short+ </LineClamp>,+ );+ expect(screen.getByTestId('clamp')).not.toHaveAttribute('tabindex');+ });++ it('sets no native title on a truncated clamp: the Tooltip alone carries the full text', async () => {+ mockOverflow();+ render(+ <LineClamp maxLines={2} data-testid="clamp">+ Long text+ </LineClamp>,+ );+ await waitFor(() => {+ expect(screen.getByTestId('clamp')).toHaveAttribute('tabindex', '0');+ });+ expect(screen.getByTestId('clamp')).not.toHaveAttribute('title');+ });++ it("calls a caller's stable ref once across re-renders", async () => {+ mockOverflow();+ const ref = vi.fn();+ const {rerender} = render(+ <LineClamp maxLines={2} ref={ref}>+ Long text+ </LineClamp>,+ );+ rerender(+ <LineClamp maxLines={2} ref={ref}>+ Long text+ </LineClamp>,+ );+ rerender(+ <LineClamp maxLines={2} ref={ref}>+ Long text, changed+ </LineClamp>,+ );+ expect(ref).toHaveBeenCalledTimes(1);+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLElement));+ });++ it("lets a caller's tabIndex win and skips the stop when the tooltip is off", async () => {+ mockOverflow();+ render(+ <>+ <LineClamp maxLines={2} data-testid="own" tabIndex={-1}>+ Long text+ </LineClamp>+ <LineClamp maxLines={2} data-testid="off" hasTruncateTooltip={false}>+ Long text+ </LineClamp>+ </>,+ );+ await waitFor(() => {+ expect(screen.getByTestId('own')).toHaveAttribute('tabindex', '-1');+ });+ expect(screen.getByTestId('off')).not.toHaveAttribute('tabindex');+ });+ });+});diff --git a/packages/lab/src/LineClamp/LineClamp.tsx b/packages/lab/src/LineClamp/LineClamp.tsxnew file mode 100644index 0000000000..c799cfcece--- /dev/null+++ b/packages/lab/src/LineClamp/LineClamp.tsx@@ -0,0 +1,574 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file LineClamp.tsx+ * @input Uses React, stylex, useTruncation + Tooltip + BaseProps from+ * @astryxdesign/core, and Core's canonical focusable selector and shared+ * mutation observer through `@astryxdesign/core/internal/line-clamp`+ * @output Exports LineClamp component, LineClampProps+ * @position Lab experiment (facebook/astryx#4180); consumed by index.ts+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/lab/src/LineClamp/LineClamp.doc.mjs (props table, features)+ * - /packages/lab/src/LineClamp/LineClamp.test.tsx (tests for new/changed behavior)+ * - /packages/lab/src/LineClamp/index.ts (exports if types change)+ * - /apps/storybook/stories/LineClamp.stories.tsx (storybook stories)+ */++import {+ useCallback,+ useLayoutEffect,+ useRef,+ type FocusEvent,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';++import type {BaseProps} from '@astryxdesign/core';+import {useTruncation} from '@astryxdesign/core/Text';+import {truncationTooltipStyles} from '@astryxdesign/core/Text/text.stylex';+import type {LayerPlacement} from '@astryxdesign/core/Layer';+import {+ composeEventHandlers,+ focusOutlineStyles,+ mergeProps,+ themeProps,+ observeResize,+} from '@astryxdesign/core/utils';+import {useMergedRefs} from '@astryxdesign/core/hooks';+import {+ FOCUSABLE_SELECTOR,+ flushMutations,+ observeMutations,+ TruncationTooltip,+ useTruncationTooltipInterest,+} from '@astryxdesign/core/internal/line-clamp';++const styles = stylex.create({+ clamp: {+ display: '-webkit-box',+ WebkitBoxOrient: 'vertical',+ // `clip`, not `hidden`: both clip the same way visually, but `hidden`+ // makes the box a scroll container, so a browser bringing a focused+ // descendant into view scrolls it, which, against a clamped box, means+ // focusing a clipped link replaces the visible line with the hidden one+ // out from under the reader. `clip` clips without becoming scrollable,+ // so that scroll-into-view path never triggers.+ overflow: 'clip',+ wordBreak: 'break-word',+ overflowWrap: 'break-word',+ },+});++const HIDDEN_ATTRIBUTE = 'data-line-clamp-hidden';+const ROOT_ATTRIBUTE = 'data-line-clamp-root';++/**+ * Whether `container` is the nearest clamp around `el`. A clamp nested inside+ * another manages its own descendants, so the outer one must not hide, restore+ * or disown them: it would undo the inner clamp's decisions with the outer+ * clamp's box in mind, not the inner one's.+ */+function isOwnedBy(container: HTMLElement, el: Element): boolean {+ // A popover or dialog renders in the top layer, which the clamp does not+ // clip, so ownership stops at that layer boundary.+ return (+ el.parentElement?.closest(`[${ROOT_ATTRIBUTE}], [popover], dialog`) ===+ container+ );+}++/**+ * Take a clipped descendant out of the tab order and the accessibility tree by+ * marking it `inert`. The element's own `tabindex` and `aria-hidden` are never+ * rewritten, so a caller's `tabIndex={-1}` or `aria-hidden="true"` survives+ * whatever the clamp does, and there is nothing to restore but the one+ * attribute this adds.+ */+function hideFromTabOrder(el: HTMLElement) {+ if (el.hasAttribute(HIDDEN_ATTRIBUTE)) {+ return;+ }+ // Already inert because the caller made it so: not ours to manage.+ if (el.hasAttribute('inert')) {+ return;+ }+ el.setAttribute('inert', '');+ el.setAttribute(HIDDEN_ATTRIBUTE, '');+}++/** Make a descendant this clamp hid reachable again. */+function restoreFromClip(el: HTMLElement) {+ el.removeAttribute('inert');+ el.removeAttribute(HIDDEN_ATTRIBUTE);+}++/**+ * Scan a clamp container for focusable descendants that fall on a visually+ * clipped line, and hide exactly those from the tab order (see the fuller+ * comment where this runs, in the component). Also includes elements this+ * already hid (`[data-line-clamp-hidden]`) so a previously-clipped descendant+ * that becomes visible again (a resize, more space) is found and restored.+ *+ * `focusTarget` is where focus is going when this runs from a `focusout`,+ * which fires before `document.activeElement` has moved.+ */+function syncFocusableClipping(+ container: HTMLElement,+ focusTarget?: Element | null,+) {+ const containerBottom = container.getBoundingClientRect().bottom;+ const candidates = container.querySelectorAll<HTMLElement>(+ `${FOCUSABLE_SELECTOR}, [data-line-clamp-hidden]`,+ );+ for (const el of candidates) {+ if (!isOwnedBy(container, el)) {+ continue;+ }+ const box = flowBox(container, el);+ if (box == null) {+ if (el.hasAttribute(HIDDEN_ATTRIBUTE)) {+ restoreFromClip(el);+ }+ continue;+ }+ // Never take the element that holds focus out of the tab order: focus+ // would be lost from under the reader.+ const isFocused =+ el.contains(document.activeElement) ||+ (focusTarget != null && el.contains(focusTarget));+ // A candidate with no box has an all-zero rect, so the rect rule cannot+ // judge it. `display: none` cannot show, so it stays inert until the edge+ // observer sees it on a visible line. `display: contents` has no box of+ // its own; its children are the candidates.+ if (el.getClientRects().length === 0) {+ if (getComputedStyle(el).display === 'contents') {+ if (el.hasAttribute(HIDDEN_ATTRIBUTE)) {+ restoreFromClip(el);+ }+ } else if (!isFocused) {+ hideFromTabOrder(el);+ }+ continue;+ }+ const isClipped =+ !isFocused && box.getBoundingClientRect().top >= containerBottom;+ if (isClipped) {+ hideFromTabOrder(el);+ } else if (el.hasAttribute('data-line-clamp-hidden')) {+ restoreFromClip(el);+ }+ }+}++/**+ * The box whose position decides whether `el` is cut off, or null when `el`+ * starts or sits in a subtree that is never made inert. A `fixed` box, or an+ * `absolute` box whose containing block is the clamp or lies outside it,+ * starts such a subtree. An `absolute` box placed against a containing block+ * in the clamp's flow (a control's own positioned wrapper) stays in the flow,+ * and that containing block's box decides. A popover or dialog stops+ * ownership in `isOwnedBy`, and a portal renders outside the clamp.+ */+function containingBlock(node: Element): Element | null {+ if (node instanceof HTMLElement && node.offsetParent != null) {+ return node.offsetParent;+ }+ // A node with no box (for example under `display: none`) has no+ // `offsetParent`, so find its containing block from computed style.+ if (node.getClientRects().length > 0) {+ return null;+ }+ for (+ let ancestor = node.parentElement;+ ancestor != null;+ ancestor = ancestor.parentElement+ ) {+ if (getComputedStyle(ancestor).position !== 'static') {+ return ancestor;+ }+ }+ return null;+}++function flowBox(container: HTMLElement, el: Element): Element | null {+ let box: Element = el;+ for (+ let node: Element | null = el;+ node != null && node !== container;+ node = node.parentElement+ ) {+ const {position} = getComputedStyle(node);+ if (position === 'fixed') {+ return null;+ }+ if (position === 'absolute') {+ const block = containingBlock(node);+ if (block == null || block === container || !container.contains(block)) {+ return null;+ }+ box = block;+ }+ }+ return box;+}++/**+ * Lines can re-wrap at the same box size with no render, mutation or resize.+ * An IntersectionObserver rooted at the clamp reports each managed focusable+ * that crosses the clip edge. A link whose top touches the edge intersects at+ * ratio 0 but is clipped, so a threshold just above 0 reports that move too.+ */+function observeEdgeCrossings(container: HTMLElement, onCross: () => void) {+ if (typeof IntersectionObserver === 'undefined') {+ return {refresh: () => {}, disconnect: () => {}};+ }+ const observer = new IntersectionObserver(onCross, {+ root: container,+ threshold: EDGE_THRESHOLDS,+ });+ const refresh = () => {+ observer.disconnect();+ const candidates = container.querySelectorAll(CANDIDATE_SELECTOR);+ for (const el of candidates) {+ if (isOwnedBy(container, el)) {+ observer.observe(el);+ }+ }+ };+ refresh();+ return {refresh, disconnect: () => observer.disconnect()};+}++const EDGE_THRESHOLDS = [0, 1e-6];++const CANDIDATE_SELECTOR = `${FOCUSABLE_SELECTOR}, [${HIDDEN_ATTRIBUTE}]`;+const BOX_ATTRIBUTES = new Set(['hidden', 'class', 'style']);++function isBoxRecord(record: MutationRecord): boolean {+ return BOX_ATTRIBUTES.has(record.attributeName ?? '');+}++/** A record that can change which descendants are focusable. */+function changesFocusables(record: MutationRecord): boolean {+ return (+ record.type === 'childList' ||+ (record.attributeName !== 'inert' && !isBoxRecord(record))+ );+}++/**+ * A `hidden`, `class` or `style` change matters only on a candidate or an+ * ancestor of one. Decorative animation inside the clamp runs no pass.+ */+function needsPass(record: MutationRecord): boolean {+ if (!isBoxRecord(record)) {+ return true;+ }+ const target = record.target;+ return (+ target instanceof Element &&+ (target.matches(CANDIDATE_SELECTOR) ||+ target.querySelector(CANDIDATE_SELECTOR) != null)+ );+}++const MUTATION_OPTIONS: MutationObserverInit = {+ childList: true,+ subtree: true,+ attributes: true,+ attributeOldValue: true,+ // `hidden`, `class` and `style` can show a focusable past the edge with no+ // other change, so they run the pass too.+ attributeFilter: [+ 'tabindex',+ 'disabled',+ 'href',+ 'inert',+ 'contenteditable',+ 'hidden',+ 'class',+ 'style',+ ],+};++/**+ * A caller writing `inert` on a link this clamp had hidden makes the attribute+ * theirs: drop the clamp's marker, so un-clipping the link leaves it as they+ * set it. The clamp's own writes are told apart by what they do rather than+ * counted, so this does not depend on when the observer attached. It only ever+ * adds or removes the attribute, so a record that goes from present to present+ * is the caller writing it again, and a hidden link left without it had it+ * taken away.+ */+function handBackCallerInert(+ container: HTMLElement,+ records: ReadonlyArray<MutationRecord>,+) {+ const inertRecords = records.filter(+ (record): record is MutationRecord & {target: HTMLElement} =>+ record.type === 'attributes' &&+ record.attributeName === 'inert' &&+ record.target instanceof HTMLElement &&+ isOwnedBy(container, record.target),+ );+ for (const [index, record] of inertRecords.entries()) {+ const target = record.target;+ // What the attribute was set to by this record: the next record for the+ // same element reports it as its old value, and the last one is the+ // element's current state.+ const next = inertRecords+ .slice(index + 1)+ .find(candidate => candidate.target === target);+ const value = next ? next.oldValue : target.getAttribute('inert');+ if (record.oldValue != null && value != null) {+ target.removeAttribute(HIDDEN_ATTRIBUTE);+ }+ }+ for (const record of inertRecords) {+ if (!record.target.hasAttribute('inert')) {+ record.target.removeAttribute(HIDDEN_ATTRIBUTE);+ }+ }+}++/**+ * A release runs in React's commit, before the new line count is written, so+ * a clipping pass there would lay the page out a second time. While a release+ * flushes the queued records, every clamp hands back its caller's `inert` at+ * once and defers its pass until the commit is done. The releasing clamp+ * skips its own pass: its layout effect syncs it.+ */+let isReleaseFlushing = false;+const deferredSyncs = new Set<() => void>();++function deferSync(sync: () => void) {+ if (deferredSyncs.size === 0) {+ queueMicrotask(() => {+ const syncs = [...deferredSyncs];+ deferredSyncs.clear();+ syncs.forEach(run => run());+ });+ }+ deferredSyncs.add(sync);+}++function releaseFlush() {+ isReleaseFlushing = true;+ try {+ flushMutations(MUTATION_OPTIONS);+ } finally {+ isReleaseFlushing = false;+ }+}++export interface LineClampProps extends BaseProps<HTMLElement> {+ /** Ref forwarded to the root element */+ ref?: React.Ref<HTMLElement>;+ /**+ * Content to clamp: mixed inline content, nested elements, anything you+ * would rather not wrap in a single `Text`.+ */+ children: ReactNode;+ /**+ * Maximum number of lines to show before clamping with an ellipsis.+ */+ maxLines: number;+ /**+ * Show a tooltip with the full text content on hover or keyboard focus when+ * clamped. A clamped root is focusable so the tooltip can be reached without a+ * pointer.+ * @default true+ */+ hasTruncateTooltip?: boolean;+ /**+ * Where the truncation tooltip opens.+ * @default 'above'+ */+ truncateTooltipPlacement?: LayerPlacement;+ /**+ * HTML element to render.+ * @default 'div'+ */+ as?: 'div' | 'span' | 'p';+}++/**+ * Clamps arbitrary content to a fixed number of lines with an ellipsis.+ *+ * `Text`'s `maxLines` clamps a `Text` element. `LineClamp` clamps whatever it+ * wraps and adds no typography of its own, so it fits content that is not a+ * single `Text` (mixed inline content, nested elements) without changing its+ * font, color or wrapping.+ *+ * Truncation detection reuses `useTruncation` (the same hook `Text` uses),+ * so overflow is measured correctly even while `-webkit-line-clamp` clips+ * `scrollHeight`.+ *+ * @example+ * ```+ * <LineClamp maxLines={2}>+ * Some <strong>mixed</strong> inline content that may run long.+ * </LineClamp>+ * <LineClamp maxLines={3} hasTruncateTooltip={false}>{longDescription}</LineClamp>+ * ```+ */+export function LineClamp({+ children,+ maxLines,+ hasTruncateTooltip = true,+ truncateTooltipPlacement = 'above',+ as: Component = 'div',+ xstyle,+ className,+ style,+ ref,+ onBlur,+ onFocus,+ onPointerEnter,+ onPointerLeave,+ onPointerDown,+ ...props+}: LineClampProps): ReactNode {+ // The clamp is height-based at every line count, so a single line must be+ // measured the way a multi-line clamp is. `useTruncation({maxLines: 1})`+ // compares horizontal overflow, which a wrapping box never has, so the+ // tooltip would never appear.+ const truncation = useTruncation({+ maxLines: maxLines > 0 ? Math.max(maxLines, 2) : 0,+ });+ const elementRef = useRef<HTMLElement>(null);++ // A resize, a re-wrap of the lines or a child's new focusable can move a+ // descendant across the edge without a render. The shared observers and+ // the edge observer run the sync for those. A callback ref attaches them+ // with the root and releases them when it goes, including when `as`+ // replaces it.+ const observeRoot = useCallback((container: HTMLElement | null) => {+ if (container == null) {+ return;+ }+ const sync = () => syncFocusableClipping(container);+ let isReleased = false;+ const edge = observeEdgeCrossings(container, () => {+ if (!isReleased) {+ sync();+ }+ });+ const unobserveMutations = observeMutations(+ container,+ MUTATION_OPTIONS,+ records => {+ handBackCallerInert(container, records);+ if (isReleased) {+ return;+ }+ if (records.some(changesFocusables)) {+ edge.refresh();+ }+ if (!records.some(needsPass)) {+ return;+ }+ if (isReleaseFlushing) {+ deferSync(sync);+ return;+ }+ sync();+ },+ );+ const unobserveResize = observeResize(container, sync);+ return () => {+ // The shared observer disconnects when its last registration goes, and+ // a disconnect drops the records it holds. Hand a caller's queued+ // `inert` back first, while this registration still receives it.+ isReleased = true;+ releaseFlush();+ edge.disconnect();+ unobserveResize();+ unobserveMutations();+ };+ }, []);+ const mergedRef = useMergedRefs(ref, truncation.ref, elementRef, observeRoot);++ const tooltipEnabled =+ hasTruncateTooltip && maxLines > 0 && truncation.isTruncated;+ // The tooltip mounts on the first hover, completed tap or focus, as Text's+ // does, so a page of clamped content mounts no tooltip layers at load.+ const tooltipInterest = useTruncationTooltipInterest(tooltipEnabled);++ // Line clamping clips paint only. A link on a clipped line stays in the Tab+ // order, so mark it inert. This runs on every render; the observers above+ // cover changes that do not render.+ useLayoutEffect(() => {+ const container = elementRef.current;+ if (container) {+ // A caller's `inert` written in this render must reach the hand-off+ // before the sync can un-clip that link.+ flushMutations(MUTATION_OPTIONS);+ syncFocusableClipping(container);+ }+ });++ // Focus has moved by now, so a link that was skipped while it held focus can+ // be hidden if it is clipped. `relatedTarget` is where focus is going.+ const handleBlur = (event: FocusEvent<HTMLElement>) => {+ syncFocusableClipping(+ event.currentTarget,+ event.relatedTarget instanceof Element ? event.relatedTarget : null,+ );+ };++ return (+ <>+ <Component+ ref={mergedRef}+ {...mergeProps(+ themeProps('line-clamp'),+ stylex.props(focusOutlineStyles.focusVisible, styles.clamp, xstyle),+ className,+ {...style, WebkitLineClamp: maxLines},+ )}+ // A truncated clamp is a tab stop so keyboard users can reveal the+ // full text through the tooltip, which opens on focus. A caller's own+ // `tabIndex` wins.+ tabIndex={tooltipEnabled ? 0 : undefined}+ {...{[ROOT_ATTRIBUTE]: ''}}+ onPointerEnter={composeEventHandlers(+ tooltipInterest.onPointerEnter,+ onPointerEnter,+ )}+ onPointerLeave={composeEventHandlers(+ tooltipInterest.onPointerLeave,+ onPointerLeave,+ )}+ onPointerDown={composeEventHandlers(+ tooltipInterest.onPointerDown,+ onPointerDown,+ )}+ onFocus={composeEventHandlers(tooltipInterest.onFocus, onFocus)}+ onBlur={composeEventHandlers(+ tooltipInterest.onBlur,+ composeEventHandlers(handleBlur, onBlur),+ )}+ {...props}>+ {children}+ </Component>+ {tooltipEnabled && tooltipInterest.isWanted && (+ <TruncationTooltip+ anchorRef={elementRef}+ content={+ <span {...stylex.props(truncationTooltipStyles.content)}>+ {truncation.fullText}+ </span>+ }+ placement={truncateTooltipPlacement}+ interest={tooltipInterest}+ />+ )}+ </>+ );+}++LineClamp.displayName = 'LineClamp';diff --git a/packages/lab/src/LineClamp/index.ts b/packages/lab/src/LineClamp/index.tsnew file mode 100644index 0000000000..124092aa13--- /dev/null+++ b/packages/lab/src/LineClamp/index.ts@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file LineClamp component barrel export+ */++export {LineClamp} from './LineClamp';+export type {LineClampProps} from './LineClamp';diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex d5fb98d29f..4515104d41 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -94,6 +94,9 @@ export {type TransferListSelectorProps,} from './TransferList';+// LineClamp — clamp arbitrary content to N lines (facebook/astryx#4180)+export {LineClamp, type LineClampProps} from './LineClamp';+// Chat — experimental reasoning displayexport {ChatReasoning,diff --git a/scripts/sync-exports.js b/scripts/sync-exports.jsindex 47b97b6742..10310fbf9f 100644--- a/scripts/sync-exports.js+++ b/scripts/sync-exports.js@@ -245,6 +245,7 @@ const FILE_MODULE_SUBPATH_EXPORTS = ['internal/calendar-system','internal/dialog-context','internal/scroll-anchoring',+ 'internal/line-clamp',];/**