Skip to content

Commit 8bbf387

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 at rest. A move during a toast's own entrance finishes it at once instead of playing it again. That move cancels the row's entry transition, so no transition ends, and the row settles on the cancel: it releases its clip and the card's shadow paints. 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 8bbf387

6 files changed

Lines changed: 331 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 entrance starts',
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 entrance starts',
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: 40 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. Once the entrance starts, a move
191+
// renders the card at rest.
192+
toastWrapperInnerEntered: {
193+
'--_toast-start-opacity': 1,
194+
'--_toast-start-slide': '0px',
195+
},
186196
});
187197

188198
export interface ToastViewportProps {
@@ -261,12 +271,40 @@ 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 transition run and cancel events have no propertyName field.
278+
const watchEntry = useCallback((row: HTMLDivElement | null) => {
279+
if (row == null) {
280+
return;
281+
}
282+
const onTransition = (event: TransitionEvent) => {
283+
if (event.target !== row || event.propertyName !== 'grid-template-rows') {
284+
return;
285+
}
286+
setHasEntryStarted(true);
287+
// A move cancels the entry, and the row then renders fully open. No
288+
// transition ends, so the row settles here.
289+
if (event.type === 'transitioncancel') {
290+
setIsSettled(true);
291+
}
292+
};
293+
row.addEventListener('transitionrun', onTransition);
294+
row.addEventListener('transitioncancel', onTransition);
295+
return () => {
296+
row.removeEventListener('transitionrun', onTransition);
297+
row.removeEventListener('transitioncancel', onTransition);
298+
};
299+
}, []);
264300

265301
return (
266302
<div
303+
ref={watchEntry}
267304
data-toast-id={entry.id}
268305
{...stylex.props(
269306
styles.toastWrapper,
307+
!hasEntryStarted && styles.toastWrapperEntering,
270308
isReversed ? styles.toastWrapperFromTop : styles.toastWrapperFromBottom,
271309
isReversed ? styles.toastWrapperGapReversed : styles.toastWrapperGap,
272310
isExiting && styles.toastWrapperExiting,
@@ -289,11 +327,13 @@ function ToastRow({
289327
// still owns pointer events and restores the clip synchronously when
290328
// dismissal starts.
291329
setIsSettled(true);
330+
setHasEntryStarted(true);
292331
}}>
293332
<div
294333
{...stylex.props(
295334
styles.toastWrapperInner,
296335
isSettled && !isExiting && styles.toastWrapperInnerSettled,
336+
hasEntryStarted && styles.toastWrapperInnerEntered,
297337
)}>
298338
<ToastSurface
299339
type={type}
Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
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+
/** Whether the toast row's entry transition runs. */
148+
async function isEntering(page: Page): Promise<boolean> {
149+
return page.evaluate(() => {
150+
const row = document.querySelector('[data-toast-id]');
151+
return (
152+
row != null &&
153+
row
154+
.getAnimations()
155+
.some(
156+
animation =>
157+
animation instanceof CSSTransition &&
158+
animation.transitionProperty === 'grid-template-rows' &&
159+
animation.playState === 'running',
160+
)
161+
);
162+
});
163+
}
164+
165+
/**
166+
* The overflow of the row's clip. A settled row releases it, so the card's
167+
* shadow paints.
168+
*/
169+
async function rowOverflow(page: Page): Promise<string> {
170+
return page.evaluate(() => {
171+
const clip = document.querySelector('[data-toast-id] > div');
172+
return clip == null ? '' : getComputedStyle(clip).overflow;
173+
});
174+
}
175+
176+
/** The row is shown, with a height, after the move. */
177+
async function expectRowShown(page: Page) {
178+
await expect(toastRow(page)).toBeVisible();
179+
const box = await toastRow(page).boundingBox();
180+
expect(box?.height ?? 0).toBeGreaterThan(0);
181+
}
182+
183+
const opacitiesOf = (frames: Frame[]) => frames.map(frame => frame.opacity);
184+
185+
test.describe('a toast in a top-layer viewport', () => {
186+
test('a new toast plays its entrance once', async ({page}) => {
187+
await openStory(page, storybook(), STORY);
188+
const dialog = await openDialog(page);
189+
await startRecording(page);
190+
await dialog.getByRole('button', {name: 'Show toast'}).click();
191+
await expect(toastText(page)).toBeVisible();
192+
await waitForRest(toastRow(page));
193+
const {frames, entrances} = await stopRecording(page);
194+
await expectRowShown(page);
195+
expect(placesOf(frames)).toEqual(['dialog']);
196+
// It fades in from nearly clear to fully shown.
197+
expect(Math.min(...opacitiesOf(frames))).toBeLessThan(0.5);
198+
expect(Math.max(...opacitiesOf(frames))).toBeGreaterThan(0.99);
199+
expect(entrances).toBe(1);
200+
});
201+
202+
test('a toast moved during its entrance finishes it once and settles', async ({
203+
page,
204+
}) => {
205+
await openStory(page, storybook(), STORY);
206+
// A slow entrance, so the move lands inside it on any runner.
207+
await page.addStyleTag({
208+
content:
209+
'[data-toast-id], [data-toast-id] * { --duration-fast: 1500ms !important; }',
210+
});
211+
const dialog = await openDialog(page);
212+
await startRecording(page);
213+
await dialog.getByRole('button', {name: 'Show toast'}).click();
214+
await expect.poll(async () => framesInDialog(page)).toBeGreaterThan(0);
215+
expect(await isEntering(page)).toBe(true);
216+
await dialog.getByRole('button', {name: 'Close'}).click();
217+
await expect(dialog).toBeHidden();
218+
await expect(toastText(page)).toBeVisible();
219+
await expect.poll(async () => rowOverflow(page)).toBe('visible');
220+
const {frames, entrances} = await stopRecording(page);
221+
await expectRowShown(page);
222+
expect(placesOf(frames)).toEqual(['dialog', 'page']);
223+
expect(fadesBack(frames)).toBe(false);
224+
expect(entrances).toBe(1);
225+
});
226+
227+
test('a toast already shown stays still when the Dialog that hosts it closes', async ({
228+
page,
229+
}) => {
230+
await openStory(page, storybook(), STORY);
231+
const dialog = await openDialog(page);
232+
await dialog.getByRole('button', {name: 'Show toast'}).click();
233+
await waitForRest(toastRow(page));
234+
await startRecording(page);
235+
await expect.poll(async () => framesInDialog(page)).toBeGreaterThan(0);
236+
await dialog.getByRole('button', {name: 'Close'}).click();
237+
await expect(dialog).toBeHidden();
238+
await waitForRest(toastRow(page));
239+
const {frames, entrances} = await stopRecording(page);
240+
await expectRowShown(page);
241+
expect(placesOf(frames)).toEqual(['dialog', 'page']);
242+
expect(Math.min(...opacitiesOf(frames))).toBeGreaterThan(0.99);
243+
expect(entrances).toBe(0);
244+
});
245+
246+
test('a toast already shown stays still when a Dialog opens over it', async ({
247+
page,
248+
}) => {
249+
await openStory(page, storybook(), STORY);
250+
const dialog = await openDialog(page);
251+
await dialog.getByRole('button', {name: 'Show toast'}).click();
252+
await dialog.getByRole('button', {name: 'Close'}).click();
253+
await expect(dialog).toBeHidden();
254+
await waitForRest(toastRow(page));
255+
await startRecording(page);
256+
await expect.poll(async () => frameCount(page)).toBeGreaterThan(0);
257+
await openDialog(page);
258+
await waitForRest(toastRow(page));
259+
const {frames, entrances} = await stopRecording(page);
260+
await expectRowShown(page);
261+
// The toast moved into the dialog that opened.
262+
expect(placesOf(frames)).toEqual(['page', 'dialog']);
263+
expect(Math.min(...opacitiesOf(frames))).toBeGreaterThan(0.99);
264+
expect(entrances).toBe(0);
265+
});
266+
});

‎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)