Skip to content

Commit dbfdaa1

Browse files
committed
fix(Toast): a toast plays its entrance once
A top-layer ToastViewport moves its host into the latest open modal and back out. Each move renders the toast's row again, and the row's and the card's `@starting-style` played the entrance again. So a toast already on screen faded out and slid in a second time whenever a Dialog, a modal Drawer or a scrim sheet opened or closed over it. A row now keeps its starting style only until its entry transition starts. Then the row drops its closed-track start, and the card's start reads the row's custom properties, so a later move renders the card where it is. A move during a toast's own entrance finishes it at once instead of playing it again. AlertDialog's touch exit (#8084) keeps the alert open while it fades, so a toast its action raises enters inside the alert and moves out when the fade ends. This fix keeps that toast from entering twice.
1 parent 8fdf6be commit dbfdaa1

6 files changed

Lines changed: 290 additions & 2 deletions

File tree

‎.changeset/toast-entrance-once.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@astryxdesign/core': patch
3+
---
4+
5+
[fix] A toast plays its entrance once. When a `Dialog`, a modal `Drawer` or a bottom sheet with a scrim opens or closes while toasts show, the viewport moves into it or back out, and a toast already on screen now stays where it is instead of sliding in again.
6+
7+
@vjeux

‎packages/core/src/Toast/Toast.doc.mjs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,20 @@ export const docs = {
126126
default: '1',
127127
private: true,
128128
},
129+
{
130+
name: '--_toast-start-opacity',
131+
description:
132+
'Private starting opacity of the entry; ToastViewport sets it to 1 once the toast has entered',
133+
default: '0',
134+
private: true,
135+
},
136+
{
137+
name: '--_toast-start-slide',
138+
description:
139+
'Private starting offset of the entry; ToastViewport sets it to 0px once the toast has entered',
140+
default: 'var(--_toast-slide-y)',
141+
private: true,
142+
},
129143
],
130144
},
131145

