Skip to content

The open alternative to Salesforce, designed for AI.

Make Toast timing deterministic (#27930)

Raphaël Bosi48372b397302
diff --git a/packages/twenty-docs/snippets/ui/generated/components/feedback/toast.mdx b/packages/twenty-docs/snippets/ui/generated/components/feedback/toast.mdx
index 2f60a827654..283c32a8c5c 100644
--- a/packages/twenty-docs/snippets/ui/generated/components/feedback/toast.mdx
+++ b/packages/twenty-docs/snippets/ui/generated/components/feedback/toast.mdx
@@ -36,7 +36,7 @@
</ParamField>
<ParamField body="duration" type="number" default="6000">
- Milliseconds before onClose is called. The countdown pauses while the pointer is over the toast or keyboard focus is inside it.
+ Milliseconds before onClose is called, defaulting to 6000. Zero keeps the toast open. Changes restart the countdown; live updateToast duration patches restart it even when unchanged. Hover and keyboard focus pause it until both leave.
</ParamField>
<ParamField body="icon" type="ReactNode">
@@ -52,11 +52,11 @@
</ParamField>
<ParamField body="onClose" type="(() =&gt; void)">
- Called when the close button is clicked or the countdown completes. Providing it shows the close button.
+ Called once per mounted toast when the close button is clicked or the countdown completes. Providing it shows the close button.
</ParamField>
<ParamField body="progress" type="number">
- Completion percentage. Providing it disables the countdown.
+ Completion percentage. Providing it disables the countdown. Removing it starts a fresh duration.
</ParamField>
<ParamField body="ref" type="Ref&lt;HTMLDivElement&gt;">
diff --git a/packages/twenty-docs/ui/components/feedback/toast.mdx b/packages/twenty-docs/ui/components/feedback/toast.mdx
index 4219519c5f3..8215a6948d2 100644
--- a/packages/twenty-docs/ui/components/feedback/toast.mdx
+++ b/packages/twenty-docs/ui/components/feedback/toast.mdx
@@ -113,6 +113,28 @@ export const SaveButton = ({ saveRecord, onViewRecord }: SaveButtonProps) => {
`ToastUpdate` requires `id` and accepts partial Toast options. Omitted fields keep their current values. Explicit `undefined` clears an optional field or restores its component default, such as `progress: undefined` or `status: undefined`. Pass `null` to remove a content slot, including `description`, `icon`, or `action`. Setting `cancelLabel: null` hides the cancel control while preserving its callback. Callback changes take effect on the existing notification. `dedupeKey` belongs to enqueueing and cannot be updated.
+## Dismissal timing
+
+The countdown defaults to 6,000 milliseconds. It pauses while the pointer is over the toast or keyboard focus is inside it, and resumes only after both leave. The visual countdown follows the remaining dismissal time. Automatic dismissal also works when reduced motion disables the animation.
+
+<StoryEmbed
+ storyId="ui-feedback-toaster-timing--documentation"
+ title="Toast timing controls"
+ height={400}
+/>
+
+| Operation | Countdown behavior |
+| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
+| Update content, status, actions, or callbacks | Preserve the remaining time. Repeated updates do not extend it. |
+| Supply `duration` to `updateToast` | Start a fresh duration, including when the value is unchanged. `duration: undefined` restores the default and restarts it. |
+| Change a standalone `Toast`'s `duration` prop | Start a fresh duration. Rendering the same value again keeps the remaining time. |
+| Set `duration: 0` | Keep the toast open until it is dismissed. |
+| Supply `progress` | Stop the countdown while progress is present. |
+| Remove `progress` | Start a fresh duration, or keep it open when its duration is zero. |
+| Update while hovered or focused | Apply the same rules, keeping the resulting countdown paused until both pointer and focus leave. |
+
+For example, `updateToast({ id, children: 'Still saving' })` preserves the remaining time, while `updateToast({ id, duration: 6000 })` gives the reader another six seconds. These rules apply to the existing notification without changing its ID or position.
+
## Dismissible notification
```tsx
@@ -141,7 +163,7 @@ export const SaveNotification = () => {
};
```
-`onClose` is called by the close button and when the countdown completes. Remove the toast in that callback. The countdown defaults to 6,000 milliseconds and pauses while the pointer is over the toast or a control inside it has keyboard focus. It resumes when both leave the toast.
+`onClose` is called once by the close button or when the countdown completes. Remove the toast in that callback. Use `duration={0}` for a notification that stays open until dismissal.
## Progress and cancellation
@@ -163,7 +185,7 @@ export const ImportProgress = ({ progress, onCancel }: ImportProgressProps) => (
);
```
-Passing `progress` supplies a percentage and disables the countdown. Cancellation invokes `onCancel`; the parent owns cancellation and removal. `cancelLabel` accepts a React node for the button content. Children, `description`, `icon`, and `action` also accept caller-owned React nodes. Use Twenty UI controls for interactive actions and provide their accessible names.
+Passing `progress` supplies a percentage and disables the countdown. Remove it after the operation finishes to start a fresh duration. Cancellation invokes `onCancel`; the parent owns cancellation and removal. `cancelLabel` accepts a React node for the button content. Children, `description`, `icon`, and `action` also accept caller-owned React nodes. Use Twenty UI controls for interactive actions and provide their accessible names.
## Appearance and announcements
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
index 7422b2ad61c..a1c23713e5d 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
@@ -7,6 +7,9 @@ Preact stories need Preact 11, which passes `ref` to function components as a
regular prop like React 19. Preact 10 hands that ref to the component instance,
so Dropdown-based popups never open there.
The field-controls fixture checks native input/textarea refs and change targets, typed textarea render composition, Field labels and controlled multiline value updates in React and Preact.
+
+The standalone Toast countdown fixture checks remaining time after repeated content updates, zero-duration persistence, manual dismissal, progress suppression and restart, and overlapping hover/focus pauses in React and Preact. It does not cover `updateToast`, `ToastProvider` or `Toaster` in the worker. The SDK snackbar stories check the separate host notification API.
+
Textarea auto-resize remains a renderer limitation. Geometry reads use cached host snapshots, so resetting inline height and reading scrollHeight in the same turn cannot measure the updated layout. These stale reads can also produce cumulative height growth instead of fitting the current content. The field fixture verifies values, refs, events and accessibility without treating incidental height changes as resize acceptance. Standalone Textarea browser checks pass.
NumberField checks locale formatting and localized paste, controlled empty values, uncontrolled typing, bounds, keyboard commits, pointer value changes, callback event details, accessible labels, native forms, refs and render composition in both runtimes. Sequential typing after clearing a formatted value can reset the caret and insert subsequent digits before earlier input. Formatted pointer edits can also restore stale display values when host blur races the worker update. Pointer button release does not emit its commit callback, although host blur can emit an input-blur commit. ScrubArea can enter its scrubbing state, but drag movement and release do not reach the worker window listeners; pointer lock and the custom scrub cursor are also unavailable. These renderer limits apply independently of the standalone React NumberField browser checks.
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-toast-countdown.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-toast-countdown.front-component.tsx
index 0f93b7ec822..178bc1b1475 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-toast-countdown.front-component.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-toast-countdown.front-component.tsx
@@ -9,24 +9,53 @@ import { TwentyUiGalleryCard } from '@/__stories__/shared/front-components/twent
const ToastCountdownExample = () => {
const [isVisible, setIsVisible] = useState(false);
const [closeCount, setCloseCount] = useState(0);
+ const [contentUpdateCount, setContentUpdateCount] = useState(0);
+ const [duration, setDuration] = useState(1600);
+ const [progress, setProgress] = useState<number>();
return (
<TwentyUiGalleryCard title="Toast countdown">
- <Button onClick={() => setIsVisible(true)}>
+ <Button
+ onClick={() => {
+ setContentUpdateCount(0);
+ setDuration(1600);
+ setProgress(undefined);
+ setIsVisible(true);
+ }}
+ >
Show timed notification
</Button>
{isVisible && (
<Toast
status="success"
- duration={1200}
+ duration={duration}
+ progress={progress}
onClose={() => {
setCloseCount((count) => count + 1);
setIsVisible(false);
}}
>
- Changes saved
+ Changes saved: update {contentUpdateCount}
</Toast>
)}
+ <Button
+ disabled={!isVisible}
+ onClick={() => setContentUpdateCount((count) => count + 1)}
+ >
+ Update notification content
+ </Button>
+ <Button disabled={!isVisible} onClick={() => setDuration(0)}>
+ Keep notification open
+ </Button>
+ <Button disabled={!isVisible} onClick={() => setProgress(25)}>
+ Track progress
+ </Button>
+ <Button disabled={!isVisible} onClick={() => setDuration(800)}>
+ Use short duration
+ </Button>
+ <Button disabled={!isVisible} onClick={() => setProgress(undefined)}>
+ Finish progress
+ </Button>
<Text>Closed notifications: {closeCount}</Text>
</TwentyUiGalleryCard>
);
@@ -35,6 +64,7 @@ const ToastCountdownExample = () => {
export default defineFrontComponent({
universalIdentifier: 'deedd53b-4e60-4a2c-abba-c80dd9c66ced',
name: 'twenty-ui-toast-countdown',
- description: 'Toast countdown, hover pause and completion in the sandbox',
+ description:
+ 'Toast remaining time, persistence, progress and overlapping pauses in the sandbox',
component: ToastCountdownExample,
});
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/toastCountdownTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/toastCountdownTest.ts
index 68c1c1ba003..2bb8e9fc615 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/toastCountdownTest.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/toastCountdownTest.ts
@@ -15,13 +15,13 @@ export const toastCountdownTest: TwentyUiGalleryPlayFunction = async ({
const toast = await canvas.findByRole('status');
await userEvent.hover(toast);
- await new Promise((resolve) => setTimeout(resolve, 1500));
+ await new Promise((resolve) => setTimeout(resolve, 1800));
expect(toast).toBeVisible();
expect(canvas.getByText('Closed notifications: 0')).toBeVisible();
await userEvent.tab();
expect(canvas.getByRole('button', { name: 'Close' })).toHaveFocus();
await userEvent.unhover(toast);
- await new Promise((resolve) => setTimeout(resolve, 1500));
+ await new Promise((resolve) => setTimeout(resolve, 1800));
expect(toast).toBeVisible();
expect(canvas.getByText('Closed notifications: 0')).toBeVisible();
await userEvent.tab({ shift: true });
@@ -29,5 +29,60 @@ export const toastCountdownTest: TwentyUiGalleryPlayFunction = async ({
timeout: 3000,
});
expect(canvas.getByText('Closed notifications: 1')).toBeVisible();
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Show timed notification' }),
+ );
+ const updatedToast = await canvas.findByRole('status');
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Update notification content' }),
+ );
+ await canvas.findByText('Changes saved: update 1');
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Update notification content' }),
+ );
+ await canvas.findByText('Changes saved: update 2');
+ await waitFor(() => expect(updatedToast).not.toBeInTheDocument(), {
+ timeout: 1100,
+ });
+ expect(canvas.getByText('Closed notifications: 2')).toBeVisible();
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Show timed notification' }),
+ );
+ const persistentToast = await canvas.findByRole('status');
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Keep notification open' }),
+ );
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Update notification content' }),
+ );
+ await new Promise((resolve) => setTimeout(resolve, 1800));
+ expect(persistentToast).toBeVisible();
+ expect(canvas.getByText('Closed notifications: 2')).toBeVisible();
+ await userEvent.click(canvas.getByRole('button', { name: 'Close' }));
+ await waitFor(() => expect(persistentToast).not.toBeInTheDocument());
+ expect(canvas.getByText('Closed notifications: 3')).toBeVisible();
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Show timed notification' }),
+ );
+ const progressToast = await canvas.findByRole('status');
+ await userEvent.click(canvas.getByRole('button', { name: 'Track progress' }));
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Use short duration' }),
+ );
+ await new Promise((resolve) => setTimeout(resolve, 1800));
+ expect(progressToast).toBeVisible();
+ expect(canvas.getByText('Closed notifications: 3')).toBeVisible();
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Finish progress' }),
+ );
+ await waitFor(() => expect(progressToast).not.toBeInTheDocument(), {
+ timeout: 1800,
+ });
+ expect(canvas.getByText('Closed notifications: 4')).toBeVisible();
expect(errorHandler).not.toHaveBeenCalled();
};
diff --git a/packages/twenty-ui/docs/toastPropDescriptions.ts b/packages/twenty-ui/docs/toastPropDescriptions.ts
index d922fc00bea..bfb2a9bbfdb 100644
--- a/packages/twenty-ui/docs/toastPropDescriptions.ts
+++ b/packages/twenty-ui/docs/toastPropDescriptions.ts
@@ -11,13 +11,14 @@ export const TOAST_PROP_DESCRIPTIONS = {
iconLabel:
'Accessible name of the default icon. Without it, the icon is decorative.',
action: 'Optional footer node, such as a Button with a caller-owned action.',
- progress: 'Completion percentage. Providing it disables the countdown.',
+ progress:
+ 'Completion percentage. Providing it disables the countdown. Removing it starts a fresh duration.',
duration:
- 'Milliseconds before onClose is called. The countdown pauses while the pointer is over the toast or keyboard focus is inside it.',
+ 'Milliseconds before onClose is called, defaulting to 6000. Zero keeps the toast open. Changes restart the countdown; live updateToast duration patches restart it even when unchanged. Hover and keyboard focus pause it until both leave.',
onCancel:
'Called when the cancel button is clicked. Providing it and renderable cancelLabel content shows the button.',
onClose:
- 'Called when the close button is clicked or the countdown completes. Providing it shows the close button.',
+ 'Called once per mounted toast when the close button is clicked or the countdown completes. Providing it shows the close button.',
cancelLabel:
'Cancel button content node. Defaults to Cancel. Pass null to hide the control.',
closeLabel: 'Accessible name of the close button. Defaults to Close.',
diff --git a/packages/twenty-ui/generated/components.docs.json b/packages/twenty-ui/generated/components.docs.json
index 07f451a263e..55deee04361 100644
--- a/packages/twenty-ui/generated/components.docs.json
+++ b/packages/twenty-ui/generated/components.docs.json
@@ -9887,7 +9887,7 @@
"type": "number",
"required": false,
"defaultValue": "6000",
- "description": "Milliseconds before onClose is called. The countdown pauses while the pointer is over the toast or keyboard focus is inside it."
+ "description": "Milliseconds before onClose is called, defaulting to 6000. Zero keeps the toast open. Changes restart the countdown; live updateToast duration patches restart it even when unchanged. Hover and keyboard focus pause it until both leave."
},
{
"name": "icon",
@@ -9915,14 +9915,14 @@
"type": "(() => void)",
"required": false,
"defaultValue": null,
- "description": "Called when the close button is clicked or the countdown completes. Providing it shows the close button."
+ "description": "Called once per mounted toast when the close button is clicked or the countdown completes. Providing it shows the close button."
},
{
"name": "progress",
"type": "number",
"required": false,
"defaultValue": null,
- "description": "Completion percentage. Providing it disables the countdown."
+ "description": "Completion percentage. Providing it disables the countdown. Removing it starts a fresh duration."
},
{
"name": "ref",
diff --git a/packages/twenty-ui/src/components/feedback/Toast/Toast.tsx b/packages/twenty-ui/src/components/feedback/Toast/Toast.tsx
index d0ca60743e5..5211be8af8f 100644
--- a/packages/twenty-ui/src/components/feedback/Toast/Toast.tsx
+++ b/packages/twenty-ui/src/components/feedback/Toast/Toast.tsx
@@ -16,7 +16,10 @@ import { isRenderableSlot } from '@ui/utilities/internal/isRenderableSlot';
import { isDefined } from '@ui/utilities/utils/isDefined';
import styles from './Toast.module.scss';
+import { ToastCountdownEffect } from './internal/components/ToastCountdownEffect';
+import { ToastFocusEffect } from './internal/components/ToastFocusEffect';
import { ToastProgress } from './internal/components/ToastProgress';
+import { useToastCountdown } from './internal/hooks/useToastCountdown';
import { type ToastProps } from './types/ToastProps';
import { type ToastStatus } from './types/ToastStatus';
@@ -54,6 +57,13 @@ export const Toast = ({
const theme = useTheme();
const [isHovered, setIsHovered] = useState(false);
const [isFocused, setIsFocused] = useState(false);
+ const [toastElement, setToastElement] = useState<HTMLDivElement | null>(null);
+
+ const isPaused = isHovered || isFocused;
+ const { countdown, clock } = useToastCountdown({
+ duration,
+ isPaused,
+ });
const Icon = TOAST_ICONS[status];
const toastColors = theme.snackBar[status === 'neutral' ? 'default' : status];
const toastIcon = isUndefined(icon) ? (
@@ -67,9 +77,9 @@ export const Toast = ({
icon
);
- return useRender({
+ const element = useRender({
render,
- ref,
+ ref: [ref ?? null, setToastElement],
props: {
role,
'aria-live': role === 'alert' ? 'assertive' : 'polite',
@@ -104,9 +114,10 @@ export const Toast = ({
<ToastProgress
barColor={toastColors.backgroundColor}
progress={progress}
- duration={duration}
- isPaused={isHovered || isFocused}
- onClose={onClose}
+ duration={countdown.duration}
+ remainingDuration={countdown.remainingDuration}
+ revision={countdown.revision}
+ isPaused={countdown.isPaused}
/>
</div>
<div className={styles.header}>
@@ -133,7 +144,7 @@ export const Toast = ({
className={styles.closeButton}
variant="ghost"
size="sm"
- onClick={onClose}
+ onClick={clock.close}
/>
)}
</div>
@@ -151,4 +162,22 @@ export const Toast = ({
),
},
});
+
+ return (
+ <>
+ {element}
+ <ToastFocusEffect
+ element={toastElement}
+ isFocused={isFocused}
+ onFocusChange={setIsFocused}
+ />
+ <ToastCountdownEffect
+ clock={clock}
+ duration={duration}
+ progress={progress}
+ isPaused={isPaused}
+ onClose={onClose}
+ />
+ </>
+ );
};
diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastCountdownEffect.tsx b/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastCountdownEffect.tsx
new file mode 100644
index 00000000000..e6352ef0577
--- /dev/null
+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastCountdownEffect.tsx
@@ -0,0 +1,47 @@
+import { useContext, useLayoutEffect } from 'react';
+
+import { isDefined } from '@ui/utilities/utils/isDefined';
+
+import { type ToastProps } from '../../types/ToastProps';
+import { ToastTimingContext } from '../contexts/ToastTimingContext';
+import { type createToastCountdown } from '../utils/createToastCountdown';
+
+type ToastCountdownEffectProps = Pick<ToastProps, 'progress' | 'onClose'> & {
+ clock: ReturnType<typeof createToastCountdown>;
+ duration: number;
+ isPaused: boolean;
+};
+
+export const ToastCountdownEffect = ({
+ clock,
+ duration,
+ progress,
+ isPaused,
+ onClose,
+}: ToastCountdownEffectProps) => {
+ const { durationRevision, isActive } = useContext(ToastTimingContext);
+ const isProgress = isDefined(progress);
+
+ useLayoutEffect(() => {
+ clock.update({
+ duration,
+ durationRevision,
+ isPaused,
+ isProgress,
+ isActive,
+ onClose,
+ });
+ }, [
+ clock,
+ duration,
+ durationRevision,
+ isPaused,
+ isProgress,
+ isActive,
+ onClose,
+ ]);
+
+ useLayoutEffect(() => () => clock.stop(), [clock]);
+
+ return null;
+};
diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastFocusEffect.tsx b/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastFocusEffect.tsx
new file mode 100644
index 00000000000..373e923f496
--- /dev/null
+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastFocusEffect.tsx
@@ -0,0 +1,40 @@
+import { useLayoutEffect } from 'react';
+
+import { isDefined } from '@ui/utilities/utils/isDefined';
+
+type ToastFocusEffectProps = {
+ element: HTMLDivElement | null;
+ isFocused: boolean;
+ onFocusChange: (isFocused: boolean) => void;
+};
+
+export const ToastFocusEffect = ({
+ element,
+ isFocused,
+ onFocusChange,
+}: ToastFocusEffectProps) => {
+ useLayoutEffect(() => {
+ if (!isFocused || !isDefined(element)) {
+ return;
+ }
+
+ const reconcileFocus = () => {
+ const isFocusInsideToast = element.contains(
+ element.ownerDocument.activeElement,
+ );
+
+ if (!isFocusInsideToast) {
+ onFocusChange(false);
+ }
+ };
+
+ reconcileFocus();
+
+ const observer = new MutationObserver(reconcileFocus);
+ observer.observe(element, { childList: true, subtree: true });
+
+ return () => observer.disconnect();
+ }, [element, isFocused, onFocusChange]);
+
+ return null;
+};
diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastProgress.module.scss b/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastProgress.module.scss
index 07b2db0bbc5..86441feaa11 100644
--- a/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastProgress.module.scss
+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastProgress.module.scss
@@ -2,6 +2,11 @@
animation: toastCountdown var(--toast-countdown-duration) linear forwards;
background-color: var(--toast-countdown-color);
height: 100%;
+ width: var(--toast-countdown-width);
+
+ @media (prefers-reduced-motion: reduce) {
+ display: none;
+ }
&[data-paused] {
animation-play-state: paused;
@@ -10,7 +15,7 @@
@keyframes toastCountdown {
from {
- width: 100%;
+ width: var(--toast-countdown-width);
}
to {
diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastProgress.tsx b/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastProgress.tsx
index b0302b693ba..d40089ab67c 100644
--- a/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastProgress.tsx
+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastProgress.tsx
@@ -3,36 +3,44 @@ import { type CSSProperties } from 'react';
import { ProgressBar } from '@ui/primitives/feedback/ProgressBar/ProgressBar';
import { isDefined } from '@ui/utilities/utils/isDefined';
+import { isCountdownDuration } from '../utils/isCountdownDuration';
import styles from './ToastProgress.module.scss';
type ToastProgressProps = {
progress?: number;
duration: number;
+ remainingDuration: number;
+ revision: number;
isPaused: boolean;
barColor: string;
- onClose?: () => void;
};
export const ToastProgress = ({
progress,
duration,
+ remainingDuration,
+ revision,
isPaused,
barColor,
- onClose,
}: ToastProgressProps) => {
if (isDefined(progress)) {
return <ProgressBar value={progress} barColor={barColor} />;
}
+ if (!isCountdownDuration(duration)) {
+ return null;
+ }
+
return (
<div
+ key={revision}
className={styles.countdown}
data-paused={isPaused || undefined}
- onAnimationEnd={onClose}
style={
{
'--toast-countdown-color': barColor,
- '--toast-countdown-duration': `${duration}ms`,
+ '--toast-countdown-width': `${(remainingDuration / duration) * 100}%`,
+ '--toast-countdown-duration': `${remainingDuration}ms`,
} as CSSProperties
}
/>
diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/contexts/ToastTimingContext.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/contexts/ToastTimingContext.ts
new file mode 100644
index 00000000000..e666bc80992
--- /dev/null
+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/contexts/ToastTimingContext.ts
@@ -0,0 +1,6 @@
+import { createContext } from 'react';
+
+export const ToastTimingContext = createContext({
+ durationRevision: 0,
+ isActive: true,
+});
diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/hooks/useToastCountdown.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/hooks/useToastCountdown.ts
new file mode 100644
index 00000000000..82151b912ba
--- /dev/null
+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/hooks/useToastCountdown.ts
@@ -0,0 +1,23 @@
+import { useState } from 'react';
+
+import { createToastCountdown } from '../utils/createToastCountdown';
+
+export const useToastCountdown = ({
+ duration,
+ isPaused,
+}: {
+ duration: number;
+ isPaused: boolean;
+}) => {
+ const [countdown, setCountdown] = useState({
+ duration,
+ remainingDuration: duration,
+ revision: 0,
+ isPaused,
+ });
+ const [clock] = useState(() =>
+ createToastCountdown({ onChange: setCountdown }),
+ );
+
+ return { countdown, clock };
+};
diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/types/ToastEntry.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/types/ToastEntry.ts
index e4ad98b6bff..fb5f6c89d3d 100644
--- a/packages/twenty-ui/src/components/feedback/Toast/internal/types/ToastEntry.ts
+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/types/ToastEntry.ts
@@ -3,5 +3,6 @@ import { type ToastNotification } from '../../types/ToastNotification';
export type ToastEntry = {
notification: ToastNotification;
dedupeKey?: string;
+ durationRevision?: number;
status: 'visible' | 'closing';
};
diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/__tests__/createToastCountdown.test.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/__tests__/createToastCountdown.test.ts
new file mode 100644
index 00000000000..e19f4e06826
--- /dev/null
+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/__tests__/createToastCountdown.test.ts
@@ -0,0 +1,326 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+import { createToastCountdown } from '../createToastCountdown';
+
+const DEFAULT_CONFIGURATION = {
+ duration: 1000,
+ durationRevision: 0,
+ isPaused: false,
+ isProgress: false,
+ isActive: true,
+};
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+});
+
+it('preserves the original expiry through repeated unchanged updates and uses the latest callback', () => {
+ const onChange = vi.fn();
+ const onClose = vi.fn();
+ const updatedClose = vi.fn();
+ const countdown = createToastCountdown({ onChange });
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose });
+
+ vi.advanceTimersByTime(400);
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose: updatedClose });
+ vi.advanceTimersByTime(400);
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose: updatedClose });
+ expect(onChange).toHaveBeenCalledOnce();
+ vi.advanceTimersByTime(199);
+ expect(updatedClose).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+
+ expect(updatedClose).toHaveBeenCalledOnce();
+ expect(onClose).not.toHaveBeenCalled();
+ expect(onChange).toHaveBeenLastCalledWith(
+ expect.objectContaining({ remainingDuration: 0 }),
+ );
+});
+
+it('restarts every explicit duration revision even when the duration stays unchanged', () => {
+ const onChange = vi.fn();
+ const onClose = vi.fn();
+ const countdown = createToastCountdown({ onChange });
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose });
+
+ vi.advanceTimersByTime(400);
+ countdown.update({
+ ...DEFAULT_CONFIGURATION,
+ durationRevision: 1,
+ onClose,
+ });
+ vi.advanceTimersByTime(400);
+ countdown.update({
+ ...DEFAULT_CONFIGURATION,
+ durationRevision: 2,
+ onClose,
+ });
+ expect(onChange).toHaveBeenLastCalledWith(
+ expect.objectContaining({ duration: 1000, remainingDuration: 1000 }),
+ );
+ vi.advanceTimersByTime(999);
+ expect(onClose).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+
+ expect(onClose).toHaveBeenCalledOnce();
+});
+
+it('starts a fresh countdown when the duration prop changes', () => {
+ const onClose = vi.fn();
+ const countdown = createToastCountdown({ onChange: vi.fn() });
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose });
+
+ vi.advanceTimersByTime(400);
+ countdown.update({ ...DEFAULT_CONFIGURATION, duration: 600, onClose });
+ vi.advanceTimersByTime(599);
+ expect(onClose).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+
+ expect(onClose).toHaveBeenCalledOnce();
+});
+
+it('cancels obsolete expiry when duration becomes zero and starts fresh when persistence ends', () => {
+ const onClose = vi.fn();
+ const countdown = createToastCountdown({ onChange: vi.fn() });
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose });
+
+ vi.advanceTimersByTime(400);
+ countdown.update({ ...DEFAULT_CONFIGURATION, duration: 0, onClose });
+ expect(vi.getTimerCount()).toBe(0);
+ vi.advanceTimersByTime(10_000);
+ countdown.update({ ...DEFAULT_CONFIGURATION, duration: 0, onClose });
+ expect(onClose).not.toHaveBeenCalled();
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose });
+ vi.advanceTimersByTime(999);
+ expect(onClose).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+
+ expect(onClose).toHaveBeenCalledOnce();
+});
+
+it('disables expiry throughout progress updates and starts the latest full duration on leaving progress', () => {
+ const onChange = vi.fn();
+ const onClose = vi.fn();
+ const countdown = createToastCountdown({ onChange });
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose });
+
+ vi.advanceTimersByTime(400);
+ countdown.update({ ...DEFAULT_CONFIGURATION, isProgress: true, onClose });
+ expect(vi.getTimerCount()).toBe(0);
+ vi.advanceTimersByTime(10_000);
+ countdown.update({
+ ...DEFAULT_CONFIGURATION,
+ duration: 600,
+ durationRevision: 1,
+ isProgress: true,
+ onClose,
+ });
+ vi.advanceTimersByTime(10_000);
+ expect(onClose).not.toHaveBeenCalled();
+ countdown.update({
+ ...DEFAULT_CONFIGURATION,
+ duration: 600,
+ durationRevision: 1,
+ onClose,
+ });
+ expect(onChange).toHaveBeenLastCalledWith(
+ expect.objectContaining({ remainingDuration: 600 }),
+ );
+ vi.advanceTimersByTime(599);
+ expect(onClose).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+
+ expect(onClose).toHaveBeenCalledOnce();
+});
+
+it('keeps zero-duration notifications persistent after leaving progress', () => {
+ const onClose = vi.fn();
+ const countdown = createToastCountdown({ onChange: vi.fn() });
+ countdown.update({
+ ...DEFAULT_CONFIGURATION,
+ duration: 0,
+ isProgress: true,
+ onClose,
+ });
+ countdown.update({ ...DEFAULT_CONFIGURATION, duration: 0, onClose });
+ vi.advanceTimersByTime(10_000);
+
+ expect(onClose).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+});
+
+it('preserves remaining time through repeated paused updates and resumes from that remainder', () => {
+ const onChange = vi.fn();
+ const onClose = vi.fn();
+ const countdown = createToastCountdown({ onChange });
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose });
+
+ vi.advanceTimersByTime(400);
+ countdown.update({ ...DEFAULT_CONFIGURATION, isPaused: true, onClose });
+ vi.advanceTimersByTime(10_000);
+ countdown.update({ ...DEFAULT_CONFIGURATION, isPaused: true, onClose });
+ vi.advanceTimersByTime(10_000);
+ expect(onChange).toHaveBeenLastCalledWith(
+ expect.objectContaining({ remainingDuration: 600, isPaused: true }),
+ );
+ expect(onClose).not.toHaveBeenCalled();
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose });
+ vi.advanceTimersByTime(599);
+ expect(onClose).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+
+ expect(onClose).toHaveBeenCalledOnce();
+});
+
+it('keeps restarted duration and progress-exit countdowns suspended while paused', () => {
+ const onChange = vi.fn();
+ const onClose = vi.fn();
+ const countdown = createToastCountdown({ onChange });
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose });
+
+ vi.advanceTimersByTime(400);
+ countdown.update({ ...DEFAULT_CONFIGURATION, isPaused: true, onClose });
+ countdown.update({
+ ...DEFAULT_CONFIGURATION,
+ durationRevision: 1,
+ isPaused: true,
+ onClose,
+ });
+ vi.advanceTimersByTime(10_000);
+ expect(onChange).toHaveBeenLastCalledWith(
+ expect.objectContaining({ remainingDuration: 1000, isPaused: true }),
+ );
+ countdown.update({
+ ...DEFAULT_CONFIGURATION,
+ durationRevision: 1,
+ isPaused: true,
+ isProgress: true,
+ onClose,
+ });
+ countdown.update({
+ ...DEFAULT_CONFIGURATION,
+ durationRevision: 1,
+ isPaused: true,
+ onClose,
+ });
+ vi.advanceTimersByTime(10_000);
+ expect(onClose).not.toHaveBeenCalled();
+ countdown.update({
+ ...DEFAULT_CONFIGURATION,
+ durationRevision: 1,
+ onClose,
+ });
+ vi.advanceTimersByTime(999);
+ expect(onClose).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+
+ expect(onClose).toHaveBeenCalledOnce();
+});
+
+it.each([
+ { mode: 'paused', isPaused: true, isProgress: false },
+ { mode: 'progress', isPaused: false, isProgress: true },
+])(
+ 'updates the callback without republishing an unchanged $mode snapshot',
+ ({ isPaused, isProgress }) => {
+ const onChange = vi.fn();
+ const onClose = vi.fn();
+ const updatedClose = vi.fn();
+ const countdown = createToastCountdown({ onChange });
+ countdown.update({
+ ...DEFAULT_CONFIGURATION,
+ isPaused,
+ isProgress,
+ onClose,
+ });
+ onChange.mockClear();
+
+ countdown.update({
+ ...DEFAULT_CONFIGURATION,
+ isPaused,
+ isProgress,
+ onClose: updatedClose,
+ });
+
+ expect(onChange).not.toHaveBeenCalled();
+ countdown.close();
+ expect(updatedClose).toHaveBeenCalledOnce();
+ expect(onClose).not.toHaveBeenCalled();
+ },
+);
+
+it('dismisses manually once and prevents later updates from reviving expiry', () => {
+ const onClose = vi.fn();
+ const countdown = createToastCountdown({ onChange: vi.fn() });
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose });
+
+ vi.advanceTimersByTime(400);
+ countdown.close();
+ countdown.close();
+ countdown.update({
+ ...DEFAULT_CONFIGURATION,
+ durationRevision: 1,
+ onClose,
+ });
+ vi.advanceTimersByTime(10_000);
+
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+});
+
+it('cancels expiry when the toast becomes inactive', () => {
+ const onClose = vi.fn();
+ const countdown = createToastCountdown({ onChange: vi.fn() });
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose });
+
+ vi.advanceTimersByTime(400);
+ countdown.update({ ...DEFAULT_CONFIGURATION, isActive: false, onClose });
+ countdown.update({
+ ...DEFAULT_CONFIGURATION,
+ durationRevision: 1,
+ isActive: false,
+ onClose,
+ });
+ vi.advanceTimersByTime(10_000);
+
+ expect(onClose).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+});
+
+it('stops scheduled work without dismissing and can resume after effect setup runs again', () => {
+ const onClose = vi.fn();
+ const countdown = createToastCountdown({ onChange: vi.fn() });
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose });
+
+ vi.advanceTimersByTime(400);
+ countdown.stop();
+ expect(vi.getTimerCount()).toBe(0);
+ vi.advanceTimersByTime(10_000);
+ expect(onClose).not.toHaveBeenCalled();
+ countdown.update({ ...DEFAULT_CONFIGURATION, onClose });
+ vi.advanceTimersByTime(599);
+ expect(onClose).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+
+ expect(onClose).toHaveBeenCalledOnce();
+});
+
+it('schedules long durations in safe chunks without expiring early', () => {
+ const onClose = vi.fn();
+ const countdown = createToastCountdown({ onChange: vi.fn() });
+ const duration = 2 ** 31 + 500;
+ countdown.update({ ...DEFAULT_CONFIGURATION, duration, onClose });
+
+ vi.advanceTimersByTime(2 ** 31 - 1);
+ expect(onClose).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(500);
+ expect(onClose).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+
+ expect(onClose).toHaveBeenCalledOnce();
+});
diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/__tests__/updateToastInStore.test.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/__tests__/updateToastInStore.test.ts
index b4ff296b679..cc326a28021 100644
--- a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/__tests__/updateToastInStore.test.ts
+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/__tests__/updateToastInStore.test.ts
@@ -149,4 +149,46 @@ it('does not publish empty patches but keeps explicit unchanged duration updates
updateToastInStore({ store, id: 'first', duration: 6000 });
expect(listener).toHaveBeenCalledOnce();
+ expect(store.state.toasts[0]?.durationRevision).toBe(1);
+
+ updateToastInStore({ store, id: 'first', duration: 6000 });
+ expect(store.state.toasts[0]?.durationRevision).toBe(2);
+
+ updateToastInStore({ store, id: 'first', children: 'Updated content' });
+ expect(store.state.toasts[0]?.durationRevision).toBe(2);
+});
+
+it('restarts duration when an explicit undefined patch restores its default', () => {
+ const { store } = createStoreWithToasts();
+
+ updateToastInStore({ store, id: 'first', duration: undefined });
+ expect(store.state.toasts[0]?.durationRevision).toBe(1);
+ expect(store.state.toasts[0]?.notification.duration).toBeUndefined();
+
+ updateToastInStore({ store, id: 'first', duration: undefined });
+ expect(store.state.toasts[0]?.durationRevision).toBe(2);
+});
+
+it('preserves countdown restart operations when progress entry and exit are batched before rendering', () => {
+ const { store } = createStoreWithToasts();
+
+ updateToastInStore({ store, id: 'first', progress: 0 });
+ updateToastInStore({ store, id: 'first', progress: 50 });
+ expect(store.state.toasts[0]?.durationRevision).toBeUndefined();
+
+ updateToastInStore({ store, id: 'first', progress: undefined });
+ expect(store.state.toasts[0]?.durationRevision).toBe(1);
+ expect(store.state.toasts[0]?.notification.progress).toBeUndefined();
+
+ updateToastInStore({ store, id: 'first', progress: undefined });
+ expect(store.state.toasts[0]?.durationRevision).toBe(1);
+
+ updateToastInStore({ store, id: 'first', progress: 100 });
+ updateToastInStore({
+ store,
+ id: 'first',
+ progress: undefined,
+ duration: 6000,
+ });
+ expect(store.state.toasts[0]?.durationRevision).toBe(2);
});
diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/createToastCountdown.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/createToastCountdown.ts
new file mode 100644
index 00000000000..dacc7395baa
--- /dev/null
+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/createToastCountdown.ts
@@ -0,0 +1,138 @@
+import { isDefined } from '@ui/utilities/utils/isDefined';
+
+import { isCountdownDuration } from './isCountdownDuration';
+
+type CountdownConfiguration = {
+ duration: number;
+ durationRevision: number;
+ isPaused: boolean;
+ isProgress: boolean;
+ isActive: boolean;
+ onClose?: () => void;
+};
+
+type CountdownSnapshot = {
+ duration: number;
+ remainingDuration: number;
+ revision: number;
+ isPaused: boolean;
+};
+
+const MAX_TIMEOUT_DURATION = 2 ** 31 - 1;
+
+export const createToastCountdown = ({
+ onChange,
+}: {
+ onChange: (snapshot: CountdownSnapshot) => void;
+}) => {
+ let configuration: CountdownConfiguration | undefined;
+ let remainingDuration = 0;
+ let startedAt: number | undefined;
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ let revision = 0;
+ let isClosed = false;
+
+ const stop = () => {
+ if (isDefined(startedAt)) {
+ remainingDuration = Math.max(
+ 0,
+ remainingDuration - (performance.now() - startedAt),
+ );
+ startedAt = undefined;
+ }
+
+ clearTimeout(timeout);
+ timeout = undefined;
+ };
+
+ const publish = () => {
+ if (!isDefined(configuration)) {
+ return;
+ }
+
+ revision += 1;
+ onChange({
+ duration: configuration.duration,
+ remainingDuration,
+ revision,
+ isPaused: configuration.isPaused || !configuration.isActive,
+ });
+ };
+
+ const close = () => {
+ if (isClosed) {
+ return;
+ }
+
+ stop();
+ isClosed = true;
+ remainingDuration = 0;
+ publish();
+ configuration?.onClose?.();
+ };
+
+ const isCountdownEnabled = () =>
+ isDefined(configuration) &&
+ configuration.isActive &&
+ !configuration.isPaused &&
+ !configuration.isProgress &&
+ isCountdownDuration(configuration.duration) &&
+ !isClosed;
+
+ const start = () => {
+ if (!isCountdownEnabled()) {
+ return;
+ }
+
+ startedAt = performance.now();
+ timeout = setTimeout(
+ () => {
+ stop();
+
+ if (remainingDuration > 0) {
+ start();
+ return;
+ }
+
+ close();
+ },
+ Math.min(remainingDuration, MAX_TIMEOUT_DURATION),
+ );
+ };
+
+ const update = (nextConfiguration: CountdownConfiguration) => {
+ const shouldRestart =
+ !isDefined(configuration) ||
+ nextConfiguration.duration !== configuration.duration ||
+ nextConfiguration.durationRevision !== configuration.durationRevision ||
+ (configuration.isProgress && !nextConfiguration.isProgress);
+ const hasTimingChanged =
+ shouldRestart ||
+ nextConfiguration.isProgress !== configuration?.isProgress ||
+ nextConfiguration.isPaused !== configuration?.isPaused ||
+ nextConfiguration.isActive !== configuration?.isActive;
+
+ const shouldResume = !isDefined(startedAt) && isCountdownEnabled();
+
+ if (!hasTimingChanged && !shouldResume) {
+ configuration = nextConfiguration;
+ return;
+ }
+
+ stop();
+ configuration = nextConfiguration;
+
+ if (isClosed) {
+ return;
+ }
+
+ if (shouldRestart) {
+ remainingDuration = Math.max(0, nextConfiguration.duration);
+ }
+
+ publish();
+ start();
+ };
+
+ return { update, close, stop };
+};
diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/isCountdownDuration.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/isCountdownDuration.ts
new file mode 100644
index 00000000000..afd313ea324
--- /dev/null
+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/isCountdownDuration.ts
@@ -0,0 +1,2 @@
+export const isCountdownDuration = (duration: number) =>
+ Number.isFinite(duration) && duration > 0;
diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/updateToastInStore.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/updateToastInStore.ts
index 8f79b5bd744..88e16e5f371 100644
--- a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/updateToastInStore.ts
+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/updateToastInStore.ts
@@ -15,10 +15,18 @@ export const updateToastInStore = ({
(toast) => toast.notification.id === id && isToastVisible(toast),
);
- if (!isDefined(toastToUpdate) || !isNonEmptyArray(Object.keys(changes))) {
+ const changedFields = Object.keys(changes);
+
+ if (!isDefined(toastToUpdate) || !isNonEmptyArray(changedFields)) {
return;
}
+ const shouldRestartCountdown =
+ changedFields.includes('duration') ||
+ (isDefined(toastToUpdate.notification.progress) &&
+ changedFields.includes('progress') &&
+ !isDefined(changes.progress));
+
store.set(
'toasts',
store.state.toasts.map((toast) =>
@@ -26,6 +34,9 @@ export const updateToastInStore = ({
? {
...toast,
notification: { ...toast.notification, ...changes, id },
+ ...(shouldRestartCountdown
+ ? { durationRevision: (toast.durationRevision ?? 0) + 1 }
+ : {}),
}
: toast,
),
diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/DefaultTimingDuration.ts b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/DefaultTimingDuration.ts
new file mode 100644
index 00000000000..56faf3f8f19
--- /dev/null
+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/DefaultTimingDuration.ts
@@ -0,0 +1 @@
+export const DEFAULT_TIMING_DURATION = 1400;
diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/Toaster.timing.stories.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/Toaster.timing.stories.tsx
new file mode 100644
index 00000000000..697befb94b8
--- /dev/null
+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/Toaster.timing.stories.tsx
@@ -0,0 +1,421 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { StrictMode } from 'react';
+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+
+import { ComponentDecorator } from '@ui/testing';
+
+import { ToasterRootReplacementExample } from './ToasterRootReplacementExample';
+import { ToasterSelfRemovingActionExample } from './ToasterSelfRemovingActionExample';
+import { ToasterTimingExample } from './ToasterTimingExample';
+import { DEFAULT_TIMING_DURATION } from './DefaultTimingDuration';
+import { type ToasterTimingExampleProps } from './ToasterTimingExampleProps';
+
+const meta: Meta<typeof ToasterTimingExample> = {
+ id: 'ui-feedback-toaster-timing',
+ title: 'UI/Components/Feedback/Toaster/Timing',
+ component: ToasterTimingExample,
+ decorators: [ComponentDecorator],
+ args: { duration: DEFAULT_TIMING_DURATION, onCancel: fn(), onClose: fn() },
+ parameters: { container: { width: 600, height: 400 } },
+};
+
+export default meta;
+type Story = StoryObj<typeof ToasterTimingExample>;
+type TimingUser = ReturnType<typeof userEvent.setup>;
+
+const wait = (duration: number) =>
+ new Promise((resolve) => setTimeout(resolve, duration));
+
+const addNotification = async ({
+ canvasElement,
+ isPersistent = false,
+}: {
+ canvasElement: HTMLElement;
+ isPersistent?: boolean;
+}) => {
+ const user = userEvent.setup();
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+ await user.click(
+ canvas.getByRole('button', {
+ name: isPersistent
+ ? 'Add persistent notification'
+ : 'Add timed notification',
+ }),
+ );
+ const toast = body.getByRole('status');
+ await waitFor(() => expect(toast).toBeVisible());
+
+ return { canvas, body, toast, user };
+};
+
+const expectExpiry = async ({
+ toast,
+ onClose,
+ timeout = 2400,
+}: {
+ toast: HTMLElement;
+ onClose: ToasterTimingExampleProps['onClose'];
+ timeout?: number;
+}) => {
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce(), { timeout });
+ await waitFor(() => expect(toast).not.toBeInTheDocument());
+};
+
+const resumeCountdown = async ({
+ canvas,
+ toast,
+ user,
+}: {
+ canvas: ReturnType<typeof within>;
+ toast: HTMLElement;
+ user: TimingUser;
+}) => {
+ const outside = canvas.getByRole('button', { name: 'Outside toast' });
+ await user.click(outside);
+ expect(outside).toHaveFocus();
+ expect(toast.contains(toast.ownerDocument.activeElement)).toBe(false);
+};
+
+export const Documentation: Story = {};
+
+export const StrictModeCountdown: Story = {
+ render: (args) => (
+ <StrictMode>
+ <ToasterTimingExample {...args} />
+ </StrictMode>
+ ),
+ play: async ({ canvasElement, args }) => {
+ const { toast } = await addNotification({ canvasElement });
+ await wait(450);
+ expect(toast).toBeVisible();
+ expect(args.onClose).not.toHaveBeenCalled();
+ await expectExpiry({ toast, onClose: args.onClose });
+ },
+};
+
+export const ContentUpdatesPreserveRemainingTime: Story = {
+ play: async ({ canvasElement, args }) => {
+ const { canvas, body, toast, user } = await addNotification({
+ canvasElement,
+ });
+ const update = canvas.getByRole('button', { name: 'Update content' });
+ await wait(450);
+ await user.click(update);
+ expect(toast).toHaveTextContent('Content update 1');
+ await wait(450);
+ await user.click(update);
+ expect(body.getByRole('status')).toBe(toast);
+ expect(toast).toHaveTextContent('Content update 2');
+ await expectExpiry({ toast, onClose: args.onClose, timeout: 900 });
+ },
+};
+
+export const SameDurationUpdatesRestart: Story = {
+ play: async ({ canvasElement, args }) => {
+ const { canvas, body, toast, user } = await addNotification({
+ canvasElement,
+ });
+ const restart = canvas.getByRole('button', { name: 'Restart countdown' });
+ await wait(900);
+ await user.click(restart);
+ await wait(900);
+ expect(toast).toBeVisible();
+ await user.click(restart);
+ await wait(900);
+ expect(body.getByRole('status')).toBe(toast);
+ expect(args.onClose).not.toHaveBeenCalled();
+ await expectExpiry({ toast, onClose: args.onClose, timeout: 1000 });
+ },
+};
+
+export const ZeroDurationCancelsExpiry: Story = {
+ play: async ({ canvasElement, args }) => {
+ const { canvas, toast, user } = await addNotification({ canvasElement });
+ await wait(450);
+ await user.click(canvas.getByRole('button', { name: 'Make persistent' }));
+ await wait(1600);
+ await user.click(canvas.getByRole('button', { name: 'Update content' }));
+ await user.click(canvas.getByRole('button', { name: 'Update content' }));
+ expect(toast).toHaveTextContent('Content update 2');
+ expect(toast).toBeVisible();
+ expect(args.onClose).not.toHaveBeenCalled();
+ await user.click(canvas.getByRole('button', { name: 'Restart countdown' }));
+ await expectExpiry({ toast, onClose: args.onClose });
+ },
+};
+
+export const PersistentNotificationStartsCountdown: Story = {
+ play: async ({ canvasElement, args }) => {
+ const { canvas, toast, user } = await addNotification({
+ canvasElement,
+ isPersistent: true,
+ });
+ await wait(1600);
+ expect(toast).toBeVisible();
+ expect(args.onClose).not.toHaveBeenCalled();
+ await user.click(canvas.getByRole('button', { name: 'Restart countdown' }));
+ await wait(900);
+ expect(toast).toBeVisible();
+ await expectExpiry({ toast, onClose: args.onClose, timeout: 1000 });
+ },
+};
+
+export const ProgressCancelsAndRestartsCountdown: Story = {
+ play: async ({ canvasElement, args }) => {
+ const { canvas, toast, user } = await addNotification({ canvasElement });
+ await wait(450);
+ await user.click(canvas.getByRole('button', { name: 'Enter progress' }));
+ await wait(1600);
+ await user.click(canvas.getByRole('button', { name: 'Update progress' }));
+ expect(
+ within(toast).getByRole('progressbar', { hidden: true }),
+ ).toHaveAttribute('aria-valuenow', '75');
+ expect(args.onClose).not.toHaveBeenCalled();
+ await user.click(canvas.getByRole('button', { name: 'Leave progress' }));
+ await wait(1100);
+ expect(toast).toBeVisible();
+ expect(args.onClose).not.toHaveBeenCalled();
+ await expectExpiry({ toast, onClose: args.onClose, timeout: 800 });
+ },
+};
+
+export const HoverAndFocusPauseIndependently: Story = {
+ play: async ({ canvasElement, args }) => {
+ const { canvas, toast, user } = await addNotification({ canvasElement });
+ await wait(450);
+ const cancel = within(toast).getByRole('button', { name: 'Keep working' });
+ await user.click(cancel);
+ expect(cancel).toHaveFocus();
+ expect(args.onCancel).toHaveBeenCalledOnce();
+ await user.unhover(toast);
+ await wait(1600);
+ expect(toast).toBeVisible();
+ expect(args.onClose).not.toHaveBeenCalled();
+ await user.tab();
+ expect(within(toast).getByRole('button', { name: 'Close' })).toHaveFocus();
+ await wait(1600);
+ expect(toast).toBeVisible();
+ await user.tab({ shift: true });
+ await user.hover(toast);
+ await user.tab({ shift: true });
+ expect(canvas.getByRole('button', { name: 'Outside toast' })).toHaveFocus();
+ await wait(1600);
+ expect(toast).toBeVisible();
+ expect(args.onClose).not.toHaveBeenCalled();
+ await user.unhover(toast);
+ await expectExpiry({ toast, onClose: args.onClose, timeout: 1500 });
+ },
+};
+
+export const ContentUpdatesWhilePausedPreserveRemainingTime: Story = {
+ play: async ({ canvasElement, args }) => {
+ const { canvas, toast, user } = await addNotification({ canvasElement });
+ await wait(800);
+ const update = within(toast).getByRole('button', {
+ name: 'Update paused content',
+ });
+ await user.click(update);
+ await wait(1600);
+ await user.click(update);
+ expect(update).toHaveFocus();
+ expect(toast).toHaveTextContent('Paused content update 2');
+ expect(args.onClose).not.toHaveBeenCalled();
+ await resumeCountdown({ canvas, toast, user });
+ await expectExpiry({ toast, onClose: args.onClose, timeout: 1000 });
+ },
+};
+
+export const DurationUpdatesWhilePausedRestart: Story = {
+ play: async ({ canvasElement, args }) => {
+ const { canvas, toast, user } = await addNotification({ canvasElement });
+ await wait(800);
+ const restart = within(toast).getByRole('button', {
+ name: 'Restart paused countdown',
+ });
+ await user.click(restart);
+ await wait(1600);
+ await user.click(restart);
+ await wait(1600);
+ expect(restart).toHaveFocus();
+ expect(toast).toBeVisible();
+ expect(args.onClose).not.toHaveBeenCalled();
+ await resumeCountdown({ canvas, toast, user });
+ await wait(900);
+ expect(toast).toBeVisible();
+ expect(args.onClose).not.toHaveBeenCalled();
+ await expectExpiry({ toast, onClose: args.onClose, timeout: 1000 });
+ },
+};
+
+export const ProgressExitWhilePausedStartsFreshDuration: Story = {
+ play: async ({ canvasElement, args }) => {
+ const { canvas, toast, user } = await addNotification({ canvasElement });
+ await wait(800);
+ await user.click(
+ within(toast).getByRole('button', { name: 'Enter paused progress' }),
+ );
+ await wait(1600);
+ await user.click(
+ within(toast).getByRole('button', { name: 'Leave paused progress' }),
+ );
+ await wait(1600);
+ expect(toast).toBeVisible();
+ expect(args.onClose).not.toHaveBeenCalled();
+ await resumeCountdown({ canvas, toast, user });
+ await wait(900);
+ expect(toast).toBeVisible();
+ await expectExpiry({ toast, onClose: args.onClose, timeout: 1000 });
+ },
+};
+
+export const RemovingFocusedActionsResumesCountdown: Story = {
+ play: async ({ canvasElement, args }) => {
+ const { toast, user } = await addNotification({ canvasElement });
+ await wait(800);
+ await user.click(
+ within(toast).getByRole('button', { name: 'Update paused content' }),
+ );
+ await wait(1600);
+ await user.click(
+ within(toast).getByRole('button', { name: 'Remove focused actions' }),
+ );
+ expect(toast.contains(toast.ownerDocument.activeElement)).toBe(false);
+ await user.hover(toast);
+ await user.unhover(toast);
+ expect(
+ within(toast).queryByRole('button', { name: 'Remove focused actions' }),
+ ).not.toBeInTheDocument();
+ await expectExpiry({ toast, onClose: args.onClose, timeout: 1000 });
+ },
+};
+
+export const NestedFocusedActionRemovalResumesCountdown: Story = {
+ render: (args) => <ToasterSelfRemovingActionExample {...args} />,
+ play: async ({ canvasElement, args }) => {
+ const { toast, user } = await addNotification({ canvasElement });
+ await wait(800);
+ const action = within(toast).getByRole('button', {
+ name: 'Remove this focused action',
+ });
+ await user.tab();
+ await user.tab();
+ expect(action).toHaveFocus();
+ await wait(1600);
+ expect(toast).toBeVisible();
+ expect(args.onClose).not.toHaveBeenCalled();
+ await user.keyboard('{Enter}');
+ expect(action).not.toBeInTheDocument();
+ expect(toast.contains(toast.ownerDocument.activeElement)).toBe(false);
+ await expectExpiry({ toast, onClose: args.onClose, timeout: 1000 });
+ },
+};
+
+export const FocusedRootReplacementResumesCountdown: Story = {
+ render: (args) => <ToasterRootReplacementExample {...args} />,
+ play: async ({ canvasElement, args }) => {
+ const { body, toast, user } = await addNotification({ canvasElement });
+ await wait(800);
+ const action = within(toast).getByRole('button', {
+ name: 'Replace focused toast root',
+ });
+ await user.tab();
+ await user.tab();
+ expect(action).toHaveFocus();
+ await wait(1600);
+ expect(toast).toBeVisible();
+ expect(args.onClose).not.toHaveBeenCalled();
+ await user.keyboard('{Enter}');
+ const replacement = body.getByRole('status');
+ expect(replacement.tagName).toBe('SECTION');
+ expect(toast).not.toBeInTheDocument();
+ expect(replacement.contains(replacement.ownerDocument.activeElement)).toBe(
+ false,
+ );
+ await expectExpiry({
+ toast: replacement,
+ onClose: args.onClose,
+ timeout: 1000,
+ });
+ },
+};
+
+export const ManualDismissalCancelsExpiry: Story = {
+ play: async ({ canvasElement, args }) => {
+ const { canvas, toast, user } = await addNotification({ canvasElement });
+ await wait(450);
+ await user.click(within(toast).getByRole('button', { name: 'Close' }));
+ await waitFor(() => expect(toast).not.toBeInTheDocument());
+ await user.click(canvas.getByRole('button', { name: 'Restart countdown' }));
+ await wait(1600);
+ expect(args.onClose).toHaveBeenCalledOnce();
+ expect(
+ within(canvasElement.ownerDocument.body).queryByRole('status'),
+ ).not.toBeInTheDocument();
+ },
+};
+
+export const ProviderUnmountCancelsExpiry: Story = {
+ play: async ({ canvasElement, args }) => {
+ const { canvas, toast, user } = await addNotification({ canvasElement });
+ await wait(450);
+ await user.click(
+ canvas.getByRole('button', { name: 'Unmount notification provider' }),
+ );
+ expect(toast).not.toBeInTheDocument();
+ await wait(1600);
+ expect(args.onClose).not.toHaveBeenCalled();
+ },
+};
+
+export const CountdownTracksRemainingTime: Story = {
+ play: async ({ canvasElement, args }) => {
+ const { canvas, toast, user } = await addNotification({ canvasElement });
+ const getCountdown = () =>
+ toast.querySelector<HTMLElement>(
+ '[style*="--toast-countdown-duration"]',
+ )!;
+
+ if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
+ expect(getCountdown()).not.toBeVisible();
+ await expectExpiry({ toast, onClose: args.onClose });
+ return;
+ }
+
+ const getWidthFraction = () =>
+ getCountdown().getBoundingClientRect().width /
+ toast.getBoundingClientRect().width;
+
+ await wait(450);
+ expect(getWidthFraction()).toBeGreaterThan(0.35);
+ expect(getWidthFraction()).toBeLessThan(0.85);
+ const update = within(toast).getByRole('button', {
+ name: 'Update paused content',
+ });
+ await user.click(update);
+ const pausedWidthFraction = getWidthFraction();
+ await wait(500);
+ await user.click(update);
+ expect(getWidthFraction()).toBeCloseTo(pausedWidthFraction, 1);
+ await user.click(
+ within(toast).getByRole('button', { name: 'Restart paused countdown' }),
+ );
+ expect(getWidthFraction()).toBeGreaterThan(0.95);
+ await wait(500);
+ expect(getWidthFraction()).toBeGreaterThan(0.95);
+ await resumeCountdown({ canvas, toast, user });
+ await wait(600);
+ expect(getWidthFraction()).toBeGreaterThan(0.3);
+ expect(getWidthFraction()).toBeLessThan(0.8);
+ await expectExpiry({ toast, onClose: args.onClose, timeout: 1300 });
+ },
+};
+
+export const ExpiryWithoutVisualAnimations: Story = {
+ args: { disableAnimations: true },
+ play: async ({ canvasElement, args }) => {
+ const { toast } = await addNotification({ canvasElement });
+ expect(toast.getAnimations({ subtree: true })).toHaveLength(0);
+ await expectExpiry({ toast, onClose: args.onClose });
+ },
+};
diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterRootReplacementExample.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterRootReplacementExample.tsx
new file mode 100644
index 00000000000..cd026f34ac2
--- /dev/null
+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterRootReplacementExample.tsx
@@ -0,0 +1,46 @@
+import { ToastProvider } from '@ui/components/feedback/Toast/ToastProvider';
+import { useToast } from '@ui/components/feedback/Toast/hooks/useToast';
+import { Button } from '@ui/primitives/input/Button/Button';
+
+import { Toaster } from '../Toaster';
+import { DEFAULT_TIMING_DURATION } from './DefaultTimingDuration';
+import { type ToasterTimingExampleProps } from './ToasterTimingExampleProps';
+
+const RootReplacementControls = ({
+ duration = DEFAULT_TIMING_DURATION,
+ onClose,
+}: ToasterTimingExampleProps) => {
+ const { enqueueToast, updateToast } = useToast();
+
+ return (
+ <Button
+ onClick={() => {
+ const id = enqueueToast({
+ children: 'Timed notification',
+ duration,
+ onClose,
+ });
+
+ updateToast({
+ id,
+ action: (
+ <Button onClick={() => updateToast({ id, render: <section /> })}>
+ Replace focused toast root
+ </Button>
+ ),
+ });
+ }}
+ >
+ Add timed notification
+ </Button>
+ );
+};
+
+export const ToasterRootReplacementExample = (
+ props: ToasterTimingExampleProps,
+) => (
+ <ToastProvider>
+ <RootReplacementControls {...props} />
+ <Toaster />
+ </ToastProvider>
+);
diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterSelfRemovingActionExample.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterSelfRemovingActionExample.tsx
new file mode 100644
index 00000000000..c60dc2b7969
--- /dev/null
+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterSelfRemovingActionExample.tsx
@@ -0,0 +1,54 @@
+import { useState } from 'react';
+
+import { ToastProvider } from '@ui/components/feedback/Toast/ToastProvider';
+import { useToast } from '@ui/components/feedback/Toast/hooks/useToast';
+import { Button } from '@ui/primitives/input/Button/Button';
+
+import { Toaster } from '../Toaster';
+import { DEFAULT_TIMING_DURATION } from './DefaultTimingDuration';
+import { type ToasterTimingExampleProps } from './ToasterTimingExampleProps';
+
+const SelfRemovingAction = () => {
+ const [isVisible, setIsVisible] = useState(true);
+
+ if (!isVisible) {
+ return null;
+ }
+
+ return (
+ <Button onClick={() => setIsVisible(false)}>
+ Remove this focused action
+ </Button>
+ );
+};
+
+const SelfRemovingActionControls = ({
+ duration = DEFAULT_TIMING_DURATION,
+ onClose,
+}: ToasterTimingExampleProps) => {
+ const { enqueueToast } = useToast();
+
+ return (
+ <Button
+ onClick={() =>
+ enqueueToast({
+ children: 'Timed notification',
+ duration,
+ action: <SelfRemovingAction />,
+ onClose,
+ })
+ }
+ >
+ Add timed notification
+ </Button>
+ );
+};
+
+export const ToasterSelfRemovingActionExample = (
+ props: ToasterTimingExampleProps,
+) => (
+ <ToastProvider>
+ <SelfRemovingActionControls {...props} />
+ <Toaster />
+ </ToastProvider>
+);
diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterTimingExample.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterTimingExample.tsx
new file mode 100644
index 00000000000..e964037a023
--- /dev/null
+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterTimingExample.tsx
@@ -0,0 +1,131 @@
+import { useState } from 'react';
+
+import { ToastProvider } from '@ui/components/feedback/Toast/ToastProvider';
+import { useToast } from '@ui/components/feedback/Toast/hooks/useToast';
+import { Button } from '@ui/primitives/input/Button/Button';
+
+import { Toaster } from '../Toaster';
+import { DEFAULT_TIMING_DURATION } from './DefaultTimingDuration';
+import { type ToasterTimingExampleProps } from './ToasterTimingExampleProps';
+
+const TimingActions = ({ id, duration }: { id: string; duration: number }) => {
+ const { updateToast } = useToast();
+ const [revision, setRevision] = useState(1);
+
+ return (
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
+ <Button
+ size="sm"
+ onClick={() => {
+ updateToast({ id, children: `Paused content update ${revision}` });
+ setRevision(revision + 1);
+ }}
+ >
+ Update paused content
+ </Button>
+ <Button size="sm" onClick={() => updateToast({ id, duration })}>
+ Restart paused countdown
+ </Button>
+ <Button size="sm" onClick={() => updateToast({ id, progress: 25 })}>
+ Enter paused progress
+ </Button>
+ <Button
+ size="sm"
+ onClick={() => updateToast({ id, progress: undefined })}
+ >
+ Leave paused progress
+ </Button>
+ <Button
+ size="sm"
+ onClick={() => updateToast({ id, action: null, onCancel: undefined })}
+ >
+ Remove focused actions
+ </Button>
+ </div>
+ );
+};
+
+const TimingControls = ({
+ duration = DEFAULT_TIMING_DURATION,
+ onCancel,
+ onClose,
+}: ToasterTimingExampleProps) => {
+ const { enqueueToast, updateToast, closeToast } = useToast();
+ const [toastId, setToastId] = useState('');
+ const [revision, setRevision] = useState(1);
+
+ const addNotification = (isPersistent: boolean) => {
+ const id = enqueueToast({
+ children: 'Timed notification',
+ duration: isPersistent ? 0 : duration,
+ onCancel,
+ onClose,
+ cancelLabel: 'Keep working',
+ });
+
+ updateToast({ id, action: <TimingActions id={id} duration={duration} /> });
+ setToastId(id);
+ };
+
+ return (
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
+ <Button onClick={() => addNotification(false)}>
+ Add timed notification
+ </Button>
+ <Button onClick={() => addNotification(true)}>
+ Add persistent notification
+ </Button>
+ <Button
+ onClick={() => {
+ updateToast({ id: toastId, children: `Content update ${revision}` });
+ setRevision(revision + 1);
+ }}
+ >
+ Update content
+ </Button>
+ <Button onClick={() => updateToast({ id: toastId, duration })}>
+ Restart countdown
+ </Button>
+ <Button onClick={() => updateToast({ id: toastId, duration: 0 })}>
+ Make persistent
+ </Button>
+ <Button onClick={() => updateToast({ id: toastId, progress: 25 })}>
+ Enter progress
+ </Button>
+ <Button onClick={() => updateToast({ id: toastId, progress: 75 })}>
+ Update progress
+ </Button>
+ <Button onClick={() => updateToast({ id: toastId, progress: undefined })}>
+ Leave progress
+ </Button>
+ <Button onClick={() => closeToast(toastId)}>Close notification</Button>
+ <Button>Outside toast</Button>
+ </div>
+ );
+};
+
+export const ToasterTimingExample = ({
+ disableAnimations = false,
+ ...props
+}: ToasterTimingExampleProps) => {
+ const [isMounted, setIsMounted] = useState(true);
+
+ return (
+ <>
+ <Button onClick={() => setIsMounted(false)}>
+ Unmount notification provider
+ </Button>
+ {isMounted && (
+ <ToastProvider>
+ <TimingControls {...props} />
+ {disableAnimations && (
+ <style>
+ {`[data-toast-timing] * { animation: none !important; transition: none !important; }`}
+ </style>
+ )}
+ <Toaster render={<section data-toast-timing />} />
+ </ToastProvider>
+ )}
+ </>
+ );
+};
diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterTimingExampleProps.ts b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterTimingExampleProps.ts
new file mode 100644
index 00000000000..5602f58dfd6
--- /dev/null
+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterTimingExampleProps.ts
@@ -0,0 +1,6 @@
+export type ToasterTimingExampleProps = {
+ duration?: number;
+ disableAnimations?: boolean;
+ onCancel?: () => void;
+ onClose?: () => void;
+};
diff --git a/packages/twenty-ui/src/components/feedback/Toaster/internal/ToasterItem.tsx b/packages/twenty-ui/src/components/feedback/Toaster/internal/ToasterItem.tsx
index 57bceb44413..a78982f0aac 100644
--- a/packages/twenty-ui/src/components/feedback/Toaster/internal/ToasterItem.tsx
+++ b/packages/twenty-ui/src/components/feedback/Toaster/internal/ToasterItem.tsx
@@ -1,6 +1,7 @@
import { useRef } from 'react';
import { Toast } from '@ui/components/feedback/Toast/Toast';
+import { ToastTimingContext } from '@ui/components/feedback/Toast/internal/contexts/ToastTimingContext';
import { type ToastEntry } from '@ui/components/feedback/Toast/internal/types/ToastEntry';
import styles from '../Toaster.module.scss';
@@ -18,7 +19,7 @@ export const ToasterItem = ({
getToastProps,
onClose,
}: ToasterItemProps) => {
- const { notification, status } = toastEntry;
+ const { notification, status, durationRevision = 0 } = toastEntry;
const { id, ...toastProps } = notification;
const elementRef = useRef<HTMLDivElement>(null);
@@ -31,12 +32,16 @@ export const ToasterItem = ({
inert={status === 'closing'}
>
<div className={styles.itemContent}>
- <Toast
- {...toastProps}
- {...getToastProps?.(notification)}
- id={id}
- onClose={() => onClose(id)}
- />
+ <ToastTimingContext.Provider
+ value={{ durationRevision, isActive: status === 'visible' }}
+ >
+ <Toast
+ {...toastProps}
+ {...getToastProps?.(notification)}
+ id={id}
+ onClose={() => onClose(id)}
+ />
+ </ToastTimingContext.Provider>
</div>
</div>
<ToasterItemExitEffect elementRef={elementRef} toastEntry={toastEntry} />