Skip to content

Commit 7844652

Browse files
authored
Toast dismiss all (#45)
* Remove all toasts when dismiss function is empty * Update readme * Revert index tsx changes
1 parent d0e1a48 commit 7844652

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,14 @@ const toastId = toast('Event has been created');
207207
toast.dismiss(toastId);
208208
```
209209

210+
You can also use the dismiss method without the id to dismiss all toasts.
211+
212+
```jsx
213+
// Removes all toasts
214+
215+
toast.dismiss();
216+
```
217+
210218
## Keyboard focus
211219

212220
You can focus on the toast area by pressing ⌥/alt + T. You can override it by providing an array of event.code values for each key.

src/state.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@ let toastsCounter = 0;
55

66
class Observer {
77
subscribers: Array<(toast: ExternalToast | ToastToDismiss) => void>;
8+
toasts: Array<ToastT | ToastToDismiss>;
89

910
constructor() {
1011
this.subscribers = [];
12+
this.toasts = [];
1113
}
1214

1315
// We use arrow functions to maintain the correct `this` reference
@@ -22,9 +24,16 @@ class Observer {
2224

2325
publish = (data: ToastT) => {
2426
this.subscribers.forEach((subscriber) => subscriber(data));
27+
this.toasts = [...this.toasts, data];
2528
};
2629

27-
dismiss = (id: number) => {
30+
dismiss = (id?: number) => {
31+
if (!id) {
32+
this.toasts.forEach((toast) => {
33+
this.subscribers.forEach((subscriber) => subscriber({ id: toast.id, dismiss: true }));
34+
});
35+
}
36+
2837
this.subscribers.forEach((subscriber) => subscriber({ id, dismiss: true }));
2938
return id;
3039
};

src/styles.css

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,9 @@
277277
}
278278

279279
[data-sonner-toast][data-removed='true'][data-front='false'][data-swipe-out='false'][data-expanded='false'] {
280+
--y: translateY(40%);
280281
opacity: 0;
282+
transition: transform 500ms, opacity 200ms;
281283
}
282284

283285
/* Bump up the height to make sure hover state doesn't get set to false */

0 commit comments

Comments
 (0)