Skip to content

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

TypeScript

fix(lab): write latest-value refs at commit, not during render (#10780)

Christopher Chedeau642cc2de1b8b
diff --git a/packages/lab/src/Comments/CommentComposer.test.tsx b/packages/lab/src/Comments/CommentComposer.test.tsx
index b89d6197ef..e290daa209 100644
--- a/packages/lab/src/Comments/CommentComposer.test.tsx
+++ b/packages/lab/src/Comments/CommentComposer.test.tsx
@@ -1,6 +1,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {useState} from 'react';
+import {
+ Suspense,
+ startTransition,
+ use,
+ useState,
+ type ComponentProps,
+} from 'react';
import {act, fireEvent, render, screen, within} from '@testing-library/react';
import {
afterAll,
@@ -495,3 +501,109 @@ describe('CommentComposer', () => {
expect(screen.getByRole('button', {name: 'Pin to moment'})).toBeTruthy();
});
});
+
+describe('CommentComposer, when React discards a render', () => {
+ // A transition that suspends for good: React renders the new props, then
+ // keeps the committed tree and never commits that render.
+ const pending = new Promise<never>(() => {});
+ function Pending(): null {
+ use(pending);
+ return null;
+ }
+ function Screen({
+ isPending,
+ ...props
+ }: Partial<ComponentProps<typeof CommentComposerBase>> & {
+ isPending: boolean;
+ }) {
+ return (
+ <Suspense fallback={null}>
+ <CommentComposerBase
+ value="Committed draft"
+ onChange={() => {}}
+ onSubmit={() => {}}
+ placeholder="Reply"
+ context={{kind: 'comment'}}
+ highlightColor="yellow"
+ triggers={[]}
+ agentCommands={[]}
+ hasEmojiPicker={false}
+ isSubmitting={false}
+ {...props}
+ />
+ {isPending ? <Pending /> : null}
+ </Suspense>
+ );
+ }
+ const neverUploads = () =>
+ new Promise<{url: string; alt: string}[]>(() => {});
+ async function pickImage(container: HTMLElement) {
+ const input = container.querySelector('input[type="file"]');
+ if (!(input instanceof HTMLInputElement)) {
+ throw new Error('File input not found');
+ }
+ const file = new File(['png'], 'chart.png', {type: 'image/png'});
+ await act(async () => {
+ fireEvent.change(input, {target: {files: [file]}});
+ await Promise.resolve();
+ });
+ return file;
+ }
+
+ it('posts the committed draft', async () => {
+ const onSubmit = vi.fn();
+ const {rerender} = render(<Screen isPending={false} onSubmit={onSubmit} />);
+ await act(async () => {
+ startTransition(() => {
+ rerender(
+ <Screen isPending value="Discarded draft" onSubmit={onSubmit} />,
+ );
+ });
+ });
+ fireEvent.click(screen.getByRole('button', {name: /send/i}));
+ expect(onSubmit).toHaveBeenCalledWith('Committed draft');
+ });
+
+ it('reports an upload to the committed onActionPendingChange', async () => {
+ const committed = vi.fn();
+ const discarded = vi.fn();
+ const onUploadImages = vi.fn(neverUploads);
+ const {container, rerender} = render(
+ <Screen
+ isPending={false}
+ onUploadImages={onUploadImages}
+ onActionPendingChange={committed}
+ />,
+ );
+ await act(async () => {
+ startTransition(() => {
+ rerender(
+ <Screen
+ isPending
+ onUploadImages={onUploadImages}
+ onActionPendingChange={discarded}
+ />,
+ );
+ });
+ });
+ await pickImage(container);
+ expect(discarded).not.toHaveBeenCalled();
+ expect(committed).toHaveBeenCalledWith(true);
+ });
+
+ it('starts an upload while the committed composer is not submitting', async () => {
+ const onUploadImages = vi.fn(neverUploads);
+ const {container, rerender} = render(
+ <Screen isPending={false} onUploadImages={onUploadImages} />,
+ );
+ await act(async () => {
+ startTransition(() => {
+ rerender(
+ <Screen isPending isSubmitting onUploadImages={onUploadImages} />,
+ );
+ });
+ });
+ const file = await pickImage(container);
+ expect(onUploadImages).toHaveBeenCalledWith([file]);
+ });
+});
diff --git a/packages/lab/src/Comments/CommentComposer.tsx b/packages/lab/src/Comments/CommentComposer.tsx
index d993cfba02..4ac8dd8a6a 100644
--- a/packages/lab/src/Comments/CommentComposer.tsx
+++ b/packages/lab/src/Comments/CommentComposer.tsx
@@ -21,6 +21,7 @@
import {
useCallback,
useEffect,
+ useLayoutEffect,
useMemo,
useRef,
useState,
@@ -236,16 +237,21 @@ export function CommentComposerBase({
[agentCommandTrigger, hostTriggers],
);
const latestValueRef = useRef(value);
- latestValueRef.current = value;
const isMountedRef = useRef(true);
const actionPendingRef = useRef(false);
// The latest callback, read when reporting. An inline callback is new on
// every render; depending on it would re-run the unmount cleanup below on
// each render and leave the composer busy after its upload ends.
const onActionPendingChangeRef = useRef(onActionPendingChange);
- onActionPendingChangeRef.current = onActionPendingChange;
const isSubmittingRef = useRef(isSubmitting);
- isSubmittingRef.current = isSubmitting;
+ // Syncs the handlers' refs with the committed props. The host owns these
+ // props, so no handler here sees each change. A render React discards, as
+ // a suspended transition does, must not leave its values.
+ useLayoutEffect(() => {
+ latestValueRef.current = value;
+ onActionPendingChangeRef.current = onActionPendingChange;
+ isSubmittingRef.current = isSubmitting;
+ });
const imageInputRef = useRef<HTMLInputElement>(null);
const inputRef = useRef<ChatComposerInputHandle | null>(null);
// Focus lands once per `focusKey`, when the input attaches: the handle ref
diff --git a/packages/lab/src/Comments/CommentThread.test.tsx b/packages/lab/src/Comments/CommentThread.test.tsx
index d72b0a5feb..1a8819ff50 100644
--- a/packages/lab/src/Comments/CommentThread.test.tsx
+++ b/packages/lab/src/Comments/CommentThread.test.tsx
@@ -2,7 +2,7 @@
import {act, fireEvent, render, screen, within} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import {useState} from 'react';
+import {Suspense, startTransition, use, useRef, useState} from 'react';
import {createPortal} from 'react-dom';
import {
afterAll,
@@ -29,7 +29,11 @@ vi.mock('../EmojiPicker/emojiData', () => ({
import {Popover} from '@astryxdesign/core/Popover';
import {CommentThread, type CommentThreadProps} from './CommentThread';
-import {unsavedDraftOf} from './useCommentThreadDismissal';
+import {
+ unsavedDraftOf,
+ useCommentThreadDismissal,
+ type UnsavedDraft,
+} from './useCommentThreadDismissal';
import type {
CommentComposerRenderProps,
CommentThreadData,
@@ -352,6 +356,62 @@ describe('CommentThread dismissal', () => {
const UNSAVED = 'Unsaved draft. Dismiss again to discard it.';
+ it('guards the committed draft when React discards a render without it', async () => {
+ // A transition that suspends for good: React renders the new props, then
+ // keeps the committed tree and never commits that render.
+ const pending = new Promise<never>(() => {});
+ function Pending(): null {
+ use(pending);
+ return null;
+ }
+ const onDismiss = vi.fn();
+ const draft: UnsavedDraft = {
+ kind: 'reply',
+ parentId: 'c1',
+ signature: 'reply:c1:Half a thought',
+ };
+ function Thread({draft}: {draft: UnsavedDraft | null}) {
+ const rootRef = useRef<HTMLDivElement>(null);
+ const {onRootPointerDownCapture} = useCommentThreadDismissal({
+ onDismiss,
+ rootRef,
+ draft,
+ announce: () => {},
+ });
+ return (
+ <div ref={rootRef} onPointerDownCapture={onRootPointerDownCapture}>
+ <textarea aria-label="Reply" defaultValue="Half a thought" />
+ </div>
+ );
+ }
+ function Screen({
+ draft,
+ isPending,
+ }: {
+ draft: UnsavedDraft | null;
+ isPending: boolean;
+ }) {
+ return (
+ <>
+ <button type="button">Elsewhere</button>
+ <Suspense fallback={null}>
+ <Thread draft={draft} />
+ {isPending ? <Pending /> : null}
+ </Suspense>
+ </>
+ );
+ }
+ const {rerender} = render(<Screen draft={draft} isPending={false} />);
+ await settle();
+ await act(async () => {
+ startTransition(() => {
+ rerender(<Screen draft={null} isPending />);
+ });
+ });
+ press(screen.getByRole('button', {name: 'Elsewhere'}));
+ expect(onDismiss).not.toHaveBeenCalled();
+ });
+
it('dismisses on an outside press when nothing is unsaved', async () => {
const {onDismiss} = renderThread();
await settle();
diff --git a/packages/lab/src/Comments/useCommentThreadDismissal.ts b/packages/lab/src/Comments/useCommentThreadDismissal.ts
index 9754df77c4..51ace43b63 100644
--- a/packages/lab/src/Comments/useCommentThreadDismissal.ts
+++ b/packages/lab/src/Comments/useCommentThreadDismissal.ts
@@ -51,6 +51,7 @@
import {
useEffect,
+ useLayoutEffect,
useRef,
type PointerEvent as ReactPointerEvent,
type RefObject,
@@ -320,16 +321,20 @@ export function useCommentThreadDismissal({
};
// The document listeners run outside render and reach the latest draft
- // through this ref, as the composer's own listeners do.
+ // through this ref, as the composer's own listeners do. The ref is written
+ // at commit: a render React discards, as a suspended transition does, must
+ // not leave its draft for the listeners.
const latestRef = useRef<{
request: () => RequestOutcome;
wouldGuard: () => boolean;
} | null>(null);
- latestRef.current = {
- request,
- wouldGuard: () =>
- draft != null && guardedSignatureRef.current !== draft.signature,
- };
+ useLayoutEffect(() => {
+ latestRef.current = {
+ request,
+ wouldGuard: () =>
+ draft != null && guardedSignatureRef.current !== draft.signature,
+ };
+ });
const {shouldDismissOnCloseRequest} = useLayerDismissal({
isActive: isEnabled,
diff --git a/packages/lab/src/RefreshControl/refreshTouchController.ts b/packages/lab/src/RefreshControl/refreshTouchController.ts
index 525e2e7c3a..465846678b 100644
--- a/packages/lab/src/RefreshControl/refreshTouchController.ts
+++ b/packages/lab/src/RefreshControl/refreshTouchController.ts
@@ -43,6 +43,7 @@
import {
useCallback,
useEffect,
+ useLayoutEffect,
useMemo,
useRef,
useState,
@@ -313,8 +314,12 @@ export function useRefreshTouchController({
edge.current = {element: null, saved: null};
}, []);
+ // Syncs the scroll listener's ref with the committed `isPullEnabled`. A
+ // render React discards must not leave its value.
const isPullEnabledRef = useRef(isPullEnabled);
- isPullEnabledRef.current = isPullEnabled;
+ useLayoutEffect(() => {
+ isPullEnabledRef.current = isPullEnabled;
+ });
/**
* Near the top, the browser draws no overscroll: the pull does. Only an
diff --git a/packages/lab/src/RefreshControl/useRefreshControl.test.tsx b/packages/lab/src/RefreshControl/useRefreshControl.test.tsx
index 15695a6a7c..dcdd13952a 100644
--- a/packages/lab/src/RefreshControl/useRefreshControl.test.tsx
+++ b/packages/lab/src/RefreshControl/useRefreshControl.test.tsx
@@ -12,7 +12,7 @@
* checks the motion itself (the interaction spec and its storyboards)
*/
-import {useState, type ReactNode} from 'react';
+import {Suspense, startTransition, use, useState, type ReactNode} from 'react';
import {act, render, screen, waitFor} from '@testing-library/react';
import {
GestureRecognizer,
@@ -864,6 +864,64 @@ describe('useRefreshControl', () => {
render(<p data-testid="refresh">Gone</p>);
});
+ it('keeps the edge claimed when React discards a render that disables the pull', async () => {
+ // A transition that suspends for good: React renders the new props, then
+ // keeps the committed tree and never commits that render.
+ const pending = new Promise<never>(() => {});
+ function Pending(): null {
+ use(pending);
+ return null;
+ }
+ function List({isDisabled}: {isDisabled: boolean}) {
+ const control = useRefreshControl({
+ onRefresh: () => {},
+ announce: 'Refreshing',
+ isDisabled,
+ });
+ return (
+ <div data-testid="list" ref={measured} style={{overflowY: 'auto'}}>
+ <div data-testid="refresh" ref={control.contentRef}>
+ <div ref={control.indicatorRef} aria-hidden />
+ <p>Inbox</p>
+ </div>
+ </div>
+ );
+ }
+ function Screen({
+ isDisabled,
+ isPending,
+ }: {
+ isDisabled: boolean;
+ isPending: boolean;
+ }) {
+ return (
+ <Suspense fallback={null}>
+ <List isDisabled={isDisabled} />
+ {isPending ? <Pending /> : null}
+ </Suspense>
+ );
+ }
+ const {rerender} = render(<Screen isDisabled={false} isPending={false} />);
+ await act(async () => {
+ for (let frame = 0; frame < 3; frame += 1) {
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => resolve());
+ });
+ }
+ });
+ const list = screen.getByTestId('list');
+ expect(list.style.overscrollBehaviorY).toBe('none');
+ await act(async () => {
+ startTransition(() => {
+ rerender(<Screen isDisabled isPending />);
+ });
+ });
+ act(() => {
+ list.dispatchEvent(new Event('scroll'));
+ });
+ expect(list.style.overscrollBehaviorY).toBe('none');
+ });
+
it('sets up the edge for content that mounts after the hook: its container is claimed near the top, given back when scrolled away, and given back when the content leaves', async () => {
function Late({isShown}: {isShown: boolean}) {
const control = useRefreshControl({
diff --git a/packages/lab/src/RefreshControl/useRefreshControl.ts b/packages/lab/src/RefreshControl/useRefreshControl.ts
index d614c13a68..4fcfc0fbd7 100644
--- a/packages/lab/src/RefreshControl/useRefreshControl.ts
+++ b/packages/lab/src/RefreshControl/useRefreshControl.ts
@@ -204,7 +204,10 @@ export function useRefreshControl({
},
[run],
);
- dispatchRef.current = dispatch;
+ // Syncs the touch layer's ref with the committed dispatch.
+ useLayoutEffect(() => {
+ dispatchRef.current = dispatch;
+ });
// -- Programmatic control -------------------------------------------------
diff --git a/packages/lab/src/Schedule/TimeGridView.tsx b/packages/lab/src/Schedule/TimeGridView.tsx
index b938f17207..f89e89c0f4 100644
--- a/packages/lab/src/Schedule/TimeGridView.tsx
+++ b/packages/lab/src/Schedule/TimeGridView.tsx
@@ -185,12 +185,15 @@ export function TimeGridView({
minHour: normalizedMinHour,
hourHeight,
});
- positioning.current = {
- currentTime,
- days,
- minHour: normalizedMinHour,
- hourHeight,
- };
+ // Syncs the positioning effect's inputs at commit, before it reads them.
+ useLayoutEffect(() => {
+ positioning.current = {
+ currentTime,
+ days,
+ minHour: normalizedMinHour,
+ hourHeight,
+ };
+ });
const isBlockScrollable = scrollState.block.isScrollable;
// The clock is 0 only in the server snapshot; wait for the client's.
const hasClock = currentTime !== 0;
@@ -246,8 +249,6 @@ export function TimeGridView({
eventID: string;
dayISO: string;
} | null>(null);
- const openBlockRef = useRef(openBlock);
- openBlockRef.current = openBlock;
const openEvent =
openBlock == null
? null
@@ -264,8 +265,6 @@ export function TimeGridView({
setOpenBlock(null);
}, []),
});
- const popoverRef = useRef(popover);
- popoverRef.current = popover;
// A pointer press on a block while the popover is open would close it by
// the browser's light dismiss before the click arrives, and the layer then
// absorbs a show() from that same press. So the press itself decides: a
@@ -282,9 +281,10 @@ export function TimeGridView({
target
?.closest('[data-schedule-event-block]')
?.getAttribute('data-schedule-event-block') ?? null;
- const current = openBlockRef.current;
const currentKey =
- current == null ? null : blockKeyOf(current.eventID, current.dayISO);
+ openBlock == null
+ ? null
+ : blockKeyOf(openBlock.eventID, openBlock.dayISO);
openBlockAtPressRef.current = pressedKey == null ? null : currentKey;
if (
pressedKey != null &&
@@ -306,9 +306,9 @@ export function TimeGridView({
const key = blockKeyOf(event.id, dayISO);
const openAtPress = openBlockAtPressRef.current;
openBlockAtPressRef.current = null;
- const current = openBlockRef.current;
const isCurrent =
- current != null && blockKeyOf(current.eventID, current.dayISO) === key;
+ openBlock != null &&
+ blockKeyOf(openBlock.eventID, openBlock.dayISO) === key;
if (openAtPress === key || (isCurrent && popover.isOpen)) {
if (popover.isOpen) {
popover.hide();
@@ -327,7 +327,7 @@ export function TimeGridView({
let openContent: ReactNode = null;
useEffect(() => {
if (openBlockKey != null && !paintedBlockKeys.has(openBlockKey)) {
- popoverRef.current.hide();
+ popover.hide();
setOpenBlock(null);
}
});
diff --git a/packages/lab/src/Schedule/useScheduleViewPopover.ts b/packages/lab/src/Schedule/useScheduleViewPopover.ts
index 432b85e774..06ba47da92 100644
--- a/packages/lab/src/Schedule/useScheduleViewPopover.ts
+++ b/packages/lab/src/Schedule/useScheduleViewPopover.ts
@@ -76,8 +76,6 @@ export function useScheduleViewPopover(
onTriggerLost?: (key: string) => void,
): ScheduleViewPopover {
const [openKey, setOpenKey] = useState<string | null>(null);
- const openKeyRef = useRef(openKey);
- openKeyRef.current = openKey;
const popover = usePopover({
dialogLabel: dialogLabelFor(openKey),
// Popover's own defaults, spelled out where the hook's differ.
@@ -90,8 +88,6 @@ export function useScheduleViewPopover(
setOpenKey(null);
}, []),
});
- const popoverRef = useRef(popover);
- popoverRef.current = popover;
// A pointer press on a trigger while the popover is open would close it by
// the browser's light dismiss before the click arrives, and the layer then
@@ -107,12 +103,11 @@ export function useScheduleViewPopover(
target
?.closest(`[${TRIGGER_ATTRIBUTE}]`)
?.getAttribute(TRIGGER_ATTRIBUTE) ?? null;
- const currentKey = openKeyRef.current;
- openKeyAtPressRef.current = pressedKey == null ? null : currentKey;
+ openKeyAtPressRef.current = pressedKey == null ? null : openKey;
if (
pressedKey != null &&
- currentKey != null &&
- pressedKey !== currentKey &&
+ openKey != null &&
+ pressedKey !== openKey &&
popover.isOpen
) {
popover.hide();
@@ -124,7 +119,7 @@ export function useScheduleViewPopover(
const toggle = (key: string, button: HTMLButtonElement) => {
const openAtPress = openKeyAtPressRef.current;
openKeyAtPressRef.current = null;
- if (openAtPress === key || (openKeyRef.current === key && popover.isOpen)) {
+ if (openAtPress === key || (openKey === key && popover.isOpen)) {
if (popover.isOpen) {
popover.hide();
}
@@ -151,7 +146,7 @@ export function useScheduleViewPopover(
}
focusSwitchedContentRef.current = false;
const frame = requestAnimationFrame(() => {
- const content = popoverRef.current.contentRef.current;
+ const content = popover.contentRef.current;
if (content == null) {
return;
}
@@ -161,7 +156,7 @@ export function useScheduleViewPopover(
(first ?? content).focus();
});
return () => cancelAnimationFrame(frame);
- }, [openKey]);
+ }, [openKey, popover.contentRef]);
// Triggers painted this render; the popover may stay open only for one of
// them. When its trigger is gone, focus — inside the popover, or dropped
@@ -170,13 +165,13 @@ export function useScheduleViewPopover(
const paintedKeys = new Set<string>();
useEffect(() => {
if (openKey != null && !paintedKeys.has(openKey)) {
- const content = popoverRef.current.contentRef.current;
+ const content = popover.contentRef.current;
const active = document.activeElement;
const hadFocus =
active == null ||
active === document.body ||
(content?.contains(active) ?? false);
- popoverRef.current.hide();
+ popover.hide();
setOpenKey(null);
if (hadFocus) {
onTriggerLost?.(openKey);
diff --git a/packages/lab/src/TransferList/TransferList.test.tsx b/packages/lab/src/TransferList/TransferList.test.tsx
index d5ccadf0b4..2d88d421bf 100644
--- a/packages/lab/src/TransferList/TransferList.test.tsx
+++ b/packages/lab/src/TransferList/TransferList.test.tsx
@@ -11,7 +11,7 @@
* SYNC: When TransferList.tsx behavior changes, update these tests.
*/
-import {useMemo, useState} from 'react';
+import {Suspense, startTransition, use, useMemo, useState} from 'react';
import {afterEach, describe, expect, it, vi} from 'vitest';
import {
act,
@@ -346,6 +346,46 @@ describe('TransferList', () => {
});
describe('transfers and filtering', () => {
+ it('adds to the committed value when React discards a render', async () => {
+ // A transition that suspends for good: React renders the new props, then
+ // keeps the committed tree and never commits that render.
+ const pending = new Promise<never>(() => {});
+ function Pending(): null {
+ use(pending);
+ return null;
+ }
+ const onChange = vi.fn();
+ function Screen({
+ value,
+ isPending,
+ }: {
+ value: readonly string[];
+ isPending: boolean;
+ }) {
+ return (
+ <Suspense fallback={null}>
+ <TransferList
+ label="Columns"
+ selectedLabel="Selected columns"
+ availableLabel="Available columns"
+ options={OPTIONS}
+ value={value}
+ onChange={onChange}
+ />
+ {isPending ? <Pending /> : null}
+ </Suspense>
+ );
+ }
+ const {rerender} = render(<Screen value={['name']} isPending={false} />);
+ await act(async () => {
+ startTransition(() => {
+ rerender(<Screen value={['name', 'status']} isPending />);
+ });
+ });
+ fireEvent.click(screen.getByRole('button', {name: 'Add Owner'}));
+ expect(onChange).toHaveBeenLastCalledWith(['name', 'owner']);
+ });
+
it('appends an added value and preserves selected order when removing', async () => {
const user = userEvent.setup();
const onValueChange = vi.fn();
diff --git a/packages/lab/src/TransferList/TransferList.tsx b/packages/lab/src/TransferList/TransferList.tsx
index 74373083a1..d99653ad68 100644
--- a/packages/lab/src/TransferList/TransferList.tsx
+++ b/packages/lab/src/TransferList/TransferList.tsx
@@ -21,6 +21,7 @@ import {
Fragment,
useCallback,
useId,
+ useLayoutEffect,
useMemo,
useRef,
useState,
@@ -439,7 +440,11 @@ export function TransferList<T extends string = string>({
const [query, setQuery] = useState('');
const announce = useAnnounce();
- currentValueRef.current = value;
+ // Syncs the handlers' ref with the committed `value`. A render React
+ // discards, as a suspended transition does, must not leave its value.
+ useLayoutEffect(() => {
+ currentValueRef.current = value;
+ });
// An option's own message names its own constraint.
// It does not apply to a disabled list.
@@ -754,9 +759,7 @@ export function TransferList<T extends string = string>({
isDisabled={isDisabled}
xstyle={[styles.item, isDisabled && styles.disabledItem]}
data-transfer-list-row={option.value}
- data-transfer-list-index={String(
- currentValueRef.current.indexOf(option.value),
- )}
+ data-transfer-list-index={String(value.indexOf(option.value))}
{...theme}
/>
);
@@ -915,7 +918,7 @@ export function TransferList<T extends string = string>({
!options.some(
option =>
!option.isTransferDisabled &&
- !currentValueRef.current.includes(option.value),
+ !value.includes(option.value),
)
}
onClick={addAll}