Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions packages/react/src/toast/createToastManager.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as React from 'react';
import { Toast } from '@base-ui/react/toast';
import { fireEvent, flushMicrotasks, screen } from '@mui/internal-test-utils';
import { expect } from 'chai';
import { spy } from 'sinon';
import { createRenderer, isJSDOM } from '#test-utils';
import { List } from './utils/test-utils';

Expand Down Expand Up @@ -672,5 +673,57 @@ describe.skipIf(!isJSDOM)('createToastManager', () => {

expect(screen.queryByTestId('title')).to.equal(null);
});

it('does not call onClose when closing toasts that are already ending', async () => {
const toastManager = Toast.createToastManager();
const onCloseSpy1 = spy();
const onCloseSpy2 = spy();
let toastId1: string;

function add() {
toastId1 = toastManager.add({
title: 'toast 1',
onClose: onCloseSpy1,
});

toastManager.add({
title: 'toast 2',
onClose: onCloseSpy2,
});
}

function close() {
toastManager.close(toastId1);
toastManager.close();
}

function Buttons() {
return (
<React.Fragment>
<button type="button" onClick={add}>
add
</button>
<button type="button" onClick={close}>
close
</button>
</React.Fragment>
);
}

await render(
<Toast.Provider toastManager={toastManager}>
<Toast.Viewport>
<List />
</Toast.Viewport>
<Buttons />
</Toast.Provider>,
);

fireEvent.click(screen.getByRole('button', { name: 'add' }));
fireEvent.click(screen.getByRole('button', { name: 'close' }));

expect(onCloseSpy1.callCount).to.equal(1);
expect(onCloseSpy2.callCount).to.equal(1);
});
});
});
22 changes: 12 additions & 10 deletions packages/react/src/toast/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,24 +235,26 @@ export class ToastStore extends ReactStore<State, {}, typeof selectors> {

closeToast = (toastId?: string) => {
const closeAll = toastId === undefined;
const toast = closeAll ? undefined : selectors.toast(this.state, toastId);
if (!closeAll && !toast) {
return;
}

const { limit, toasts } = this.state;

const callOnClose = (toast: ToastObject<any>) => {
if (toast.transitionStatus !== 'ending') {
toast.onClose?.();
}
};

if (closeAll) {
toasts.forEach((item) => {
item.onClose?.();
});
toasts.forEach(callOnClose);
this.timers.forEach((timer) => {
timer.timeout?.clear();
});
this.timers.clear();
} else {
toast?.onClose?.();

const toast = selectors.toast(this.state, toastId);
if (!toast) {
return;
}
callOnClose(toast);
const timer = this.timers.get(toastId);
if (timer?.timeout) {
timer.timeout.clear();
Expand Down
Loading