An open source design system that's fully customizable and agent ready
TypeScript
fix(Text): truncation tooltip follows changed content, not only resizes (#7611)
Cindy Zhang374b53a9ea6b
diff --git a/.changeset/text-truncation-follows-content.md b/.changeset/text-truncation-follows-content.mdnew file mode 100644index 0000000000..950aab3769--- /dev/null+++ b/.changeset/text-truncation-follows-content.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A truncated `Text` or `Heading` (`maxLines`) now re-measures when its content changes, not only when its box resizes. A fixed-width single-line status whose message changed kept showing the first message in its truncation tooltip, and a new short message could keep a tooltip while a new long one lacked one. `useTruncation` now also observes the element's text, so the tooltip text and the truncated state follow the current content.++@cixzhangdiff --git a/packages/core/src/Text/useTruncation.test.tsx b/packages/core/src/Text/useTruncation.test.tsxnew file mode 100644index 0000000000..b617107622--- /dev/null+++ b/packages/core/src/Text/useTruncation.test.tsx@@ -0,0 +1,69 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useTruncation.test.tsx+ * Tests for useTruncation+ */++import {render, screen, waitFor} from '@testing-library/react';+import {afterEach, describe, it, expect, vi} from 'vitest';+import {useTruncation} from './useTruncation';++function Probe({text}: {text: string}) {+ const truncation = useTruncation({maxLines: 1});+ return (+ <>+ <span ref={truncation.ref}>{text}</span>+ <output data-testid="full-text">{truncation.fullText}</output>+ </>+ );+}++// A status line at a fixed width never resizes when its message changes, so+// the tooltip text must follow the content, not only the element's size.+describe('useTruncation', () => {+ it('re-measures when the text changes without a resize', async () => {+ const {rerender} = render(<Probe text="planning the first step" />);+ expect(screen.getByTestId('full-text')).toHaveTextContent(+ 'planning the first step',+ );++ rerender(<Probe text="writing the second step" />);++ await waitFor(() =>+ expect(screen.getByTestId('full-text')).toHaveTextContent(+ 'writing the second step',+ ),+ );+ });++ describe('content observation', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('shares one observer across every truncating instance', () => {+ const NativeMutationObserver = globalThis.MutationObserver;+ let created = 0;+ vi.stubGlobal(+ 'MutationObserver',+ class extends NativeMutationObserver {+ constructor(callback: MutationCallback) {+ super(callback);+ created += 1;+ }+ },+ );++ render(+ <>+ {Array.from({length: 50}, (_, index) => (+ <Probe key={index} text={`cell ${index}`} />+ ))}+ </>,+ );++ expect(created).toBe(1);+ });+ });+});diff --git a/packages/core/src/Text/useTruncation.ts b/packages/core/src/Text/useTruncation.tsindex 207fef8511..7c24e53a79 100644--- a/packages/core/src/Text/useTruncation.ts+++ b/packages/core/src/Text/useTruncation.ts@@ -4,7 +4,7 @@/*** @file useTruncation.ts- * @input Uses React hooks, sharedResizeObserver+ * @input Uses React hooks, sharedResizeObserver, sharedMutationObserver* @output Exports useTruncation hook for detecting text overflow* @position Hook; consumed by Text.tsx, Heading.tsx*@@ -14,6 +14,7 @@import {useCallback, useRef, useState, type RefCallback} from 'react';import {observeResize} from '../utils/sharedResizeObserver';+import {observeContent} from '../utils/sharedMutationObserver';export interface UseTruncationOptions {/**@@ -43,10 +44,12 @@ export interface UseTruncationReturn {/*** Hook for detecting text overflow/truncation.*- * Uses a shared ResizeObserver singleton (via observeResize)- * for efficient detection when content or container changes. A single- * ResizeObserver instance is shared across all mounted useTruncation hooks,- * so even hundreds of table cells only create one observer.+ * Uses a shared ResizeObserver singleton (via observeResize) for size+ * changes and a shared MutationObserver singleton (via observeContent) for+ * content changes, so even hundreds of table cells create one observer of+ * each kind. Observing content matters because an element whose text changes+ * without resizing (a fixed-width status line) must still be re-measured for+ * the tooltip text and the truncated state to follow the current content.** - Single-line: compares scrollWidth > offsetWidth* - Multi-line: uses Range.getBoundingClientRect() to measure actual content@@ -71,6 +74,7 @@ export function useTruncation(const [fullText, setFullText] = useState('');const elementRef = useRef<HTMLElement | null>(null);const unobserveRef = useRef<(() => void) | null>(null);+ const unobserveContentRef = useRef<(() => void) | null>(null);const checkTruncation = useCallback((element: HTMLElement) => {@@ -113,6 +117,8 @@ export function useTruncation(// by element leaves any other observer of the same node untouched.unobserveRef.current?.();unobserveRef.current = null;+ unobserveContentRef.current?.();+ unobserveContentRef.current = null;elementRef.current = element;@@ -127,6 +133,11 @@ export function useTruncation(} else {checkTruncation(element);}+ // New text in a box that keeps its size fires no resize, so the+ // captured text and truncated state would otherwise stay stale.+ unobserveContentRef.current = observeContent(element, () => {+ checkTruncation(element);+ });} else {setIsTruncated(false);setFullText('');diff --git a/packages/core/src/utils/sharedMutationObserver.test.ts b/packages/core/src/utils/sharedMutationObserver.test.tsnew file mode 100644index 0000000000..9f8a4748d8--- /dev/null+++ b/packages/core/src/utils/sharedMutationObserver.test.ts@@ -0,0 +1,53 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect, vi} from 'vitest';+import {observeContent} from './sharedMutationObserver';++const flush = async () => new Promise(resolve => setTimeout(resolve, 0));++describe('observeContent', () => {+ it('calls a registration once per batch for changes anywhere inside its element', async () => {+ const element = document.createElement('div');+ element.innerHTML = '<span>first</span>';+ const callback = vi.fn();+ const unsubscribe = observeContent(element, callback);++ element.querySelector('span')!.firstChild!.nodeValue = 'second';+ element.append('third');+ await flush();++ expect(callback).toHaveBeenCalledTimes(1);+ unsubscribe();+ });++ it('removes only its own registration', async () => {+ const element = document.createElement('div');+ const kept = vi.fn();+ const removed = vi.fn();+ const unsubscribeKept = observeContent(element, kept);+ const unsubscribeRemoved = observeContent(element, removed);++ unsubscribeRemoved();+ element.textContent = 'changed';+ await flush();++ expect(kept).toHaveBeenCalledTimes(1);+ expect(removed).not.toHaveBeenCalled();+ unsubscribeKept();+ });++ it('ignores a released element', async () => {+ const released = document.createElement('div');+ const live = document.createElement('div');+ const releasedCallback = vi.fn();+ const unsubscribeReleased = observeContent(released, releasedCallback);+ const unsubscribeLive = observeContent(live, vi.fn());++ unsubscribeReleased();+ released.textContent = 'changed';+ await flush();++ expect(releasedCallback).not.toHaveBeenCalled();+ unsubscribeLive();+ });+});diff --git a/packages/core/src/utils/sharedMutationObserver.ts b/packages/core/src/utils/sharedMutationObserver.tsnew file mode 100644index 0000000000..c8a9555a50--- /dev/null+++ b/packages/core/src/utils/sharedMutationObserver.ts@@ -0,0 +1,78 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file sharedMutationObserver.ts+ * @input MutationObserver API+ * @output Exports observeContent for shared content-change observation+ * @position Internal utility; consumed by useTruncation. The content-change+ * counterpart of sharedResizeObserver: one observer for every element, so a+ * repeated cell or row path does not create one observer per instance.+ */++type ContentCallback = () => void;++const OPTIONS: MutationObserverInit = {+ characterData: true,+ childList: true,+ subtree: true,+};++let observer: MutationObserver | null = null;+const callbacks = new Map<Node, Set<ContentCallback>>();++function dispatch(records: MutationRecord[]): void {+ // One call per callback per batch, however many records it received. A+ // record's target can be any descendant, so walk up to the observed roots.+ const pending = new Set<ContentCallback>();+ for (const record of records) {+ for (let node: Node | null = record.target; node; node = node.parentNode) {+ callbacks.get(node)?.forEach(callback => pending.add(callback));+ }+ }+ pending.forEach(callback => callback());+}++/**+ * Call `callback` when the element's text or children change (including+ * descendants). Returns an unsubscribe that removes only this registration.+ *+ * MutationObserver has no per-target unobserve, so a released element stays+ * registered with the shared observer until no element remains; its records+ * match no callback and are ignored. The observer disconnects and is released+ * when the last registration goes.+ */+export function observeContent(+ element: Element,+ callback: ContentCallback,+): () => void {+ if (typeof MutationObserver === 'undefined') {+ return () => {};+ }+ observer ??= new MutationObserver(dispatch);+ const existing = callbacks.get(element);+ if (existing) {+ existing.add(callback);+ } else {+ callbacks.set(element, new Set([callback]));+ observer.observe(element, OPTIONS);+ }++ let isSubscribed = true;+ return () => {+ if (!isSubscribed) {+ return;+ }+ isSubscribed = false;+ const targetCallbacks = callbacks.get(element);+ targetCallbacks?.delete(callback);+ if (targetCallbacks?.size === 0) {+ callbacks.delete(element);+ }+ if (callbacks.size === 0 && observer) {+ observer.disconnect();+ observer = null;+ }+ };+}