‎packages/core/src/Toast/Toast.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,8 @@ const styles = stylex.create({
9393
},
9494
transitionTimingFunction: easeVars['--ease-standard'],
9595
'@starting-style': {
96-
opacity: 0,
97-
transform: `translateY(var(--_toast-slide-y, ${TOAST_EDGE_DRIFT}))`,
96+
opacity: 'var(--_toast-start-opacity, 0)',
97+
transform: `translateY(var(--_toast-start-slide, var(--_toast-slide-y, ${TOAST_EDGE_DRIFT})))`,
9898
},
9999
},
100100
variantDefault: {

‎packages/core/src/Toast/ToastViewport.tsx‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,10 @@ const styles = stylex.create({
144144
'@media (prefers-reduced-motion: reduce)': '0.01ms',
145145
},
146146
transitionTimingFunction: easeVars['--ease-standard'],
147+
},
148+
// A row opens from a closed track only when it first renders. A move to
149+
// another modal outlet renders it again, and it must not open again.
150+
toastWrapperEntering: {
147151
'@starting-style': {
148152
gridTemplateRows: '0fr',
149153
paddingBlockEnd: 0,
@@ -183,6 +187,12 @@ const styles = stylex.create({
183187
toastWrapperInnerSettled: {
184188
overflow: 'visible',
185189
},
190+
// The card's starting style reads these. A card that has entered then
191+
// starts where it is when a move renders it again.
192+
toastWrapperInnerEntered: {
193+
'--_toast-start-opacity': 1,
194+
'--_toast-start-slide': '0px',
195+
},
186196
});
187197

188198
export interface ToastViewportProps {
@@ -261,12 +271,32 @@ function ToastRow({
261271
const isAutoHide = o.isAutoHide ?? (type === 'error' ? false : true);
262272
const dur = o.autoHideDuration ?? 5000;
263273
const [isSettled, setIsSettled] = useState(false);
274+
// Each move between modal outlets renders the row again. Its starting style
275+
// must not apply then.
276+
const [hasEntryStarted, setHasEntryStarted] = useState(false);
277+
// React's onTransitionRun event has no propertyName field.
278+
const watchEntry = useCallback((row: HTMLDivElement | null) => {
279+
if (row == null) {
280+
return;
281+
}
282+
const onRun = (event: TransitionEvent) => {
283+
if (event.target === row && event.propertyName === 'grid-template-rows') {
284+
setHasEntryStarted(true);
285+
}
286+
};
287+
row.addEventListener('transitionrun', onRun);
288+
return () => {
289+
row.removeEventListener('transitionrun', onRun);
290+
};
291+
}, []);
264292

265293
return (
266294
<div
295+
ref={watchEntry}
267296
data-toast-id={entry.id}
268297
{...stylex.props(
269298
styles.toastWrapper,
299+
!hasEntryStarted && styles.toastWrapperEntering,
270300
isReversed ? styles.toastWrapperFromTop : styles.toastWrapperFromBottom,
271301
isReversed ? styles.toastWrapperGapReversed : styles.toastWrapperGap,
272302
isExiting && styles.toastWrapperExiting,
@@ -289,11 +319,13 @@ function ToastRow({
289319
// still owns pointer events and restores the clip synchronously when
290320
// dismissal starts.
291321
setIsSettled(true);
322+
setHasEntryStarted(true);
292323
}}>
293324
<div
294325
{...stylex.props(
295326
styles.toastWrapperInner,
296327
isSettled && !isExiting && styles.toastWrapperInnerSettled,
328+
hasEntryStarted && styles.toastWrapperInnerEntered,
297329
)}>
298330
<ToastSurface
299331
type={type}
Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/**
4+
* @file ToastViewport.hostMove.interaction.browser.spec.ts
5+
* @input The AppToastOverDialog story, recorded frame by frame
6+
* @output Tests that a toast plays its entrance once. A Dialog that opens or
7+
* closes over it moves the viewport, and the toast does not enter again
8+
* @position Testing; validates ToastViewport.tsx and Toast.tsx in a real
9+
* browser
10+
*/
11+
12+
import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';
13+
import {
14+
openStory,
15+
waitForRest,
16+
withStorybook,
17+
} from '@astryxdesign/interaction-harness';
18+
19+
const storybook = withStorybook(test);
20+
21+
const STORY = 'core-toast--app-toast-over-dialog';
22+
const MESSAGE = 'Toast from inside the dialog!';
23+
24+
/** The toast's card on one frame. */
25+
interface Frame {
26+
opacity: number;
27+
/** Whether the card was inside a dialog, the viewport's modal outlet. */
28+
isInDialog: boolean;
29+
}
30+
31+
/** What the recorder saw of the toast's card. */
32+
interface Recording {
33+
/** The card on each frame it was in the page. */
34+
frames: Frame[];
35+
/** The opacity transitions the card ran: one for each entrance. */
36+
entrances: number;
37+
}
38+
39+
interface Recorder {
40+
frames: Frame[];
41+
transitions: Set<Animation>;
42+
isRecording: boolean;
43+
}
44+
45+
/** Records the toast card's opacity and its opacity transitions on each frame. */
46+
async function startRecording(page: Page): Promise<void> {
47+
await page.evaluate(() => {
48+
const recorder: Recorder = {
49+
frames: [],
50+
transitions: new Set(),
51+
isRecording: true,
52+
};
53+
(window as unknown as {__toastRecorder: Recorder}).__toastRecorder =
54+
recorder;
55+
const record = () => {
56+
const card = document.querySelector('[data-toast-id] .astryx-toast');
57+
if (card != null) {
58+
recorder.frames.push({
59+
opacity: Number(getComputedStyle(card).opacity),
60+
isInDialog: card.closest('dialog') != null,
61+
});
62+
for (const animation of card.getAnimations()) {
63+
if (
64+
animation instanceof CSSTransition &&
65+
animation.transitionProperty === 'opacity'
66+
) {
67+
recorder.transitions.add(animation);
68+
}
69+
}
70+
}
71+
if (recorder.isRecording) {
72+
requestAnimationFrame(record);
73+
}
74+
};
75+
requestAnimationFrame(record);
76+
});
77+
}
78+
79+
async function stopRecording(page: Page): Promise<Recording> {
80+
return page.evaluate(() => {
81+
const recorder = (window as unknown as {__toastRecorder: Recorder})
82+
.__toastRecorder;
83+
recorder.isRecording = false;
84+
return {
85+
frames: recorder.frames,
86+
entrances: recorder.transitions.size,
87+
};
88+
});
89+
}
90+
91+
/** How many frames the recorder has seen the card in a dialog so far. */
92+
async function framesInDialog(page: Page): Promise<number> {
93+
return page.evaluate(
94+
() =>
95+
(
96+
window as unknown as {__toastRecorder: Recorder}
97+
).__toastRecorder.frames.filter(frame => frame.isInDialog).length,
98+
);
99+
}
100+
101+
/** How many frames the recorder has seen the card so far. */
102+
async function frameCount(page: Page): Promise<number> {
103+
return page.evaluate(
104+
() =>
105+
(window as unknown as {__toastRecorder: Recorder}).__toastRecorder.frames
106+
.length,
107+
);
108+
}
109+
110+
/** The card's places in frame order, each run once: `['dialog', 'page']`. */
111+
function placesOf(frames: Frame[]): string[] {
112+
const places: string[] = [];
113+
for (const {isInDialog} of frames) {
114+
const place = isInDialog ? 'dialog' : 'page';
115+
if (places.at(-1) !== place) {
116+
places.push(place);
117+
}
118+
}
119+
return places;
120+
}
121+
122+
/** Whether the card faded back out after it had shown: a second entrance. */
123+
function fadesBack(frames: Frame[]): boolean {
124+
let hasShown = false;
125+
for (const {opacity} of frames) {
126+
if (opacity > 0.9) {
127+
hasShown = true;
128+
} else if (hasShown && opacity < 0.3) {
129+
return true;
130+
}
131+
}
132+
return false;
133+
}
134+
135+
async function openDialog(page: Page) {
136+
await page.getByRole('button', {name: 'Open dialog'}).click();
137+
const dialog = page.getByRole('dialog');
138+
await waitForRest(dialog);
139+
return dialog;
140+
}
141+
142+
const toastRow = (page: Page) => page.locator('[data-toast-id]');
143+
144+
/** The message in the toast's row, not in the viewport's live region. */
145+
const toastText = (page: Page) => toastRow(page).getByText(MESSAGE);
146+
147+
/** The row is shown, with a height, after the move. */
148+
async function expectRowShown(page: Page) {
149+
await expect(toastRow(page)).toBeVisible();
150+
const box = await toastRow(page).boundingBox();
151+
expect(box?.height ?? 0).toBeGreaterThan(0);
152+
}
153+
154+
const opacitiesOf = (frames: Frame[]) => frames.map(frame => frame.opacity);
155+
156+
test.describe('a toast in a top-layer viewport', () => {
157+
test('a new toast plays its entrance once', async ({page}) => {
158+
await openStory(page, storybook(), STORY);
159+
const dialog = await openDialog(page);
160+
await startRecording(page);
161+
await dialog.getByRole('button', {name: 'Show toast'}).click();
162+
await expect(toastText(page)).toBeVisible();
163+
await waitForRest(toastRow(page));
164+
const {frames, entrances} = await stopRecording(page);
165+
await expectRowShown(page);
166+
expect(placesOf(frames)).toEqual(['dialog']);
167+
// It fades in from nearly clear to fully shown.
168+
expect(Math.min(...opacitiesOf(frames))).toBeLessThan(0.5);
169+
expect(Math.max(...opacitiesOf(frames))).toBeGreaterThan(0.99);
170+
expect(entrances).toBe(1);
171+
});
172+
173+
test('a toast raised in a Dialog that then closes enters once', async ({
174+
page,
175+
}) => {
176+
await openStory(page, storybook(), STORY);
177+
const dialog = await openDialog(page);
178+
await startRecording(page);
179+
await dialog.getByRole('button', {name: 'Show toast'}).click();
180+
// Closes once the toast has shown in the dialog, usually while it still
181+
// enters.
182+
await expect.poll(async () => framesInDialog(page)).toBeGreaterThan(0);
183+
await dialog.getByRole('button', {name: 'Close'}).click();
184+
await expect(dialog).toBeHidden();
185+
await expect(toastText(page)).toBeVisible();
186+
await waitForRest(toastRow(page));
187+
const {frames, entrances} = await stopRecording(page);
188+
await expectRowShown(page);
189+
expect(placesOf(frames)).toEqual(['dialog', 'page']);
190+
expect(fadesBack(frames)).toBe(false);
191+
expect(entrances).toBe(1);
192+
});
193+
194+
test('a toast already shown stays still when the Dialog that hosts it closes', async ({
195+
page,
196+
}) => {
197+
await openStory(page, storybook(), STORY);
198+
const dialog = await openDialog(page);
199+
await dialog.getByRole('button', {name: 'Show toast'}).click();
200+
await waitForRest(toastRow(page));
201+
await startRecording(page);
202+
await expect.poll(async () => framesInDialog(page)).toBeGreaterThan(0);
203+
await dialog.getByRole('button', {name: 'Close'}).click();
204+
await expect(dialog).toBeHidden();
205+
await waitForRest(toastRow(page));
206+
const {frames, entrances} = await stopRecording(page);
207+
await expectRowShown(page);
208+
expect(placesOf(frames)).toEqual(['dialog', 'page']);
209+
expect(Math.min(...opacitiesOf(frames))).toBeGreaterThan(0.99);
210+
expect(entrances).toBe(0);
211+
});
212+
213+
test('a toast already shown stays still when a Dialog opens over it', async ({
214+
page,
215+
}) => {
216+
await openStory(page, storybook(), STORY);
217+
const dialog = await openDialog(page);
218+
await dialog.getByRole('button', {name: 'Show toast'}).click();
219+
await dialog.getByRole('button', {name: 'Close'}).click();
220+
await expect(dialog).toBeHidden();
221+
await waitForRest(toastRow(page));
222+
await startRecording(page);
223+
await expect.poll(async () => frameCount(page)).toBeGreaterThan(0);
224+
await openDialog(page);
225+
await waitForRest(toastRow(page));
226+
const {frames, entrances} = await stopRecording(page);
227+
await expectRowShown(page);
228+
// The toast moved into the dialog that opened.
229+
expect(placesOf(frames)).toEqual(['page', 'dialog']);
230+
expect(Math.min(...opacitiesOf(frames))).toBeGreaterThan(0.99);
231+
expect(entrances).toBe(0);
232+
});
233+
});

‎packages/core/src/theme/derivedVarRegistry.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,8 @@ const VARS_WITHOUT_DERIVED_MAPPING = new Set([
372372
'--_toast-swipe-exit-y',
373373
'--_toast-swipe-opacity',
374374
'--_toast-swipe-scale',
375+
'--_toast-start-opacity',
376+
'--_toast-start-slide',
375377
// Set by each ChatMessage article from its own content and read as its
376378
// avatar's top margin, so the avatar lines up with a name row. Content
377379
// state, not a value a theme author sets.

0 commit comments

Comments
 (0)