The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Complete Toast lifecycle ownership (#27938)
Raphaël Bosi2c44d36ab8ce
diff --git a/packages/twenty-docs/snippets/ui/generated/components/feedback/toast-provider.mdx b/packages/twenty-docs/snippets/ui/generated/components/feedback/toast-provider.mdxindex 1d7477f738e..9ef4b8b7e94 100644--- a/packages/twenty-docs/snippets/ui/generated/components/feedback/toast-provider.mdx+++ b/packages/twenty-docs/snippets/ui/generated/components/feedback/toast-provider.mdx@@ -12,9 +12,9 @@*/}<ParamField body="children" type="ReactNode">- Application content and a Toaster sharing this notification store.+ Application content and any Toasters sharing this provider’s independent notification store and lifecycle.</ParamField><ParamField body="limit" type="number" default="3">- Maximum number of visible toasts, read once when the provider mounts. Must be a positive integer. Adding a toast above the limit dismisses the oldest visible notifications.+ Reactive maximum number of visible toasts, defaulting to three. Must be a positive integer. Lowering it or adding above it dismisses the oldest visible notifications and calls their onClose once. Surviving IDs, order, and countdowns are preserved.</ParamField>diff --git a/packages/twenty-docs/snippets/ui/generated/components/feedback/toast.mdx b/packages/twenty-docs/snippets/ui/generated/components/feedback/toast.mdxindex 283c32a8c5c..cd82fa30f6c 100644--- a/packages/twenty-docs/snippets/ui/generated/components/feedback/toast.mdx+++ b/packages/twenty-docs/snippets/ui/generated/components/feedback/toast.mdx@@ -52,7 +52,7 @@</ParamField><ParamField body="onClose" type="(() => void)">- Called once per mounted toast when the close button is clicked or the countdown completes. Providing it shows the close button.+ For standalone Toast, called once per mount by the close button or expiry. For provider notifications, called once on close, expiry, closeToast, or limit eviction, after dismissal and before exit cleanup. Provider teardown does not call it.</ParamField><ParamField body="progress" type="number">diff --git a/packages/twenty-docs/snippets/ui/generated/components/feedback/toaster.mdx b/packages/twenty-docs/snippets/ui/generated/components/feedback/toaster.mdxindex 2f535aca970..25a6c8464c7 100644--- a/packages/twenty-docs/snippets/ui/generated/components/feedback/toaster.mdx+++ b/packages/twenty-docs/snippets/ui/generated/components/feedback/toaster.mdx@@ -12,11 +12,11 @@*/}<ParamField body="container" type="HTMLElement | null">- Portal destination. Omit to use the theme container or document.body; null defers rendering.+ Portal destination. Omit to use the theme container or document.body; null defers rendering. The provider retains visible notifications and pauses their countdowns while no Toaster is rendered.</ParamField><ParamField body="getToastProps" type="((toast: ToastNotification) => Partial<Omit<ToastProps, "ref" | "id" | "onClose">>)">- Customizes each notification’s Toast props. The toaster owns id, ref, and dismissal.+ Adapts notification content and presentation. The provider owns id, dismissal, and the shared countdown. Set timing through enqueueToast or updateToast; duration and progress overrides must match across Toasters sharing a provider.</ParamField><ParamField body="render" type="RenderProp<Record<string, unknown>>">diff --git a/packages/twenty-docs/ui/components/feedback/toast.mdx b/packages/twenty-docs/ui/components/feedback/toast.mdxindex 8215a6948d2..b40ea068b78 100644--- a/packages/twenty-docs/ui/components/feedback/toast.mdx+++ b/packages/twenty-docs/ui/components/feedback/toast.mdx@@ -11,7 +11,7 @@ import ToasterReference from '/snippets/ui/generated/components/feedback/toaster`Toast` renders one notification. Your application controls when it appears, its position, and when it is removed.-For application notifications, wrap the application in `ToastProvider`, mount one `Toaster` inside it, and use `useToast()` from descendants. Each provider owns a separate notification store.+For application notifications, wrap the application in `ToastProvider`, mount a `Toaster` inside it, and use `useToast()` from descendants. Each provider owns an independent notification store, countdowns, and dismissal lifecycle. Multiple Toasters can mirror the same provider.<StoryEmbedstoryId="ui-feedback-toast--documentation"@@ -22,6 +22,8 @@ For application notifications, wrap the application in `ToastProvider`, mount on## Application notifications```tsx+import { useState } from 'react';+import {ToastProvider,Toaster,@@ -38,26 +40,55 @@ const SaveNotificationButton = () => {enqueueToast({children: 'Record saved',status: 'success',- dedupeKey: 'record-saved',})}>- Show saved notification+ Add saved notification</Button>);};-export const Notifications = () => (- <ToastProvider limit={3}>- <SaveNotificationButton />- <Toaster />- </ToastProvider>-);+export const Notifications = () => {+ const [limit, setLimit] = useState(3);++ return (+ <ToastProvider limit={limit}>+ <SaveNotificationButton />+ <Button onClick={() => setLimit(1)}>Keep one notification</Button>+ <Button onClick={() => setLimit(3)}>Keep three notifications</Button>+ <Toaster />+ </ToastProvider>+ );+};````enqueueToast` accepts Toast props and an optional `dedupeKey`, and returns the notification ID. A matching visible key returns the existing ID without adding another notification. `updateToast({ id, ...changes })` patches that live notification. `closeToast(id)` dismisses one notification; `closeToast()` dismisses all visible notifications in the provider.-The provider defaults to three visible notifications. Adding another dismisses the oldest visible ones. The toaster handles dismissal and exit animations. `container` overrides its portal destination; `null` defers rendering. `getToastProps` customizes each notification, while the toaster retains its ID and dismissal handler. Set `aria-label` on `Toaster` to localize its default region name, "Notifications".+The provider defaults to three visible notifications. `limit` must be a positive integer and can change while the provider is mounted. Lowering it or adding above it dismisses the oldest visible notifications first. Increasing it leaves existing notifications unchanged and does not restore dismissed notifications. Configuration changes preserve the store, surviving IDs, order, and remaining countdown time.++## Provider lifecycle++<StoryEmbed+ storyId="ui-feedback-toaster-lifecycle--documentation"+ title="Shared notification lifecycle"+ height={450}+/>++Multiple Toasters inside a provider render the same notifications. Updates and dismissal apply to every mirror, and each notification has one shared countdown. Hover or focus inside any mirror pauses it; it resumes after all mirrors release both. Mounting another Toaster does not restart the countdown or create another callback lifecycle. Use separate providers for independent queues.++For provider notifications, expiry, the close button, `closeToast`, and limit eviction call the latest `onClose` once. The notification is already dismissed when the callback runs, so updates and repeated close requests for that ID have no effect. `onCancel` remains a separate action callback and does not dismiss automatically.++Dismissed notifications are inert during exit animations. Their entries are removed after all rendered mirrors finish their exit work or unmount. Unmounting the last Toaster clears dismissed entries and freezes the remaining time for visible notifications. Remounting a Toaster resumes that time. Unmounting the provider discards its notifications and cancels countdown and exit work without calling `onClose`. Captured `enqueueToast`, `updateToast`, and `closeToast` operations from that provider have no effect after it unmounts.++`getToastProps` adapts each notification’s content and presentation. Set `duration` and `progress` in `enqueueToast` or `updateToast` so every mirror shares the same timing configuration. Existing timing overrides through `getToastProps` remain supported when all mirrors return the same duration and progress for a notification. The provider retains the ID, dismissal handler, and shared countdown.++`container` selects a Toaster’s portal destination. When omitted, it uses the surrounding theme container or `document.body`. An explicit element renders there; `null` defers rendering. Visible notifications remain queued, with their countdowns paused while no Toaster is rendered. Portals retain the surrounding theme and direction. Set `aria-label` on each Toaster to localize its default region name, "Notifications", and give mirrored regions appropriate names.++<StoryEmbed+ storyId="ui-feedback-toaster-lifecycle--portal-documentation"+ title="Scoped notification portal"+ height={350}+/>## Update a live notification@@ -115,7 +146,7 @@ export const SaveButton = ({ saveRecord, onViewRecord }: SaveButtonProps) => {## 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.+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. With multiple Toasters, pause state is shared across their mirrors. The visual countdown follows the remaining dismissal time. Automatic dismissal also works when reduced motion disables the animation.<StoryEmbedstoryId="ui-feedback-toaster-timing--documentation"diff --git a/packages/twenty-ui/docs/label-ownership.md b/packages/twenty-ui/docs/label-ownership.mdindex 5737a90ad9e..a7b8202dea8 100644--- a/packages/twenty-ui/docs/label-ownership.md+++ b/packages/twenty-ui/docs/label-ownership.md@@ -16,7 +16,7 @@ This covers production exports under components, primitives, and icons, includin| CountrySelect | `searchLabel`, `noCountryLabel`, and `noResultsLabel` default to `Search`, `No country`, and `No results`. The search label names the search input and is its placeholder. Applications supply `label` or native accessible names and the country labels, including translated strings. || PhoneCountryPicker | Callers supply country labels and the trigger accessible name. The popup takes the trigger name unless a `Dropdown.Title` or an explicit `Dropdown.Content` label names it, and the selected country label describes the trigger. `searchLabel` defaults to `Search`; `emptyLabel` defaults to `No results`. Calling codes are supplied as data without a leading plus sign. || ImageInput | `uploadLabel`, `removeLabel`, and `abortLabel` default to `Upload`, `Remove`, and `Abort`. The upload label names the visible upload button, preview button, and hidden file input. Native accessible attributes can supply names and descriptions for the file input. Applications supply `helperText` and `errorMessage`, including validation instructions and translated strings. |-| Toast and Toaster | Caller-owned children, description, icon, action, and `cancelLabel` nodes (default `Cancel`), plus `iconLabel` and `closeLabel` (default `Close`). Live updates replace only supplied fields. Toaster accepts native accessible attributes over its `Notifications` region default. |+| Toast and Toaster | Caller-owned children, description, icon, action, and `cancelLabel` nodes (default `Cancel`), plus `iconLabel` and `closeLabel` (default `Close`). Live updates replace only supplied fields. Toaster accepts native accessible attributes over its `Notifications` region default. Multiple Toasters mirror one provider-owned notification lifecycle; each region owns its accessible name. || Chip and Avatar | Chip content, translated fallbacks and interactive accessible names belong to the caller. Missing children add no label. Avatar's image and default fallback are decorative. `name` supplies the visual initial and colors. Explicit `imageProps.alt` labels the image and default fallback; caller fallback semantics take precedence. Composed buttons and links own their labels and interaction handlers. || JsonTree | Callers supply empty string, array, and object labels and expanded/collapsed arrow names. JSON booleans, null, property names, and values are data. || ResizeHandle and CodeEditor | ResizeHandle accepts native labels over `Resize`. Hosts supply a contextual label, `aria-controls`, and the focus destination when collapsing a panel removes its handle. CodeEditor exposes `resizeLabel` (default `Resize editor`) and Monaco `options`, including its editor accessible label. The loading indicator adds no text. Monaco owns its internal editor messages. |diff --git a/packages/twenty-ui/docs/toastPropDescriptions.ts b/packages/twenty-ui/docs/toastPropDescriptions.tsindex bfb2a9bbfdb..2ee9ef4c37d 100644--- a/packages/twenty-ui/docs/toastPropDescriptions.ts+++ b/packages/twenty-ui/docs/toastPropDescriptions.ts@@ -18,7 +18,7 @@ export const TOAST_PROP_DESCRIPTIONS = {onCancel:'Called when the cancel button is clicked. Providing it and renderable cancelLabel content shows the button.',onClose:- 'Called once per mounted toast when the close button is clicked or the countdown completes. Providing it shows the close button.',+ 'For standalone Toast, called once per mount by the close button or expiry. For provider notifications, called once on close, expiry, closeToast, or limit eviction, after dismissal and before exit cleanup. Provider teardown does not call it.',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/docs/toastProviderPropDescriptions.ts b/packages/twenty-ui/docs/toastProviderPropDescriptions.tsindex 4ba963b08ab..f9514b78ea8 100644--- a/packages/twenty-ui/docs/toastProviderPropDescriptions.ts+++ b/packages/twenty-ui/docs/toastProviderPropDescriptions.ts@@ -4,7 +4,7 @@ import { type ToastProvider } from '../src/components/feedback/Toast/ToastProvidexport const TOAST_PROVIDER_PROP_DESCRIPTIONS = {children:- 'Application content and a Toaster sharing this notification store.',+ 'Application content and any Toasters sharing this provider’s independent notification store and lifecycle.',limit:- 'Maximum number of visible toasts, read once when the provider mounts. Must be a positive integer. Adding a toast above the limit dismisses the oldest visible notifications.',+ 'Reactive maximum number of visible toasts, defaulting to three. Must be a positive integer. Lowering it or adding above it dismisses the oldest visible notifications and calls their onClose once. Surviving IDs, order, and countdowns are preserved.',} satisfies Partial<Record<keyof ComponentProps<typeof ToastProvider>, string>>;diff --git a/packages/twenty-ui/docs/toasterPropDescriptions.ts b/packages/twenty-ui/docs/toasterPropDescriptions.tsindex c8c00255c76..0b61003b4f0 100644--- a/packages/twenty-ui/docs/toasterPropDescriptions.ts+++ b/packages/twenty-ui/docs/toasterPropDescriptions.ts@@ -4,8 +4,8 @@ import { type Toaster } from '../src/components/feedback/Toaster/Toaster';export const TOASTER_PROP_DESCRIPTIONS = {container:- 'Portal destination. Omit to use the theme container or document.body; null defers rendering.',+ 'Portal destination. Omit to use the theme container or document.body; null defers rendering. The provider retains visible notifications and pauses their countdowns while no Toaster is rendered.',getToastProps:- 'Customizes each notification’s Toast props. The toaster owns id, ref, and dismissal.',+ 'Adapts notification content and presentation. The provider owns id, dismissal, and the shared countdown. Set timing through enqueueToast or updateToast; duration and progress overrides must match across Toasters sharing a provider.',render: 'Custom root element composed through Base UI.',} satisfies Partial<Record<keyof ComponentProps<typeof Toaster>, string>>;diff --git a/packages/twenty-ui/generated/components.docs.json b/packages/twenty-ui/generated/components.docs.jsonindex 38f0f1a4459..597507eab7e 100644--- a/packages/twenty-ui/generated/components.docs.json+++ b/packages/twenty-ui/generated/components.docs.json@@ -9915,7 +9915,7 @@"type": "(() => void)","required": false,"defaultValue": null,- "description": "Called once per mounted toast when the close button is clicked or the countdown completes. Providing it shows the close button."+ "description": "For standalone Toast, called once per mount by the close button or expiry. For provider notifications, called once on close, expiry, closeToast, or limit eviction, after dismissal and before exit cleanup. Provider teardown does not call it."},{"name": "progress",@@ -13211,14 +13211,14 @@"type": "ReactNode","required": false,"defaultValue": null,- "description": "Application content and a Toaster sharing this notification store."+ "description": "Application content and any Toasters sharing this provider’s independent notification store and lifecycle."},{"name": "limit","type": "number","required": false,"defaultValue": "3",- "description": "Maximum number of visible toasts, read once when the provider mounts. Must be a positive integer. Adding a toast above the limit dismisses the oldest visible notifications."+ "description": "Reactive maximum number of visible toasts, defaulting to three. Must be a positive integer. Lowering it or adding above it dismisses the oldest visible notifications and calls their onClose once. Surviving IDs, order, and countdowns are preserved."}]},@@ -13232,14 +13232,14 @@"type": "HTMLElement | null","required": false,"defaultValue": null,- "description": "Portal destination. Omit to use the theme container or document.body; null defers rendering."+ "description": "Portal destination. Omit to use the theme container or document.body; null defers rendering. The provider retains visible notifications and pauses their countdowns while no Toaster is rendered."},{"name": "getToastProps","type": "((toast: ToastNotification) => Partial<Omit<ToastProps, \"ref\" | \"id\" | \"onClose\">>)","required": false,"defaultValue": null,- "description": "Customizes each notification’s Toast props. The toaster owns id, ref, and dismissal."+ "description": "Adapts notification content and presentation. The provider owns id, dismissal, and the shared countdown. Set timing through enqueueToast or updateToast; duration and progress overrides must match across Toasters sharing a provider."},{"name": "render",diff --git a/packages/twenty-ui/src/components/feedback/Toast/Toast.tsx b/packages/twenty-ui/src/components/feedback/Toast/Toast.tsxindex 5211be8af8f..88bbda37077 100644--- a/packages/twenty-ui/src/components/feedback/Toast/Toast.tsx+++ b/packages/twenty-ui/src/components/feedback/Toast/Toast.tsx@@ -18,6 +18,7 @@ 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 { DEFAULT_TOAST_DURATION } from './internal/constants/DefaultToastDuration';import { ToastProgress } from './internal/components/ToastProgress';import { useToastCountdown } from './internal/hooks/useToastCountdown';import { type ToastProps } from './types/ToastProps';@@ -38,7 +39,7 @@ export const Toast = ({iconLabel,action,progress,- duration = 6000,+ duration = DEFAULT_TOAST_DURATION,onCancel,onClose,cancelLabel = 'Cancel',@@ -60,7 +61,7 @@ export const Toast = ({const [toastElement, setToastElement] = useState<HTMLDivElement | null>(null);const isPaused = isHovered || isFocused;- const { countdown, clock } = useToastCountdown({+ const { countdown, clock, setClock } = useToastCountdown({duration,isPaused,});@@ -173,6 +174,7 @@ export const Toast = ({/><ToastCountdownEffectclock={clock}+ onClockChange={setClock}duration={duration}progress={progress}isPaused={isPaused}diff --git a/packages/twenty-ui/src/components/feedback/Toast/ToastProvider.tsx b/packages/twenty-ui/src/components/feedback/Toast/ToastProvider.tsxindex 3462016acf4..225dd902d0e 100644--- a/packages/twenty-ui/src/components/feedback/Toast/ToastProvider.tsx+++ b/packages/twenty-ui/src/components/feedback/Toast/ToastProvider.tsx@@ -1,5 +1,6 @@import { useState } from 'react';+import { ToastProviderLifecycleEffect } from './internal/components/ToastProviderLifecycleEffect';import { DEFAULT_TOAST_LIMIT } from './internal/constants/DefaultToastLimit';import { ToastContext } from './internal/contexts/ToastContext';import { createToastStore } from './internal/stores/createToastStore';@@ -12,6 +13,9 @@ export const ToastProvider = ({const [store] = useState(() => createToastStore(limit));return (- <ToastContext.Provider value={store}>{children}</ToastContext.Provider>+ <ToastContext.Provider value={store}>+ {children}+ <ToastProviderLifecycleEffect limit={limit} />+ </ToastContext.Provider>);};diff --git a/packages/twenty-ui/src/components/feedback/Toast/hooks/__tests__/useToast.test.tsx b/packages/twenty-ui/src/components/feedback/Toast/hooks/__tests__/useToast.test.tsxindex b48c8a02509..37398f65dbb 100644--- a/packages/twenty-ui/src/components/feedback/Toast/hooks/__tests__/useToast.test.tsx+++ b/packages/twenty-ui/src/components/feedback/Toast/hooks/__tests__/useToast.test.tsx@@ -87,6 +87,25 @@ it('ignores undefined options without publishing or evicting a toast', () => {expect(onClose).not.toHaveBeenCalled();});+it('ignores a captured enqueue after final provider disposal', async () => {+ const { store, result, unmount } = renderToastHooks();+ const { enqueueToast } = result.current;+ const stop = store.lifecycle.mount();+ enqueueToast({ children: 'Saved' });+ unmount();+ stop();+ await Promise.resolve();+ const disposedSnapshot = store.state.toasts;+ const listener = vi.fn();+ store.subscribe(listener);++ enqueueToast({ children: 'Stale notification' });++ expect(disposedSnapshot).toEqual([]);+ expect(store.state.toasts).toBe(disposedSnapshot);+ expect(listener).not.toHaveBeenCalled();+});+it('retains a dismissed toast until its exit finishes and calls onClose once', () => {const { store, result } = renderToastHooks();const listener = vi.fn();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.tsxindex e6352ef0577..4a2a96f8472 100644--- a/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastCountdownEffect.tsx+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastCountdownEffect.tsx@@ -4,26 +4,58 @@ import { isDefined } from '@ui/utilities/utils/isDefined';import { type ToastProps } from '../../types/ToastProps';import { ToastTimingContext } from '../contexts/ToastTimingContext';-import { type createToastCountdown } from '../utils/createToastCountdown';+import { type createToastCountdownStore } from '../utils/createToastCountdownStore';type ToastCountdownEffectProps = Pick<ToastProps, 'progress' | 'onClose'> & {- clock: ReturnType<typeof createToastCountdown>;+ clock: ReturnType<typeof createToastCountdownStore>;+ onClockChange: (clock: ReturnType<typeof createToastCountdownStore>) => void;duration: number;isPaused: boolean;};export const ToastCountdownEffect = ({clock,+ onClockChange,duration,progress,isPaused,onClose,}: ToastCountdownEffectProps) => {- const { durationRevision, isActive } = useContext(ToastTimingContext);+ const {+ durationRevision,+ isActive,+ lifecycle,+ id,+ rendererKey,+ timingOverrides,+ } = useContext(ToastTimingContext);+ const isSharedCountdown =+ isDefined(lifecycle) && isDefined(id) && isDefined(rendererKey);+ const standaloneClock = isSharedCountdown ? undefined : clock;const isProgress = isDefined(progress);+ const isDurationOverridden =+ isDefined(timingOverrides) &&+ Object.prototype.propertyIsEnumerable.call(timingOverrides, 'duration');+ const isProgressOverridden =+ isDefined(timingOverrides) &&+ Object.prototype.propertyIsEnumerable.call(timingOverrides, 'progress');useLayoutEffect(() => {- clock.update({+ if (isSharedCountdown) {+ const sharedClock = lifecycle.updateRenderer({+ id,+ key: rendererKey,+ configuration: {+ duration: isDurationOverridden ? duration : undefined,+ isProgress: isProgressOverridden ? isProgress : undefined,+ isPaused,+ },+ });+ onClockChange(sharedClock);+ return;+ }++ standaloneClock?.update({duration,durationRevision,isPaused,@@ -32,16 +64,33 @@ export const ToastCountdownEffect = ({onClose,});}, [- clock,+ standaloneClock,+ onClockChange,+ isSharedCountdown,duration,durationRevision,isPaused,isProgress,isActive,onClose,+ lifecycle,+ id,+ rendererKey,+ isDurationOverridden,+ isProgressOverridden,]);- useLayoutEffect(() => () => clock.stop(), [clock]);+ useLayoutEffect(+ () => () => {+ if (isSharedCountdown) {+ lifecycle.removeRenderer({ id, key: rendererKey });+ return;+ }++ standaloneClock?.stop();+ },+ [standaloneClock, lifecycle, id, rendererKey, isSharedCountdown],+ );return null;};diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastProviderLifecycleEffect.tsx b/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastProviderLifecycleEffect.tsxnew file mode 100644index 00000000000..b3fa021aad4--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/components/ToastProviderLifecycleEffect.tsx@@ -0,0 +1,13 @@+import { useEffect, useLayoutEffect } from 'react';++import { useToastContext } from '../hooks/useToastContext';+import { updateToastLimit } from '../utils/updateToastLimit';++export const ToastProviderLifecycleEffect = ({ limit }: { limit: number }) => {+ const store = useToastContext();++ useEffect(() => store.lifecycle.mount(), [store]);+ useLayoutEffect(() => updateToastLimit({ store, limit }), [store, limit]);++ return null;+};diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/constants/DefaultToastDuration.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/constants/DefaultToastDuration.tsnew file mode 100644index 00000000000..9df47cda583--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/constants/DefaultToastDuration.ts@@ -0,0 +1 @@+export const DEFAULT_TOAST_DURATION = 6000;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.tsindex e666bc80992..51906de6c07 100644--- a/packages/twenty-ui/src/components/feedback/Toast/internal/contexts/ToastTimingContext.ts+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/contexts/ToastTimingContext.ts@@ -1,6 +1,17 @@import { createContext } from 'react';-export const ToastTimingContext = createContext({+import { type createToastLifecycle } from '../utils/createToastLifecycle';++type ToastTiming = {+ durationRevision: number;+ isActive: boolean;+ lifecycle?: ReturnType<typeof createToastLifecycle>;+ id?: string;+ rendererKey?: symbol;+ timingOverrides?: { duration?: number; progress?: number };+};++export const ToastTimingContext = createContext<ToastTiming>({durationRevision: 0,isActive: true,});diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/hooks/useCloseToast.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/hooks/useCloseToast.tsindex ef51ad8976d..7c95084fe86 100644--- a/packages/twenty-ui/src/components/feedback/Toast/internal/hooks/useCloseToast.ts+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/hooks/useCloseToast.ts@@ -10,6 +10,10 @@ export const useCloseToast = () => {const store = useToastContext();const closeToast = (id?: string) => {+ if (!store.lifecycle.isActive()) {+ return;+ }+const toastsToClose = store.state.toasts.filter((toast) =>isToastVisible(toast) &&diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/hooks/useEnqueueToast.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/hooks/useEnqueueToast.tsindex b31ecdc46a5..45dba25495d 100644--- a/packages/twenty-ui/src/components/feedback/Toast/internal/hooks/useEnqueueToast.ts+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/hooks/useEnqueueToast.ts@@ -9,6 +9,11 @@ import { useToastContext } from './useToastContext';let lastToastId = 0;+const createToastId = () => {+ lastToastId += 1;+ return `toast-${lastToastId}`;+};+export const useEnqueueToast = () => {const store = useToastContext();@@ -22,6 +27,10 @@ export const useEnqueueToast = () => {return;}+ if (!store.lifecycle.isActive()) {+ return createToastId();+ }+const { dedupeKey, ...toastProps } = options;const { toasts, limit } = store.state;const visibleToasts = toasts.filter(isToastVisible);@@ -33,8 +42,7 @@ export const useEnqueueToast = () => {return existingToast.notification.id;}- lastToastId += 1;- const id = `toast-${lastToastId}`;+ const id = createToastId();const removedCount = Math.max(0, visibleToasts.length - limit + 1);dismissToasts({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.tsindex 82151b912ba..6456e07fb1d 100644--- a/packages/twenty-ui/src/components/feedback/Toast/internal/hooks/useToastCountdown.ts+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/hooks/useToastCountdown.ts@@ -1,6 +1,9 @@-import { useState } from 'react';+import { useContext, useState, useSyncExternalStore } from 'react';-import { createToastCountdown } from '../utils/createToastCountdown';+import { isDefined } from '@ui/utilities/utils/isDefined';++import { ToastTimingContext } from '../contexts/ToastTimingContext';+import { createToastCountdownStore } from '../utils/createToastCountdownStore';export const useToastCountdown = ({duration,@@ -9,15 +12,20 @@ export const useToastCountdown = ({duration: number;isPaused: boolean;}) => {- const [countdown, setCountdown] = useState({- duration,- remainingDuration: duration,- revision: 0,- isPaused,+ const { lifecycle, id, rendererKey } = useContext(ToastTimingContext);+ const [clock, setClock] = useState(() => {+ const sharedClock =+ isDefined(lifecycle) && isDefined(id) && isDefined(rendererKey)+ ? lifecycle.getCountdown(id)+ : undefined;++ return sharedClock ?? createToastCountdownStore({ duration, isPaused });});- const [clock] = useState(() =>- createToastCountdown({ onChange: setCountdown }),+ const countdown = useSyncExternalStore(+ clock.subscribe,+ clock.getSnapshot,+ clock.getSnapshot,);- return { countdown, clock };+ return { countdown, clock, setClock };};diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/stores/createToastStore.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/stores/createToastStore.tsindex cceeb08a8b6..b52061d4bf6 100644--- a/packages/twenty-ui/src/components/feedback/Toast/internal/stores/createToastStore.ts+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/stores/createToastStore.ts@@ -1,17 +1,18 @@import { Store } from '@base-ui/utils/store';-import { isPositiveInteger } from '@sniptt/guards';import { DEFAULT_TOAST_LIMIT } from '../constants/DefaultToastLimit';import { type ToastStoreState } from '../types/ToastStoreState';+import { assertValidToastLimit } from '../utils/assertValidToastLimit';+import { createToastLifecycle } from '../utils/createToastLifecycle';export const createToastStore = (limit = DEFAULT_TOAST_LIMIT) => {- if (!isPositiveInteger(limit)) {- throw new Error('Toast limit must be a positive integer.');- }+ assertValidToastLimit(limit);- return new Store<ToastStoreState>({+ const store = new Store<ToastStoreState>({toasts: [],limit,mountedToasterCount: 0,});++ return Object.assign(store, { lifecycle: createToastLifecycle(store) });};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.tsindex e19f4e06826..16d8667b341 100644--- 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@@ -42,6 +42,33 @@ it('preserves the original expiry through repeated unchanged updates and uses th);});+it.each([+ { state: 'persistent', configuration: { duration: 0 } },+ { state: 'inactive', configuration: { isActive: false } },+])(+ 'keeps unchanged $state snapshots while refreshing the close callback',+ ({ configuration }) => {+ const onChange = vi.fn();+ const onClose = vi.fn();+ const updatedClose = vi.fn();+ const countdown = createToastCountdown({ onChange });+ countdown.update({ ...DEFAULT_CONFIGURATION, ...configuration, onClose });++ vi.advanceTimersByTime(400);+ countdown.update({+ ...DEFAULT_CONFIGURATION,+ ...configuration,+ onClose: updatedClose,+ });++ expect(onChange).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ countdown.close();+ expect(updatedClose).toHaveBeenCalledOnce();+ expect(onClose).not.toHaveBeenCalled();+ },+);+it('restarts every explicit duration revision even when the duration stays unchanged', () => {const onChange = vi.fn();const onClose = vi.fn();diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/__tests__/createToastLifecycle.test.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/__tests__/createToastLifecycle.test.tsnew file mode 100644index 00000000000..0804cb3955e--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/__tests__/createToastLifecycle.test.ts@@ -0,0 +1,546 @@+import { isFunction } from '@sniptt/guards';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++import { createToastStore } from '../../stores/createToastStore';+import { type ToastEntry } from '../../types/ToastEntry';+import { dismissToasts } from '../dismissToasts';+import { updateToastInStore } from '../updateToastInStore';++const RENDERER_CONFIGURATION = { isPaused: false };++const createStoreWithNotification = ({+ id = 'notification',+ onClose = vi.fn(),+}: {+ id?: string;+ onClose?: () => void;+} = {}) => {+ const store = createToastStore();+ const notification: ToastEntry = {+ notification: { id, children: 'Saved', duration: 1000, onClose },+ status: 'visible',+ };+ store.set('mountedToasterCount', 1);+ store.set('toasts', [notification]);++ return { store, notification, onClose };+};++beforeEach(() => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });+});++afterEach(() => {+ vi.clearAllTimers();+ vi.restoreAllMocks();+ vi.useRealTimers();+});++it('allocates a shared countdown only when a renderer is registered', () => {+ const { store } = createStoreWithNotification();++ expect(store.lifecycle.getCountdown('notification')).toBeUndefined();+ expect(store.lifecycle.getCountdown('notification')).toBeUndefined();+ expect(+ store.lifecycle.getCountdown('abandoned notification'),+ ).toBeUndefined();+ expect(vi.getTimerCount()).toBe(0);++ const firstClock = store.lifecycle.updateRenderer({+ id: 'notification',+ key: Symbol(),+ configuration: RENDERER_CONFIGURATION,+ });+ const secondClock = store.lifecycle.updateRenderer({+ id: 'notification',+ key: Symbol(),+ configuration: RENDERER_CONFIGURATION,+ });++ expect(store.lifecycle.getCountdown('notification')).toBe(firstClock);+ expect(secondClock).toBe(firstClock);+ expect(+ store.lifecycle.getCountdown('abandoned notification'),+ ).toBeUndefined();+ expect(vi.getTimerCount()).toBe(0);+});++it('shares one countdown across mirrors and dismisses with the latest callback once', () => {+ const { store, onClose } = createStoreWithNotification();+ const firstKey = Symbol();+ const secondKey = Symbol();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: firstKey,+ configuration: RENDERER_CONFIGURATION,+ });+ vi.advanceTimersByTime(400);+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: secondKey,+ configuration: RENDERER_CONFIGURATION,+ });+ const updatedClose = vi.fn();+ updateToastInStore({+ store,+ id: 'notification',+ children: 'Updated',+ onClose: updatedClose,+ });++ expect(vi.getTimerCount()).toBe(1);+ vi.advanceTimersByTime(599);+ expect(updatedClose).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(updatedClose).toHaveBeenCalledOnce();+ expect(onClose).not.toHaveBeenCalled();+ expect(store.state.toasts[0]?.status).toBe('closing');+ vi.advanceTimersByTime(10_000);+ expect(updatedClose).toHaveBeenCalledOnce();+ stop();+});++it('keeps the shared clock paused until every mirror resumes', () => {+ const { store, onClose } = createStoreWithNotification();+ const firstKey = Symbol();+ const secondKey = Symbol();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: firstKey,+ configuration: RENDERER_CONFIGURATION,+ });+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: secondKey,+ configuration: RENDERER_CONFIGURATION,+ });+ vi.advanceTimersByTime(400);+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: firstKey,+ configuration: { ...RENDERER_CONFIGURATION, isPaused: true },+ });+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: secondKey,+ configuration: { ...RENDERER_CONFIGURATION, isPaused: true },+ });+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: firstKey,+ configuration: RENDERER_CONFIGURATION,+ });+ vi.advanceTimersByTime(10_000);+ expect(onClose).not.toHaveBeenCalled();+ expect(+ store.lifecycle.getCountdown('notification')?.getSnapshot(),+ ).toMatchObject({+ remainingDuration: 600,+ isPaused: true,+ });+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: secondKey,+ configuration: RENDERER_CONFIGURATION,+ });+ vi.advanceTimersByTime(599);+ expect(onClose).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(onClose).toHaveBeenCalledOnce();+ stop();+});++it('preserves remaining time while every mirror is detached and resumes on remount', () => {+ const { store, onClose } = createStoreWithNotification();+ const key = Symbol();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key,+ configuration: RENDERER_CONFIGURATION,+ });+ vi.advanceTimersByTime(400);+ store.lifecycle.removeRenderer({ id: 'notification', key });+ vi.advanceTimersByTime(10_000);++ expect(onClose).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: Symbol(),+ configuration: RENDERER_CONFIGURATION,+ });+ vi.advanceTimersByTime(599);+ expect(onClose).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(onClose).toHaveBeenCalledOnce();+ stop();+});++it('uses the first registered mirror timing override until that mirror detaches', () => {+ const { store, onClose } = createStoreWithNotification();+ const firstKey = Symbol();+ const secondKey = Symbol();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: firstKey,+ configuration: { ...RENDERER_CONFIGURATION, duration: 0 },+ });+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: secondKey,+ configuration: { ...RENDERER_CONFIGURATION, duration: 600 },+ });+ vi.advanceTimersByTime(10_000);+ expect(onClose).not.toHaveBeenCalled();++ store.lifecycle.removeRenderer({ id: 'notification', key: firstKey });+ vi.advanceTimersByTime(599);+ expect(onClose).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(onClose).toHaveBeenCalledOnce();+ stop();+});++it('keeps notification clocks and callbacks isolated between providers', () => {+ const first = createStoreWithNotification();+ const second = createStoreWithNotification();+ const stopFirst = first.store.lifecycle.mount();+ const stopSecond = second.store.lifecycle.mount();+ first.store.lifecycle.updateRenderer({+ id: 'notification',+ key: Symbol(),+ configuration: RENDERER_CONFIGURATION,+ });+ second.store.lifecycle.updateRenderer({+ id: 'notification',+ key: Symbol(),+ configuration: { ...RENDERER_CONFIGURATION, duration: 0 },+ });++ vi.advanceTimersByTime(1000);++ expect(first.onClose).toHaveBeenCalledOnce();+ expect(second.onClose).not.toHaveBeenCalled();+ expect(second.store.state.toasts[0]).toBe(second.notification);+ stopFirst();+ stopSecond();+});++it('stops provider work without dismissing and resumes from the same remainder', () => {+ const { store, onClose } = createStoreWithNotification();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: Symbol(),+ configuration: RENDERER_CONFIGURATION,+ });+ vi.advanceTimersByTime(400);+ stop();+ vi.advanceTimersByTime(10_000);+ expect(onClose).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);++ const stopRemounted = store.lifecycle.mount();+ vi.advanceTimersByTime(599);+ expect(onClose).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(onClose).toHaveBeenCalledOnce();+ stopRemounted();+});++it('retains cleanup updates when effect replay cancels provider disposal', async () => {+ const { store, onClose } = createStoreWithNotification();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: Symbol(),+ configuration: RENDERER_CONFIGURATION,+ });+ vi.advanceTimersByTime(400);+ stop();++ expect(vi.getTimerCount()).toBe(0);+ updateToastInStore({+ store,+ id: 'notification',+ children: 'Updated during cleanup',+ });+ expect(store.state.toasts[0]?.notification.children).toBe(+ 'Updated during cleanup',+ );++ const stopRemounted = store.lifecycle.mount();+ await Promise.resolve();+ expect(store.lifecycle.isActive()).toBe(true);+ expect(store.state.toasts[0]?.notification.children).toBe(+ 'Updated during cleanup',+ );+ vi.advanceTimersByTime(599);+ expect(onClose).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(onClose).toHaveBeenCalledOnce();+ stopRemounted();+});++it('does not restart stopped provider work when an obsolete timer callback arrives', () => {+ const { store, onClose } = createStoreWithNotification();+ const timeoutSpy = vi.spyOn(globalThis, 'setTimeout');+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: Symbol(),+ configuration: RENDERER_CONFIGURATION,+ });+ const [timeoutCallback] = timeoutSpy.mock.calls[0]!;+ vi.advanceTimersByTime(400);+ stop();++ if (!isFunction(timeoutCallback)) {+ throw new Error('Expected a scheduled countdown callback.');+ }++ timeoutCallback();+ expect(vi.getTimerCount()).toBe(0);+ vi.advanceTimersByTime(10_000);+ expect(onClose).not.toHaveBeenCalled();+ timeoutSpy.mockRestore();+});++it('retains a closing notification until every registered mirror finishes or detaches', () => {+ const { store, notification, onClose } = createStoreWithNotification();+ const firstKey = Symbol();+ const secondKey = Symbol();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: firstKey,+ configuration: RENDERER_CONFIGURATION,+ });+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: secondKey,+ configuration: RENDERER_CONFIGURATION,+ });++ dismissToasts({ store, toastsToClose: [notification] });+ store.lifecycle.finishExit({ id: 'notification', key: firstKey });+ store.lifecycle.finishExit({ id: 'notification', key: firstKey });+ store.lifecycle.finishExit({ id: 'notification', key: Symbol() });+ expect(store.state.toasts[0]?.status).toBe('closing');+ store.lifecycle.removeRenderer({ id: 'notification', key: secondKey });++ expect(store.state.toasts).toEqual([]);+ expect(onClose).toHaveBeenCalledOnce();+ store.lifecycle.finishExit({ id: 'notification', key: secondKey });+ expect(store.state.toasts).toEqual([]);+ stop();+});++it('ignores an old mirror exit completion after the renderer is replaced', () => {+ const { store, notification, onClose } = createStoreWithNotification();+ const oldKey = Symbol();+ const currentKey = Symbol();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: oldKey,+ configuration: RENDERER_CONFIGURATION,+ });+ store.lifecycle.removeRenderer({ id: 'notification', key: oldKey });+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: currentKey,+ configuration: RENDERER_CONFIGURATION,+ });++ dismissToasts({ store, toastsToClose: [notification] });+ store.lifecycle.finishExit({ id: 'notification', key: oldKey });+ expect(store.state.toasts[0]?.status).toBe('closing');+ store.lifecycle.finishExit({ id: 'notification', key: currentKey });++ expect(store.state.toasts).toEqual([]);+ expect(onClose).toHaveBeenCalledOnce();+ stop();+});++it('applies progress updates before a registered renderer refreshes', () => {+ const { store, onClose } = createStoreWithNotification();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: Symbol(),+ configuration: RENDERER_CONFIGURATION,+ });+ vi.advanceTimersByTime(900);++ updateToastInStore({ store, id: 'notification', progress: 25 });+ vi.advanceTimersByTime(10_000);++ expect(vi.getTimerCount()).toBe(0);+ expect(onClose).not.toHaveBeenCalled();+ updateToastInStore({ store, id: 'notification', progress: undefined });+ vi.advanceTimersByTime(999);+ expect(onClose).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(onClose).toHaveBeenCalledOnce();+ stop();+});++it('applies duration updates before a registered renderer refreshes', () => {+ const { store, onClose } = createStoreWithNotification();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: Symbol(),+ configuration: RENDERER_CONFIGURATION,+ });+ vi.advanceTimersByTime(900);++ updateToastInStore({ store, id: 'notification', duration: 600 });+ vi.advanceTimersByTime(599);++ expect(onClose).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(onClose).toHaveBeenCalledOnce();+ stop();+});++it('retains a mirror duration override and its remainder while detached', () => {+ const { store, onClose } = createStoreWithNotification();+ const key = Symbol();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key,+ configuration: { ...RENDERER_CONFIGURATION, duration: 600 },+ });+ vi.advanceTimersByTime(200);+ store.lifecycle.removeRenderer({ id: 'notification', key });+ vi.advanceTimersByTime(10_000);++ expect(onClose).not.toHaveBeenCalled();+ expect(+ store.lifecycle.getCountdown('notification')?.getSnapshot(),+ ).toMatchObject({+ duration: 600,+ remainingDuration: 400,+ isPaused: true,+ });+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: Symbol(),+ configuration: { ...RENDERER_CONFIGURATION, duration: 600 },+ });+ vi.advanceTimersByTime(399);+ expect(onClose).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(onClose).toHaveBeenCalledOnce();+ stop();+});++it('defers late mirror exit completions while the provider is stopped', () => {+ const { store, notification, onClose } = createStoreWithNotification();+ const key = Symbol();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key,+ configuration: RENDERER_CONFIGURATION,+ });+ dismissToasts({ store, toastsToClose: [notification] });+ const closingSnapshot = store.state.toasts;+ stop();++ store.lifecycle.finishExit({ id: 'notification', key });++ expect(store.state.toasts).toBe(closingSnapshot);+ expect(onClose).toHaveBeenCalledOnce();+ const stopRemounted = store.lifecycle.mount();+ expect(store.state.toasts).toEqual([]);+ expect(onClose).toHaveBeenCalledOnce();+ stopRemounted();+});++it('waits for a mirror that joins while a notification is closing', () => {+ const { store, notification, onClose } = createStoreWithNotification();+ const firstKey = Symbol();+ const secondKey = Symbol();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: firstKey,+ configuration: RENDERER_CONFIGURATION,+ });+ dismissToasts({ store, toastsToClose: [notification] });+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: secondKey,+ configuration: RENDERER_CONFIGURATION,+ });++ store.lifecycle.finishExit({ id: 'notification', key: firstKey });++ expect(store.state.toasts[0]?.status).toBe('closing');+ store.lifecycle.finishExit({ id: 'notification', key: secondKey });+ expect(store.state.toasts).toEqual([]);+ expect(onClose).toHaveBeenCalledOnce();+ stop();+});++it('does not wait again for a completed mirror when its configuration refreshes', () => {+ const { store, notification, onClose } = createStoreWithNotification();+ const firstKey = Symbol();+ const secondKey = Symbol();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: firstKey,+ configuration: RENDERER_CONFIGURATION,+ });+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: secondKey,+ configuration: RENDERER_CONFIGURATION,+ });+ dismissToasts({ store, toastsToClose: [notification] });+ store.lifecycle.finishExit({ id: 'notification', key: firstKey });++ store.lifecycle.updateRenderer({+ id: 'notification',+ key: firstKey,+ configuration: { ...RENDERER_CONFIGURATION, isPaused: true },+ });+ store.lifecycle.finishExit({ id: 'notification', key: secondKey });++ expect(store.state.toasts).toEqual([]);+ expect(onClose).toHaveBeenCalledOnce();+ stop();+});++it('discards notifications after final provider teardown without dismissal callbacks', async () => {+ const { store, onClose } = createStoreWithNotification();+ const stop = store.lifecycle.mount();+ store.lifecycle.updateRenderer({+ id: 'notification',+ key: Symbol(),+ configuration: RENDERER_CONFIGURATION,+ });+ stop();++ expect(vi.getTimerCount()).toBe(0);+ expect(onClose).not.toHaveBeenCalled();+ await Promise.resolve();++ expect(store.lifecycle.isActive()).toBe(false);+ const disposedSnapshot = store.state.toasts;+ updateToastInStore({ store, id: 'notification', children: 'Stale update' });+ expect(store.state.toasts).toBe(disposedSnapshot);+ expect(store.state.toasts).toEqual([]);+ vi.advanceTimersByTime(10_000);+ expect(onClose).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+});diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/__tests__/updateToastLimit.test.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/__tests__/updateToastLimit.test.tsnew file mode 100644index 00000000000..32a2c937156--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/__tests__/updateToastLimit.test.ts@@ -0,0 +1,152 @@+import { expect, it, vi } from 'vitest';++import { createToastStore } from '../../stores/createToastStore';+import { type ToastEntry } from '../../types/ToastEntry';+import { dismissToasts } from '../dismissToasts';+import { updateToastInStore } from '../updateToastInStore';+import { updateToastLimit } from '../updateToastLimit';++const createToastEntry = ({+ id,+ onClose,+}: {+ id: string;+ onClose?: () => void;+}): ToastEntry => ({+ notification: { id, children: id, onClose },+ status: 'visible',+});++it('evicts the oldest visible notifications while preserving retained identity and order', () => {+ const store = createToastStore(4);+ const onFirstClose = vi.fn();+ const onSecondClose = vi.fn();+ const first = createToastEntry({ id: 'first', onClose: onFirstClose });+ const second = createToastEntry({ id: 'second', onClose: onSecondClose });+ const third = createToastEntry({ id: 'third' });+ const fourth = createToastEntry({ id: 'fourth' });+ const exiting: ToastEntry = {+ notification: { id: 'exiting', onClose: vi.fn() },+ status: 'closing',+ };+ store.set('mountedToasterCount', 1);+ store.set('toasts', [first, exiting, second, third, fourth]);++ updateToastLimit({ store, limit: 2 });++ expect(store.state.limit).toBe(2);+ expect(store.state.toasts.map((entry) => entry.notification.id)).toEqual([+ 'first',+ 'exiting',+ 'second',+ 'third',+ 'fourth',+ ]);+ expect(store.state.toasts.map((entry) => entry.status)).toEqual([+ 'closing',+ 'closing',+ 'closing',+ 'visible',+ 'visible',+ ]);+ expect(store.state.toasts[1]).toBe(exiting);+ expect(store.state.toasts[3]).toBe(third);+ expect(store.state.toasts[4]).toBe(fourth);+ expect(onFirstClose).toHaveBeenCalledOnce();+ expect(onSecondClose).toHaveBeenCalledOnce();+ expect(exiting.notification.onClose).not.toHaveBeenCalled();+});++it('keeps live notifications and their identities when the limit grows', () => {+ const store = createToastStore(1);+ const onClose = vi.fn();+ const first = createToastEntry({ id: 'first', onClose });+ const toasts = [first];+ store.set('toasts', toasts);++ updateToastLimit({ store, limit: 4 });++ expect(store.state.limit).toBe(4);+ expect(store.state.toasts).toBe(toasts);+ expect(onClose).not.toHaveBeenCalled();+});++it('does not publish or repeat callbacks when the configured limit is unchanged', () => {+ const store = createToastStore(2);+ const listener = vi.fn();+ store.subscribe(listener);++ updateToastLimit({ store, limit: 2 });++ expect(listener).not.toHaveBeenCalled();+});++it.each([0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY])(+ 'rejects invalid limit %s without changing the store',+ (limit) => {+ const store = createToastStore(2);+ const first = createToastEntry({ id: 'first' });+ store.set('toasts', [first]);+ const snapshot = store.state;+ const listener = vi.fn();+ store.subscribe(listener);++ expect(() => updateToastLimit({ store, limit })).toThrow(+ 'Toast limit must be a positive integer.',+ );+ expect(store.state).toBe(snapshot);+ expect(listener).not.toHaveBeenCalled();+ },+);++it('removes evicted notifications immediately when no renderer is mounted', () => {+ const store = createToastStore(3);+ const onClose = vi.fn();+ const first = createToastEntry({ id: 'first', onClose });+ const second = createToastEntry({ id: 'second' });+ const third = createToastEntry({ id: 'third' });+ store.set('toasts', [first, second, third]);++ updateToastLimit({ store, limit: 2 });++ expect(store.state.toasts).toEqual([second, third]);+ expect(store.state.toasts[0]).toBe(second);+ expect(store.state.toasts[1]).toBe(third);+ expect(onClose).toHaveBeenCalledOnce();+});++it('preserves reentrant callback updates and enqueues without closing an evicted notification twice', () => {+ const store = createToastStore(3);+ store.set('mountedToasterCount', 1);+ const onSecondClose = vi.fn();+ const second = createToastEntry({ id: 'second', onClose: onSecondClose });+ const retained = createToastEntry({ id: 'retained' });+ const replacement = createToastEntry({ id: 'replacement' });+ const onFirstClose = vi.fn(() => {+ updateToastInStore({ store, id: 'retained', children: 'Updated' });+ updateToastInStore({ store, id: 'first', children: 'Revived' });+ dismissToasts({ store, toastsToClose: [second] });+ dismissToasts({+ store,+ toastsToClose: [store.state.toasts[2]!],+ nextToasts: [...store.state.toasts, replacement],+ });+ });+ const first = createToastEntry({ id: 'first', onClose: onFirstClose });+ store.set('toasts', [first, second, retained]);++ updateToastLimit({ store, limit: 1 });++ expect(onFirstClose).toHaveBeenCalledOnce();+ expect(onSecondClose).toHaveBeenCalledOnce();+ expect(store.state.toasts.map((entry) => entry.notification.id)).toEqual([+ 'first',+ 'second',+ 'retained',+ 'replacement',+ ]);+ expect(store.state.toasts[0]?.notification.children).toBe('first');+ expect(store.state.toasts[2]?.notification.children).toBe('Updated');+ expect(store.state.toasts[2]?.status).toBe('closing');+ expect(store.state.toasts[3]).toBe(replacement);+});diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/assertValidToastLimit.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/assertValidToastLimit.tsnew file mode 100644index 00000000000..a2f03c06ac4--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/assertValidToastLimit.ts@@ -0,0 +1,7 @@+import { isPositiveInteger } from '@sniptt/guards';++export const assertValidToastLimit = (limit: number) => {+ if (!isPositiveInteger(limit)) {+ throw new Error('Toast limit must be a positive integer.');+ }+};diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/completeToastExit.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/completeToastExit.tsindex 3e6adeed0f6..33ef8104fee 100644--- a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/completeToastExit.ts+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/completeToastExit.ts@@ -1,11 +1,13 @@-import { type createToastStore } from '../stores/createToastStore';+import { type Store } from '@base-ui/utils/store';++import { type ToastStoreState } from '../types/ToastStoreState';import { type ToastEntry } from '../types/ToastEntry';export const completeToastExit = ({store,toast,}: {- store: ReturnType<typeof createToastStore>;+ store: Store<ToastStoreState>;toast: ToastEntry;}) => {const { toasts } = store.state;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.tsindex dacc7395baa..55fb9911750 100644--- a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/createToastCountdown.ts+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/createToastCountdown.ts@@ -30,9 +30,11 @@ export const createToastCountdown = ({let startedAt: number | undefined;let timeout: ReturnType<typeof setTimeout> | undefined;let revision = 0;+ let timerRevision = 0;let isClosed = false;const stop = () => {+ timerRevision += 1;if (isDefined(startedAt)) {remainingDuration = Math.max(0,@@ -85,8 +87,13 @@ export const createToastCountdown = ({}startedAt = performance.now();+ const scheduledRevision = timerRevision;timeout = setTimeout(() => {+ if (scheduledRevision !== timerRevision) {+ return;+ }+stop();if (remainingDuration > 0) {diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/createToastCountdownStore.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/createToastCountdownStore.tsnew file mode 100644index 00000000000..14b57791c8d--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/createToastCountdownStore.ts@@ -0,0 +1,38 @@+import { createToastCountdown } from './createToastCountdown';++type CountdownSnapshot = Parameters<+ Parameters<typeof createToastCountdown>[0]['onChange']+>[0];++export const createToastCountdownStore = ({+ duration,+ isPaused,+}: Pick<CountdownSnapshot, 'duration' | 'isPaused'>) => {+ let snapshot: CountdownSnapshot = {+ duration,+ remainingDuration: duration,+ revision: 0,+ isPaused,+ };+ const listeners = new Set<() => void>();+ const countdown = createToastCountdown({+ onChange: (nextSnapshot) => {+ snapshot = nextSnapshot;++ for (const listener of listeners) {+ listener();+ }+ },+ });++ return {+ ...countdown,+ getSnapshot: () => snapshot,+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ };+};diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/createToastLifecycle.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/createToastLifecycle.tsnew file mode 100644index 00000000000..cab850722c2--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/createToastLifecycle.ts@@ -0,0 +1,200 @@+import { type Store } from '@base-ui/utils/store';++import { isDefined } from '@ui/utilities/utils/isDefined';++import { DEFAULT_TOAST_DURATION } from '../constants/DefaultToastDuration';+import { type ToastStoreState } from '../types/ToastStoreState';+import { completeToastExit } from './completeToastExit';+import { createToastCountdownStore } from './createToastCountdownStore';+import { dismissToasts } from './dismissToasts';+import { isToastVisible } from './isToastVisible';++type RendererConfiguration = {+ duration?: number;+ isProgress?: boolean;+ isPaused: boolean;+};++type NotificationLifecycle = {+ countdown: ReturnType<typeof createToastCountdownStore>;+ renderers: Map<symbol, RendererConfiguration>;+ pendingExits?: Set<symbol>;+ lastRenderer?: RendererConfiguration;+};++export const createToastLifecycle = (store: Store<ToastStoreState>) => {+ const notifications = new Map<string, NotificationLifecycle>();+ let isMounted = false;+ let isDisposed = false;+ let lifecycleRevision = 0;++ const getNotification = (id: string) => {+ const existingNotification = notifications.get(id);++ if (isDefined(existingNotification)) {+ return existingNotification;+ }++ const notification: NotificationLifecycle = {+ countdown: createToastCountdownStore({+ duration: DEFAULT_TOAST_DURATION,+ isPaused: true,+ }),+ renderers: new Map<symbol, RendererConfiguration>(),+ };+ notifications.set(id, notification);+ return notification;+ };++ const completeExit = (id: string) => {+ if (!isMounted) {+ return;+ }++ const lifecycle = notifications.get(id);++ if (+ !isDefined(lifecycle?.pendingExits) ||+ lifecycle.pendingExits.size > 0+ ) {+ return;+ }++ const toast = store.state.toasts.find(+ (entry) => entry.notification.id === id,+ );++ if (!isDefined(toast)) {+ return;+ }++ completeToastExit({ store, toast });+ };++ const synchronize = () => {+ for (const [id, lifecycle] of notifications) {+ const toast = store.state.toasts.find(+ (entry) => entry.notification.id === id,+ );++ if (!isDefined(toast)) {+ lifecycle.countdown.stop();+ notifications.delete(id);+ continue;+ }++ const firstRenderer =+ lifecycle.renderers.values().next().value ?? lifecycle.lastRenderer;+ lifecycle.lastRenderer = firstRenderer;+ const isPaused =+ !isMounted ||+ lifecycle.renderers.size === 0 ||+ [...lifecycle.renderers.values()].some((renderer) => renderer.isPaused);++ lifecycle.countdown.update({+ duration:+ firstRenderer?.duration ??+ toast.notification.duration ??+ DEFAULT_TOAST_DURATION,+ durationRevision: toast.durationRevision ?? 0,+ isProgress:+ firstRenderer?.isProgress ?? isDefined(toast.notification.progress),+ isPaused,+ isActive: toast.status === 'visible',+ onClose: () => {+ const currentToast = store.state.toasts.find(+ (entry) => entry.notification.id === id && isToastVisible(entry),+ );++ if (!isMounted || !isDefined(currentToast)) {+ return;+ }++ dismissToasts({ store, toastsToClose: [currentToast] });+ },+ });++ if (toast.status === 'visible') {+ continue;+ }++ lifecycle.pendingExits ??= new Set(lifecycle.renderers.keys());+ completeExit(id);+ }+ };++ const updateRenderer = ({+ id,+ key,+ configuration,+ }: {+ id: string;+ key: symbol;+ configuration: RendererConfiguration;+ }) => {+ const lifecycle = getNotification(id);++ if (!lifecycle.renderers.has(key)) {+ lifecycle.countdown.stop();+ lifecycle.pendingExits?.add(key);+ }++ lifecycle.renderers.set(key, configuration);+ synchronize();+ return lifecycle.countdown;+ };++ const removeRenderer = ({ id, key }: { id: string; key: symbol }) => {+ const lifecycle = notifications.get(id);++ if (!isDefined(lifecycle)) {+ return;+ }++ lifecycle.renderers.delete(key);+ lifecycle.pendingExits?.delete(key);+ synchronize();+ };++ const finishExit = ({ id, key }: { id: string; key: symbol }) => {+ notifications.get(id)?.pendingExits?.delete(key);+ completeExit(id);+ };++ const mount = () => {+ isMounted = true;+ isDisposed = false;+ lifecycleRevision += 1;+ const unsubscribe = store.subscribe(synchronize);+ synchronize();++ return () => {+ isMounted = false;+ unsubscribe();++ for (const lifecycle of notifications.values()) {+ lifecycle.countdown.stop();+ }++ const teardownRevision = ++lifecycleRevision;+ queueMicrotask(() => {+ if (isMounted || lifecycleRevision !== teardownRevision) {+ return;+ }++ isDisposed = true;+ notifications.clear();+ store.set('toasts', []);+ });+ };+ };++ return {+ mount,+ isActive: () => !isDisposed,+ getCountdown: (id: string) => notifications.get(id)?.countdown,+ updateRenderer,+ removeRenderer,+ finishExit,+ };+};diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/dismissToasts.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/dismissToasts.tsindex 79e513f02b4..cda27372b0f 100644--- a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/dismissToasts.ts+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/dismissToasts.ts@@ -1,4 +1,6 @@-import { type createToastStore } from '../stores/createToastStore';+import { type Store } from '@base-ui/utils/store';++import { type ToastStoreState } from '../types/ToastStoreState';import { type ToastEntry } from '../types/ToastEntry';import { isToastVisible } from './isToastVisible';@@ -7,12 +9,17 @@ export const dismissToasts = ({toastsToClose,nextToasts = store.state.toasts,}: {- store: ReturnType<typeof createToastStore>;+ store: Store<ToastStoreState>;toastsToClose: ToastEntry[];nextToasts?: ToastEntry[];}) => {+ const visibleToastsToClose = toastsToClose.filter(+ (toast) => isToastVisible(toast) && store.state.toasts.includes(toast),+ );const toasts = nextToasts.map((toast): ToastEntry =>- toastsToClose.includes(toast) ? { ...toast, status: 'closing' } : toast,+ visibleToastsToClose.includes(toast)+ ? { ...toast, status: 'closing' }+ : toast,);const isToasterMounted = store.state.mountedToasterCount > 0;@@ -22,7 +29,7 @@ export const dismissToasts = ({isToasterMounted ? toasts : toasts.filter(isToastVisible),);- for (const toast of toastsToClose) {+ for (const toast of visibleToastsToClose) {toast.notification.onClose?.();}};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.tsindex 88e16e5f371..5c78d999c62 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@@ -11,6 +11,10 @@ export const updateToastInStore = ({id,...changes}: ToastUpdate & { store: ReturnType<typeof createToastStore> }) => {+ if (!store.lifecycle.isActive()) {+ return;+ }+const toastToUpdate = store.state.toasts.find((toast) => toast.notification.id === id && isToastVisible(toast),);diff --git a/packages/twenty-ui/src/components/feedback/Toast/internal/utils/updateToastLimit.ts b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/updateToastLimit.tsnew file mode 100644index 00000000000..7a4456c256e--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toast/internal/utils/updateToastLimit.ts@@ -0,0 +1,31 @@+import { type createToastStore } from '../stores/createToastStore';+import { assertValidToastLimit } from './assertValidToastLimit';+import { dismissToasts } from './dismissToasts';+import { isToastVisible } from './isToastVisible';++export const updateToastLimit = ({+ store,+ limit,+}: {+ store: ReturnType<typeof createToastStore>;+ limit: number;+}) => {+ assertValidToastLimit(limit);++ if (store.state.limit === limit) {+ return;+ }++ store.set('limit', limit);+ const visibleToasts = store.state.toasts.filter(isToastVisible);+ const removedCount = Math.max(0, visibleToasts.length - limit);++ if (removedCount === 0) {+ return;+ }++ dismissToasts({+ store,+ toastsToClose: visibleToasts.slice(0, removedCount),+ });+};diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/Toaster.lifecycle.stories.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/Toaster.lifecycle.stories.tsxnew file mode 100644index 00000000000..e63436ad850--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/Toaster.lifecycle.stories.tsx@@ -0,0 +1,896 @@+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 { ToasterLifecycleExample } from './ToasterLifecycleExample';+import { ToasterLifecycleTimingOverrideExample } from './ToasterLifecycleTimingOverrideExample';+import { ToasterPortalExample } from './ToasterPortalExample';+import { ToasterProviderLayoutReplayEffect } from './ToasterProviderLayoutReplayEffect';+import { ToasterProviderPassiveReplayEffect } from './ToasterProviderPassiveReplayEffect';+import { ToasterProviderReplayExample } from './ToasterProviderReplayExample';+import { ToasterProviderSuspenseExample } from './ToasterProviderSuspenseExample';++const meta: Meta<typeof ToasterLifecycleExample> = {+ id: 'ui-feedback-toaster-lifecycle',+ title: 'UI/Components/Feedback/Toaster/Lifecycle',+ component: ToasterLifecycleExample,+ decorators: [ComponentDecorator],+ args: { duration: 1800, onClose: fn() },+ parameters: { container: { width: 800, height: 350 } },+};++export default meta;+type Story = StoryObj<typeof ToasterLifecycleExample>;++const wait = (duration: number) =>+ new Promise((resolve) => setTimeout(resolve, duration));++const getLifecycle = (canvasElement: HTMLElement) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const user = userEvent.setup();+ const first = within(+ body.getByRole('region', { name: 'First lifecycle notifications' }),+ );+ const second = within(+ body.getByRole('region', { name: 'Second lifecycle notifications' }),+ );++ return { canvas, body, user, first, second };+};++export const Documentation: Story = {};++export const ReactiveLimitPreservesNewestNotifications: Story = {+ play: async ({ canvasElement, args }) => {+ const { canvas, user, first, second } = getLifecycle(canvasElement);+ const add = canvas.getByRole('button', {+ name: 'Add persistent notification',+ });+ await user.click(add);+ await user.click(add);+ await user.click(add);+ const firstNotifications = first.getAllByRole('status');+ const secondNotifications = second.getAllByRole('status');+ const newestFirst = firstNotifications[2]!;+ const newestSecond = secondNotifications[2]!;+ const newestId = newestFirst.id;+ expect(secondNotifications.map((notification) => notification.id)).toEqual(+ firstNotifications.map((notification) => notification.id),+ );+ await user.click(+ canvas.getByRole('button', { name: 'Limit to one notification' }),+ );+ await waitFor(() => {+ expect(first.getAllByRole('status')).toHaveLength(1);+ expect(second.getAllByRole('status')).toHaveLength(1);+ });+ expect(first.getByRole('status')).toBe(newestFirst);+ expect(second.getByRole('status')).toBe(newestSecond);+ expect(newestFirst.id).toBe(newestId);+ expect(args.onClose).toHaveBeenNthCalledWith(1, 'Lifecycle notification 1');+ expect(args.onClose).toHaveBeenNthCalledWith(2, 'Lifecycle notification 2');+ await user.click(+ canvas.getByRole('button', { name: 'Limit to one notification' }),+ );+ expect(args.onClose).toHaveBeenCalledTimes(2);+ await user.click(+ canvas.getByRole('button', { name: 'Limit to four notifications' }),+ );+ await user.click(add);+ await user.click(add);+ expect(first.getAllByRole('status')).toHaveLength(3);+ expect(second.getAllByRole('status')).toHaveLength(3);+ expect(first.getAllByRole('status')[0]).toBe(newestFirst);+ expect(+ first+ .getAllByRole('status')+ .map((notification) => notification.textContent),+ ).toEqual(+ second+ .getAllByRole('status')+ .map((notification) => notification.textContent),+ );+ expect(args.onClose).toHaveBeenCalledTimes(2);+ },+};++export const ProviderLimitsAndUpdatesRemainIsolated: Story = {+ args: { hasIndependentProvider: true },+ play: async ({ canvasElement, args }) => {+ const { canvas, body, user, first } = getLifecycle(canvasElement);+ const independentSource = within(+ canvas.getByRole('region', { name: 'Independent source' }),+ );+ const independent = within(+ body.getByRole('region', { name: 'Independent notifications' }),+ );+ const add = canvas.getByRole('button', {+ name: 'Add persistent notification',+ });+ await user.click(add);+ await user.click(add);+ await user.click(add);+ await user.click(+ independentSource.getByRole('button', { name: 'Add notification' }),+ );+ const independentToast = independent.getByRole('status');+ await user.click(+ canvas.getByRole('button', { name: 'Limit to one notification' }),+ );+ await waitFor(() => expect(first.getAllByRole('status')).toHaveLength(1));+ expect(independent.getByRole('status')).toBe(independentToast);+ expect(independentToast).toHaveTextContent('Notification 1');+ await user.click(+ within(+ canvas.getByRole('region', { name: 'Lifecycle source' }),+ ).getByRole('button', { name: 'Update last notification' }),+ );+ expect(first.getByRole('status')).toHaveTextContent(+ 'Updated lifecycle notification',+ );+ expect(independentToast).toHaveTextContent('Notification 1');+ await user.click(+ canvas.getByRole('button', { name: 'Unmount notification provider' }),+ );+ expect(independentToast).toBeVisible();+ expect(args.onClose).toHaveBeenCalledTimes(2);+ await user.click(+ independentSource.getByRole('button', {+ name: 'Close all notifications',+ }),+ );+ await waitFor(() => expect(independentToast).not.toBeInTheDocument());+ expect(args.onClose).toHaveBeenCalledTimes(3);+ expect(args.onClose).toHaveBeenLastCalledWith('Independent notification');+ },+};++export const MirrorsShareUpdatesAndDismissal: Story = {+ play: async ({ canvasElement, args }) => {+ const { canvas, user, first, second } = getLifecycle(canvasElement);+ await user.click(+ canvas.getByRole('button', { name: 'Add persistent notification' }),+ );+ const firstToast = first.getByRole('status');+ const secondToast = second.getByRole('status');+ expect(firstToast.id).toBe(secondToast.id);+ await user.click(+ canvas.getByRole('button', { name: 'Update last notification' }),+ );+ expect(first.getByRole('status')).toBe(firstToast);+ expect(second.getByRole('status')).toBe(secondToast);+ expect(firstToast).toHaveTextContent('Updated lifecycle notification');+ expect(secondToast).toHaveTextContent('Updated lifecycle notification');+ await user.click(+ canvas.getByRole('button', { name: 'Dismiss and update notification' }),+ );+ expect(args.onClose).toHaveBeenCalledOnce();+ await waitFor(() => {+ expect(firstToast).not.toBeInTheDocument();+ expect(secondToast).not.toBeInTheDocument();+ });+ await user.click(+ canvas.getByRole('button', { name: 'Restart last countdown' }),+ );+ await user.click(+ canvas.getByRole('button', { name: 'Update last notification' }),+ );+ await wait(2000);+ expect(first.queryByRole('status')).not.toBeInTheDocument();+ expect(second.queryByRole('status')).not.toBeInTheDocument();+ expect(args.onClose).toHaveBeenCalledOnce();+ },+};++export const MirrorsExpireOnce: Story = {+ play: async ({ canvasElement, args }) => {+ const { canvas, user, first, second } = getLifecycle(canvasElement);+ await user.click(+ canvas.getByRole('button', { name: 'Add timed notification' }),+ );+ const firstToast = first.getByRole('status');+ const secondToast = second.getByRole('status');+ await waitFor(() => expect(args.onClose).toHaveBeenCalledOnce(), {+ timeout: 2600,+ });+ await waitFor(() => {+ expect(firstToast).not.toBeInTheDocument();+ expect(secondToast).not.toBeInTheDocument();+ });+ await wait(500);+ expect(args.onClose).toHaveBeenCalledOnce();+ },+};++export const UndefinedDurationOverrideRestoresDefaultCountdown: Story = {+ args: { duration: 1200 },+ render: (args) => (+ <ToasterLifecycleTimingOverrideExample+ duration={args.duration}+ initialTimingOverrides={{ duration: 400 }}+ onClose={args.onClose}+ />+ ),+ play: async ({ canvasElement, args }) => {+ const { canvas, user, first, second } = getLifecycle(canvasElement);+ const add = canvas.getByRole('button', {+ name: 'Add override notification',+ });+ await user.click(add);+ const initialFirst = first.getByRole('status');+ const initialSecond = second.getByRole('status');+ await waitFor(() => expect(args.onClose).toHaveBeenCalledOnce(), {+ timeout: 1000,+ });+ await waitFor(() => {+ expect(initialFirst).not.toBeInTheDocument();+ expect(initialSecond).not.toBeInTheDocument();+ });+ await user.click(+ canvas.getByRole('button', { name: 'Use default duration override' }),+ );+ await user.click(add);+ const defaultFirst = first.getByRole('status');+ const defaultSecond = second.getByRole('status');+ expect(defaultFirst.id).toBe(defaultSecond.id);+ await wait(1700);+ expect(defaultFirst).toBeVisible();+ expect(defaultSecond).toBeVisible();+ expect(args.onClose).toHaveBeenCalledOnce();+ await waitFor(() => expect(args.onClose).toHaveBeenCalledTimes(2), {+ timeout: 5000,+ });+ await waitFor(() => {+ expect(defaultFirst).not.toBeInTheDocument();+ expect(defaultSecond).not.toBeInTheDocument();+ });+ expect(args.onClose).toHaveBeenCalledTimes(2);+ expect(args.onClose).toHaveBeenNthCalledWith(1, 'Override notification 1');+ expect(args.onClose).toHaveBeenNthCalledWith(2, 'Override notification 2');+ },+};++export const UndefinedProgressOverrideStartsStoredCountdown: Story = {+ args: { duration: 800 },+ render: (args) => (+ <ToasterLifecycleTimingOverrideExample+ duration={args.duration}+ progress={25}+ initialTimingOverrides={{ progress: 75 }}+ onClose={args.onClose}+ />+ ),+ play: async ({ canvasElement, args }) => {+ const { canvas, user, first, second } = getLifecycle(canvasElement);+ await user.click(+ canvas.getByRole('button', { name: 'Add override notification' }),+ );+ const firstToast = first.getByRole('status');+ const secondToast = second.getByRole('status');+ expect(+ within(firstToast).getByRole('progressbar', { hidden: true }),+ ).toHaveAttribute('aria-valuenow', '75');+ expect(+ within(secondToast).getByRole('progressbar', { hidden: true }),+ ).toHaveAttribute('aria-valuenow', '75');+ await wait(1200);+ expect(firstToast).toBeVisible();+ expect(secondToast).toBeVisible();+ expect(args.onClose).not.toHaveBeenCalled();+ await user.click(+ canvas.getByRole('button', { name: 'Clear progress override' }),+ );+ expect(+ within(firstToast).queryByRole('progressbar', { hidden: true }),+ ).not.toBeInTheDocument();+ expect(+ within(secondToast).queryByRole('progressbar', { hidden: true }),+ ).not.toBeInTheDocument();+ await waitFor(() => expect(args.onClose).toHaveBeenCalledOnce(), {+ timeout: 1600,+ });+ await waitFor(() => {+ expect(firstToast).not.toBeInTheDocument();+ expect(secondToast).not.toBeInTheDocument();+ });+ expect(args.onClose).toHaveBeenCalledWith('Override notification 1');+ },+};++export const StrictModeMirrorsExpireAndTeardownOnce: Story = {+ render: (args) => (+ <StrictMode>+ <ToasterLifecycleExample+ // oxlint-disable-next-line react/jsx-props-no-spreading+ {...args}+ />+ </StrictMode>+ ),+ play: async ({ canvasElement, args }) => {+ const { canvas, body, user, first, second } = getLifecycle(canvasElement);+ const add = canvas.getByRole('button', { name: 'Add timed notification' });+ await user.click(add);+ const firstToast = first.getByRole('status');+ const secondToast = second.getByRole('status');+ expect(firstToast.id).toBe(secondToast.id);+ await waitFor(() => expect(args.onClose).toHaveBeenCalledOnce(), {+ timeout: 2600,+ });+ await waitFor(() => {+ expect(firstToast).not.toBeInTheDocument();+ expect(secondToast).not.toBeInTheDocument();+ });+ await user.click(add);+ await wait(400);+ await user.click(+ canvas.getByRole('button', { name: 'Unmount notification provider' }),+ );+ await wait(2000);+ expect(body.queryByRole('status')).not.toBeInTheDocument();+ expect(args.onClose).toHaveBeenCalledOnce();+ expect(args.onClose).toHaveBeenCalledWith('Lifecycle notification 1');+ },+};++export const HoverAndFocusPauseAcrossMirrors: Story = {+ args: { hasUnrelatedNotificationActions: true },+ play: async ({ canvasElement, args }) => {+ const { canvas, user, first, second } = getLifecycle(canvasElement);+ await user.click(+ canvas.getByRole('button', { name: 'Add timed notification' }),+ );+ const firstToast = first.getByRole('status');+ const secondToast = second.getByRole('status');+ await wait(400);+ const action = within(firstToast).getByRole('button', {+ name: 'Notification action',+ });+ await user.click(action);+ await user.unhover(firstToast);+ await user.hover(secondToast);+ expect(action).toHaveFocus();+ const getCountdown = (toast: HTMLElement) =>+ toast.querySelector<HTMLElement>(+ '[style*="--toast-countdown-duration"]',+ )!;+ const firstCountdown = getCountdown(firstToast);+ const secondCountdown = getCountdown(secondToast);+ expect(firstCountdown).toHaveAttribute('data-paused');+ expect(secondCountdown).toHaveAttribute('data-paused');+ await user.click(+ within(firstToast).getByRole('button', {+ name: 'Add unrelated notification',+ }),+ );+ expect(getCountdown(firstToast)).toBe(firstCountdown);+ expect(getCountdown(secondToast)).toBe(secondCountdown);+ await user.click(+ within(firstToast).getByRole('button', {+ name: 'Update unrelated notification',+ }),+ );+ expect(first.getByText('Updated unrelated notification')).toBeVisible();+ expect(second.getByText('Updated unrelated notification')).toBeVisible();+ expect(getCountdown(firstToast)).toBe(firstCountdown);+ expect(getCountdown(secondToast)).toBe(secondCountdown);+ await user.unhover(firstToast);+ await user.hover(secondToast);+ await wait(2000);+ expect(firstToast).toBeVisible();+ expect(secondToast).toBeVisible();+ expect(args.onClose).not.toHaveBeenCalled();+ await user.click(+ canvas.getByRole('button', { name: 'Outside notifications' }),+ );+ await user.hover(secondToast);+ await wait(2000);+ expect(firstToast).toBeVisible();+ expect(secondToast).toBeVisible();+ expect(args.onClose).not.toHaveBeenCalled();+ await user.unhover(secondToast);+ await waitFor(() => expect(args.onClose).toHaveBeenCalledOnce(), {+ timeout: 1800,+ });+ await waitFor(() => {+ expect(firstToast).not.toBeInTheDocument();+ expect(secondToast).not.toBeInTheDocument();+ });+ },+};++export const LateMirrorMountSharesRemainingTime: Story = {+ play: async ({ canvasElement, args }) => {+ const { canvas, body, user, first } = getLifecycle(canvasElement);+ await user.click(+ canvas.getByRole('button', { name: 'Detach second renderer' }),+ );+ await user.click(+ canvas.getByRole('button', { name: 'Add timed notification' }),+ );+ const original = first.getByRole('status');+ await wait(700);+ await user.click(+ canvas.getByRole('button', { name: 'Mount second renderer' }),+ );+ const mirror = within(+ body.getByRole('region', { name: 'Second lifecycle notifications' }),+ ).getByRole('status');+ expect(mirror.id).toBe(original.id);+ await wait(400);+ expect(original).toBeVisible();+ expect(mirror).toBeVisible();+ expect(args.onClose).not.toHaveBeenCalled();+ await waitFor(() => expect(args.onClose).toHaveBeenCalledOnce(), {+ timeout: 1000,+ });+ await waitFor(() => {+ expect(original).not.toBeInTheDocument();+ expect(mirror).not.toBeInTheDocument();+ });+ },+};++export const DetachingOneMirrorKeepsCountdownRunning: Story = {+ play: async ({ canvasElement, args }) => {+ const { canvas, user, second } = getLifecycle(canvasElement);+ await user.click(+ canvas.getByRole('button', { name: 'Add timed notification' }),+ );+ const remainingMirror = second.getByRole('status');+ await wait(700);+ await user.click(+ canvas.getByRole('button', { name: 'Detach first renderer' }),+ );+ expect(second.getByRole('status')).toBe(remainingMirror);+ await wait(400);+ expect(remainingMirror).toBeVisible();+ expect(args.onClose).not.toHaveBeenCalled();+ await waitFor(() => expect(args.onClose).toHaveBeenCalledOnce(), {+ timeout: 1000,+ });+ await waitFor(() => expect(remainingMirror).not.toBeInTheDocument());+ },+};++export const LastRendererDetachPreservesRemainingTime: Story = {+ play: async ({ canvasElement, args }) => {+ const { canvas, body, user, first } = getLifecycle(canvasElement);+ await user.click(+ canvas.getByRole('button', { name: 'Add timed notification' }),+ );+ const originalId = first.getByRole('status').id;+ await wait(700);+ await user.click(+ canvas.getByRole('button', { name: 'Detach all renderers' }),+ );+ await wait(2000);+ expect(body.queryByRole('status')).not.toBeInTheDocument();+ expect(args.onClose).not.toHaveBeenCalled();+ await user.click(+ canvas.getByRole('button', { name: 'Mount first renderer' }),+ );+ const remounted = body.getByRole('status');+ expect(remounted.id).toBe(originalId);+ await wait(400);+ expect(remounted).toBeVisible();+ expect(args.onClose).not.toHaveBeenCalled();+ await waitFor(() => expect(args.onClose).toHaveBeenCalledOnce(), {+ timeout: 1000,+ });+ await waitFor(() => expect(remounted).not.toBeInTheDocument());+ },+};++export const ExitWaitsForEveryMirror: Story = {+ args: { hasSlowMirrorExit: true },+ play: async ({ canvasElement, args }) => {+ const { canvas, body, user, first, second } = getLifecycle(canvasElement);+ await user.click(+ canvas.getByRole('button', { name: 'Add persistent notification' }),+ );+ const firstToast = first.getByRole('status');+ const secondToast = second.getByRole('status');+ const firstRegion = body.getByRole('region', {+ name: 'First lifecycle notifications',+ });+ const secondRegion = body.getByRole('region', {+ name: 'Second lifecycle notifications',+ });+ await waitFor(() => {+ expect(firstRegion.getAnimations({ subtree: true })).toHaveLength(0);+ expect(secondRegion.getAnimations({ subtree: true })).toHaveLength(0);+ });+ await user.click(+ canvas.getByRole('button', { name: 'Close last notification' }),+ );+ expect(args.onClose).toHaveBeenCalledOnce();+ if (!window.matchMedia('(prefers-reduced-motion: reduce)').matches) {+ await wait(650);+ expect(firstToast).toBeInTheDocument();+ expect(secondToast).toBeInTheDocument();+ }+ await waitFor(+ () => {+ expect(firstToast).not.toBeInTheDocument();+ expect(secondToast).not.toBeInTheDocument();+ },+ { timeout: 1800 },+ );+ expect(args.onClose).toHaveBeenCalledOnce();+ },+};++export const DetachingClosingRenderersDoesNotReviveNotifications: Story = {+ play: async ({ canvasElement, args }) => {+ const { canvas, body, user, first } = getLifecycle(canvasElement);+ await user.click(+ canvas.getByRole('button', { name: 'Add persistent notification' }),+ );+ const originalId = first.getByRole('status').id;+ await user.click(+ canvas.getByRole('button', { name: 'Dismiss and detach renderers' }),+ );+ expect(args.onClose).toHaveBeenCalledOnce();+ await user.click(+ canvas.getByRole('button', { name: 'Mount both renderers' }),+ );+ expect(body.queryByRole('status')).not.toBeInTheDocument();+ await user.click(+ canvas.getByRole('button', { name: 'Restart last countdown' }),+ );+ await user.click(+ canvas.getByRole('button', { name: 'Update last notification' }),+ );+ expect(body.queryByRole('status')).not.toBeInTheDocument();+ await user.click(+ canvas.getByRole('button', { name: 'Add persistent notification' }),+ );+ const replacement = within(+ body.getByRole('region', { name: 'First lifecycle notifications' }),+ ).getByRole('status');+ expect(replacement.id).not.toBe(originalId);+ await wait(2000);+ expect(replacement).toBeVisible();+ expect(args.onClose).toHaveBeenCalledOnce();+ },+};++export const ProviderRemountCancelsOldCountdowns: Story = {+ play: async ({ canvasElement, args }) => {+ const { canvas, body, user, first } = getLifecycle(canvasElement);+ await user.click(+ canvas.getByRole('button', { name: 'Add timed notification' }),+ );+ const originalId = first.getByRole('status').id;+ await wait(500);+ await user.click(+ canvas.getByRole('button', { name: 'Unmount notification provider' }),+ );+ await user.click(+ canvas.getByRole('button', { name: 'Mount notification provider' }),+ );+ expect(body.queryByRole('status')).not.toBeInTheDocument();+ await user.click(+ canvas.getByRole('button', { name: 'Add persistent notification' }),+ );+ const replacement = within(+ body.getByRole('region', { name: 'First lifecycle notifications' }),+ ).getByRole('status');+ expect(replacement.id).not.toBe(originalId);+ await wait(2000);+ expect(replacement).toBeVisible();+ expect(args.onClose).not.toHaveBeenCalled();+ await user.click(+ canvas.getByRole('button', { name: 'Close last notification' }),+ );+ expect(args.onClose).toHaveBeenCalledOnce();+ },+};++export const PreviousProviderOperationsRemainInactive: Story = {+ play: async ({ canvasElement, args }) => {+ const { canvas, body, user, first } = getLifecycle(canvasElement);+ const add = canvas.getByRole('button', {+ name: 'Add persistent notification',+ });+ const runPreviousOperations = canvas.getByRole('button', {+ name: 'Run previous provider operations',+ });+ await user.click(add);+ const originalId = first.getByRole('status').id;+ await user.click(+ canvas.getByRole('button', { name: 'Unmount notification provider' }),+ );+ await user.click(runPreviousOperations);+ expect(body.queryByRole('status')).not.toBeInTheDocument();+ expect(args.onClose).not.toHaveBeenCalled();+ await user.click(+ canvas.getByRole('button', { name: 'Mount notification provider' }),+ );+ await user.click(+ canvas.getByRole('button', { name: 'Add persistent notification' }),+ );+ const replacementFirst = within(+ body.getByRole('region', { name: 'First lifecycle notifications' }),+ ).getByRole('status');+ const replacementSecond = within(+ body.getByRole('region', { name: 'Second lifecycle notifications' }),+ ).getByRole('status');+ const replacementId = replacementFirst.id;+ expect(replacementId).not.toBe(originalId);+ await user.click(+ canvas.getByRole('button', { name: 'Update last notification' }),+ );+ await user.click(runPreviousOperations);+ await user.click(runPreviousOperations);+ expect(body.getAllByRole('status')).toHaveLength(2);+ expect(replacementFirst).toBeVisible();+ expect(replacementSecond).toBeVisible();+ expect(replacementFirst.id).toBe(replacementId);+ expect(replacementSecond.id).toBe(replacementId);+ expect(replacementFirst).toHaveTextContent(+ 'Updated lifecycle notification',+ );+ expect(replacementSecond).toHaveTextContent(+ 'Updated lifecycle notification',+ );+ expect(+ body.queryByText('Previous provider notification enqueued'),+ ).not.toBeInTheDocument();+ expect(args.onClose).not.toHaveBeenCalled();+ await user.click(+ canvas.getByRole('button', { name: 'Close last notification' }),+ );+ await waitFor(() => {+ expect(replacementFirst).not.toBeInTheDocument();+ expect(replacementSecond).not.toBeInTheDocument();+ });+ expect(args.onClose).toHaveBeenCalledOnce();+ expect(args.onClose).toHaveBeenCalledWith('Lifecycle notification 1');+ },+};++export const ProviderRemountIgnoresOldExits: Story = {+ args: { hasSlowMirrorExit: true },+ play: async ({ canvasElement, args }) => {+ const { canvas, body, user, first } = getLifecycle(canvasElement);+ await user.click(+ canvas.getByRole('button', { name: 'Add persistent notification' }),+ );+ const originalId = first.getByRole('status').id;+ await user.click(+ canvas.getByRole('button', { name: 'Close last notification' }),+ );+ await user.click(+ canvas.getByRole('button', { name: 'Unmount notification provider' }),+ );+ await user.click(+ canvas.getByRole('button', { name: 'Mount notification provider' }),+ );+ await user.click(+ canvas.getByRole('button', { name: 'Add persistent notification' }),+ );+ const replacement = within(+ body.getByRole('region', { name: 'First lifecycle notifications' }),+ ).getByRole('status');+ expect(replacement.id).not.toBe(originalId);+ await wait(1600);+ expect(replacement).toBeVisible();+ expect(args.onClose).toHaveBeenCalledOnce();+ await user.click(+ canvas.getByRole('button', { name: 'Close last notification' }),+ );+ expect(args.onClose).toHaveBeenCalledTimes(2);+ },+};++export const PortalDocumentation: Story = {+ render: () => <ToasterPortalExample isScoped />,+};++export const DefaultAndExplicitPortalTargets: Story = {+ render: () => <ToasterPortalExample />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const user = userEvent.setup();+ await user.click(canvas.getByRole('button', { name: 'Add notification' }));+ const region = body.getByRole('region', { name: 'Portal notifications' });+ const originalId = within(region).getByRole('status').id;+ expect(region.parentElement).toBe(canvasElement.ownerDocument.body);+ await user.click(+ canvas.getByRole('button', { name: 'Use explicit portal' }),+ );+ const destination = canvas.getByRole('region', {+ name: 'Explicit portal destination',+ });+ const explicitRegion = within(destination).getByRole('region', {+ name: 'Portal notifications',+ });+ expect(explicitRegion.parentElement).toBe(destination);+ expect(within(explicitRegion).getByRole('status').id).toBe(originalId);+ await user.click(canvas.getByRole('button', { name: 'Disable portal' }));+ expect(body.queryByRole('status')).not.toBeInTheDocument();+ await user.click(+ canvas.getByRole('button', { name: 'Update last notification' }),+ );+ await user.click(+ canvas.getByRole('button', { name: 'Use default portal' }),+ );+ const restoredRegion = body.getByRole('region', {+ name: 'Portal notifications',+ });+ expect(restoredRegion.parentElement).toBe(canvasElement.ownerDocument.body);+ expect(within(restoredRegion).getByRole('status').id).toBe(originalId);+ expect(within(restoredRegion).getByRole('status')).toHaveTextContent(+ 'Updated notification',+ );+ },+};++export const ScopedAndNullPortalTargets: Story = {+ render: () => <ToasterPortalExample isScoped />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const user = userEvent.setup();+ await user.click(canvas.getByRole('button', { name: 'Add notification' }));+ const region = body.getByRole('region', { name: 'Portal notifications' });+ const originalId = within(region).getByRole('status').id;+ expect(region.parentElement).toHaveClass('toast-lifecycle-portal-scope');+ expect(region.parentElement).toHaveClass('dark');+ expect(region).toHaveAttribute('dir', 'rtl');+ await user.click(canvas.getByRole('button', { name: 'Disable portal' }));+ expect(+ body.queryByRole('region', { name: 'Portal notifications' }),+ ).not.toBeInTheDocument();+ await user.click(+ canvas.getByRole('button', { name: 'Close last notification' }),+ );+ await user.click(+ canvas.getByRole('button', { name: 'Use default portal' }),+ );+ expect(body.queryByRole('status')).not.toBeInTheDocument();+ await user.click(canvas.getByRole('button', { name: 'Add notification' }));+ const restoredRegion = body.getByRole('region', {+ name: 'Portal notifications',+ });+ const replacement = within(restoredRegion).getByRole('status');+ expect(replacement.id).not.toBe(originalId);+ expect(restoredRegion.parentElement).toHaveClass(+ 'toast-lifecycle-portal-scope',+ );+ expect(restoredRegion).toHaveAttribute('dir', 'rtl');+ await user.click(+ canvas.getByRole('button', { name: 'Use explicit portal' }),+ );+ const destination = canvas.getByRole('region', {+ name: 'Explicit portal destination',+ });+ expect(+ within(destination).getByRole('region', { name: 'Portal notifications' }),+ ).toHaveAttribute('dir', 'rtl');+ expect(within(destination).getByRole('status').id).toBe(replacement.id);+ },+};++export const SuspensePreservesProviderNotificationsAndRemainingTime: Story = {+ args: { duration: 3000 },+ render: (args) => (+ <ToasterProviderSuspenseExample+ duration={args.duration}+ onClose={args.onClose}+ />+ ),+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const user = userEvent.setup();+ await user.click(+ canvas.getByRole('button', { name: 'Add timed notification' }),+ );+ const original = within(+ body.getByRole('region', { name: 'Suspense lifecycle notifications' }),+ ).getByRole('status');+ const originalId = original.id;+ await wait(1600);+ await user.click(+ canvas.getByRole('button', { name: 'Suspend notification provider' }),+ );+ await waitFor(() => {+ expect(+ canvas.getByRole('note', { name: 'Provider suspension state' }),+ ).toHaveTextContent('Notification provider suspended');+ expect(original).not.toBeVisible();+ });+ await wait(3500);+ expect(body.queryByRole('status')).not.toBeInTheDocument();+ expect(args.onClose).not.toHaveBeenCalled();+ await user.click(+ canvas.getByRole('button', { name: 'Reveal notification provider' }),+ );+ const restored = await body.findByRole('status');+ expect(restored.id).toBe(originalId);+ expect(restored).toHaveTextContent('Lifecycle notification 1');+ expect(+ canvas.getByRole('note', { name: 'Last lifecycle notification ID' }),+ ).toHaveTextContent(originalId);+ await wait(400);+ expect(restored).toBeVisible();+ expect(args.onClose).not.toHaveBeenCalled();+ await waitFor(() => expect(args.onClose).toHaveBeenCalledOnce(), {+ timeout: 1400,+ });+ await waitFor(() => expect(restored).not.toBeInTheDocument());+ expect(args.onClose).toHaveBeenCalledWith('Lifecycle notification 1');+ await user.click(+ canvas.getByRole('button', { name: 'Unmount notification provider' }),+ );+ await Promise.resolve();+ expect(body.queryByRole('status')).not.toBeInTheDocument();+ expect(args.onClose).toHaveBeenCalledOnce();+ },+};++export const StrictModePassiveEffectsCloseTheirOwnNotifications: Story = {+ parameters: { react: { rootOptions: { unstable_strictMode: true } } },+ render: (args) => (+ <ToasterProviderReplayExample>+ <ToasterProviderPassiveReplayEffect onClose={args.onClose} />+ </ToasterProviderReplayExample>+ ),+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const user = userEvent.setup();+ await waitFor(() => {+ expect(body.getAllByRole('status')).toHaveLength(1);+ expect(args.onClose).toHaveBeenCalledOnce();+ });+ const notification = body.getByRole('status');+ const notificationId = notification.id;+ expect(notification).toHaveTextContent('Passive effect notification');+ expect(args.onClose).not.toHaveBeenNthCalledWith(1, notificationId);+ await user.click(+ canvas.getByRole('button', { name: 'Unmount notification provider' }),+ );+ await Promise.resolve();+ expect(notification).not.toBeInTheDocument();+ expect(body.queryByRole('status')).not.toBeInTheDocument();+ expect(args.onClose).toHaveBeenCalledTimes(2);+ expect(args.onClose).toHaveBeenNthCalledWith(2, notificationId);+ },+};++export const StrictModeLayoutEffectsCloseTheirOwnNotifications: Story = {+ parameters: { react: { rootOptions: { unstable_strictMode: true } } },+ render: (args) => (+ <ToasterProviderReplayExample>+ <ToasterProviderLayoutReplayEffect onClose={args.onClose} />+ </ToasterProviderReplayExample>+ ),+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const user = userEvent.setup();+ await waitFor(() => {+ expect(body.getAllByRole('status')).toHaveLength(1);+ expect(args.onClose).toHaveBeenCalledOnce();+ });+ const notification = body.getByRole('status');+ const notificationId = notification.id;+ expect(notification).toHaveTextContent('Layout effect notification');+ expect(args.onClose).not.toHaveBeenNthCalledWith(1, notificationId);+ await user.click(+ canvas.getByRole('button', { name: 'Unmount notification provider' }),+ );+ await Promise.resolve();+ expect(notification).not.toBeInTheDocument();+ expect(body.queryByRole('status')).not.toBeInTheDocument();+ expect(args.onClose).toHaveBeenCalledTimes(2);+ expect(args.onClose).toHaveBeenNthCalledWith(2, notificationId);+ },+};diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleControls.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleControls.tsxnew file mode 100644index 00000000000..d9dadab617c--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleControls.tsx@@ -0,0 +1,109 @@+import { useState } from 'react';++import { useToast } from '@ui/components/feedback/Toast/hooks/useToast';+import { Button } from '@ui/primitives/input/Button/Button';+import { Text } from '@ui/primitives/typography/Text/Text';++import { type ToasterLifecycleExampleProps } from './ToasterLifecycleExampleProps';+import { ToasterLifecycleUnrelatedNotificationActions } from './ToasterLifecycleUnrelatedNotificationActions';++const DEFAULT_LIFECYCLE_DURATION = 1800;++type ToasterLifecycleControlsProps = Pick<+ ToasterLifecycleExampleProps,+ 'duration' | 'hasUnrelatedNotificationActions' | 'onClose'+> & {+ onDetachRenderers: () => void;+ onRememberProviderOperations?: (operations: () => void) => void;+};++export const ToasterLifecycleControls = ({+ duration = DEFAULT_LIFECYCLE_DURATION,+ hasUnrelatedNotificationActions = false,+ onClose,+ onDetachRenderers,+ onRememberProviderOperations,+}: ToasterLifecycleControlsProps) => {+ const { enqueueToast, updateToast, closeToast } = useToast();+ const [notificationNumber, setNotificationNumber] = useState(1);+ const [toastId, setToastId] = useState('');++ const addNotification = (notificationDuration: number) => {+ const notification = `Lifecycle notification ${notificationNumber}`;+ const id = enqueueToast({+ children: notification,+ duration: notificationDuration,+ onClose: () => onClose?.(notification),+ action: hasUnrelatedNotificationActions ? (+ <ToasterLifecycleUnrelatedNotificationActions onClose={onClose} />+ ) : (+ <Button size="sm">Notification action</Button>+ ),+ });++ onRememberProviderOperations?.(() => {+ closeToast(id);+ updateToast({ id, children: 'Previous provider notification updated' });+ enqueueToast({+ children: 'Previous provider notification enqueued',+ duration: 0,+ onClose: () => onClose?.('Previous provider notification'),+ });+ });+ setToastId(id);+ setNotificationNumber(notificationNumber + 1);+ };++ return (+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>+ <Button onClick={() => addNotification(0)}>+ Add persistent notification+ </Button>+ <Button onClick={() => addNotification(duration)}>+ Add timed notification+ </Button>+ <Button+ onClick={() =>+ updateToast({+ id: toastId,+ children: 'Updated lifecycle notification',+ })+ }+ >+ Update last notification+ </Button>+ <Button onClick={() => updateToast({ id: toastId, duration })}>+ Restart last countdown+ </Button>+ <Button onClick={() => closeToast(toastId)}>+ Close last notification+ </Button>+ <Button onClick={() => closeToast()}>Close all notifications</Button>+ <Button+ onClick={() => {+ closeToast(toastId);+ updateToast({+ id: toastId,+ children: 'Dismissed notification updated',+ });+ closeToast(toastId);+ updateToast({ id: toastId, duration });+ }}+ >+ Dismiss and update notification+ </Button>+ <Button+ onClick={() => {+ closeToast(toastId);+ onDetachRenderers();+ }}+ >+ Dismiss and detach renderers+ </Button>+ <Button>Outside notifications</Button>+ <Text role="note" aria-label="Last lifecycle notification ID">+ {toastId}+ </Text>+ </div>+ );+};diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleExample.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleExample.tsxnew file mode 100644index 00000000000..e5d85c8ada8--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleExample.tsx@@ -0,0 +1,121 @@+import { useState } from 'react';++import { ToastProvider } from '@ui/components/feedback/Toast/ToastProvider';+import { Button } from '@ui/primitives/input/Button/Button';+import { Text } from '@ui/primitives/typography/Text/Text';++import { Toaster } from '../Toaster';+import { ToastControls } from './ToastControls';+import { ToasterLifecycleControls } from './ToasterLifecycleControls';+import { type ToasterLifecycleExampleProps } from './ToasterLifecycleExampleProps';++export const ToasterLifecycleExample = ({+ duration,+ hasIndependentProvider = false,+ hasSlowMirrorExit = false,+ hasUnrelatedNotificationActions = false,+ onClose,+}: ToasterLifecycleExampleProps) => {+ const [limit, setLimit] = useState(3);+ const [isProviderMounted, setIsProviderMounted] = useState(true);+ const [isFirstRendererMounted, setIsFirstRendererMounted] = useState(true);+ const [isSecondRendererMounted, setIsSecondRendererMounted] = useState(true);+ const [previousProviderOperations, setPreviousProviderOperations] = useState<+ (() => void) | undefined+ >();++ const detachRenderers = () => {+ setIsFirstRendererMounted(false);+ setIsSecondRendererMounted(false);+ };++ return (+ <>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>+ <Button onClick={() => setLimit(1)}>Limit to one notification</Button>+ <Button onClick={() => setLimit(4)}>Limit to four notifications</Button>+ <Button+ onClick={() => setIsFirstRendererMounted(!isFirstRendererMounted)}+ >+ {isFirstRendererMounted+ ? 'Detach first renderer'+ : 'Mount first renderer'}+ </Button>+ <Button+ onClick={() => setIsSecondRendererMounted(!isSecondRendererMounted)}+ >+ {isSecondRendererMounted+ ? 'Detach second renderer'+ : 'Mount second renderer'}+ </Button>+ <Button onClick={detachRenderers}>Detach all renderers</Button>+ <Button+ onClick={() => {+ setIsFirstRendererMounted(true);+ setIsSecondRendererMounted(true);+ }}+ >+ Mount both renderers+ </Button>+ <Button onClick={() => setIsProviderMounted(!isProviderMounted)}>+ {isProviderMounted+ ? 'Unmount notification provider'+ : 'Mount notification provider'}+ </Button>+ <Button onClick={() => previousProviderOperations?.()}>+ Run previous provider operations+ </Button>+ <Text role="note" aria-label="Notification limit">+ {limit}+ </Text>+ </div>+ <section aria-label="Lifecycle source">+ {isProviderMounted && (+ <ToastProvider limit={limit}>+ <ToasterLifecycleControls+ duration={duration}+ hasUnrelatedNotificationActions={hasUnrelatedNotificationActions}+ onClose={onClose}+ onDetachRenderers={detachRenderers}+ onRememberProviderOperations={(operations) =>+ setPreviousProviderOperations(+ (previousOperations) => previousOperations ?? operations,+ )+ }+ />+ {isFirstRendererMounted && (+ <Toaster+ aria-label="First lifecycle notifications"+ style={{ bottom: 180 }}+ />+ )}+ {isSecondRendererMounted && (+ <Toaster+ aria-label="Second lifecycle notifications"+ data-lifecycle-second+ />+ )}+ </ToastProvider>+ )}+ </section>+ {hasSlowMirrorExit && (+ <style>+ {`[data-lifecycle-second] [data-exiting] { transition-duration: 1200ms !important; }`}+ </style>+ )}+ {hasIndependentProvider && (+ <section aria-label="Independent source">+ <ToastProvider>+ <ToastControls+ onClose={() => onClose?.('Independent notification')}+ />+ <Toaster+ aria-label="Independent notifications"+ style={{ right: 360 }}+ />+ </ToastProvider>+ </section>+ )}+ </>+ );+};diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleExampleProps.ts b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleExampleProps.tsnew file mode 100644index 00000000000..afcae43a085--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleExampleProps.ts@@ -0,0 +1,7 @@+export type ToasterLifecycleExampleProps = {+ duration?: number;+ hasIndependentProvider?: boolean;+ hasSlowMirrorExit?: boolean;+ hasUnrelatedNotificationActions?: boolean;+ onClose?: (notification: string) => void;+};diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleTimingOverrideExample.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleTimingOverrideExample.tsxnew file mode 100644index 00000000000..f0f77940345--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleTimingOverrideExample.tsx@@ -0,0 +1,102 @@+import { useState } from 'react';++import { ToastProvider } from '@ui/components/feedback/Toast/ToastProvider';+import { useToast } from '@ui/components/feedback/Toast/hooks/useToast';+import { type ToastProps } from '@ui/components/feedback/Toast/types/ToastProps';+import { Button } from '@ui/primitives/input/Button/Button';++import { Toaster } from '../Toaster';++const DEFAULT_TIMING_OVERRIDE_DURATION = 1800;++type ToasterLifecycleTimingOverrideExampleProps = {+ duration?: number;+ progress?: number;+ initialTimingOverrides: Pick<Partial<ToastProps>, 'duration' | 'progress'>;+ onClose?: (notification: string) => void;+};++type TimingOverrideControlsProps = Pick<+ ToasterLifecycleTimingOverrideExampleProps,+ 'progress' | 'onClose'+> & {+ duration: number;+ onUseDefaultDuration: () => void;+ onClearProgress: () => void;+};++const TimingOverrideControls = ({+ duration,+ progress,+ onClose,+ onUseDefaultDuration,+ onClearProgress,+}: TimingOverrideControlsProps) => {+ const { enqueueToast } = useToast();+ const [notificationNumber, setNotificationNumber] = useState(1);++ return (+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>+ <Button+ onClick={() => {+ const notification = `Override notification ${notificationNumber}`;+ enqueueToast({+ children: notification,+ duration,+ progress,+ onClose: () => onClose?.(notification),+ });+ setNotificationNumber(notificationNumber + 1);+ }}+ >+ Add override notification+ </Button>+ <Button onClick={onUseDefaultDuration}>+ Use default duration override+ </Button>+ <Button onClick={onClearProgress}>Clear progress override</Button>+ </div>+ );+};++export const ToasterLifecycleTimingOverrideExample = ({+ duration = DEFAULT_TIMING_OVERRIDE_DURATION,+ progress,+ initialTimingOverrides,+ onClose,+}: ToasterLifecycleTimingOverrideExampleProps) => {+ const [timingOverrides, setTimingOverrides] = useState(+ initialTimingOverrides,+ );++ return (+ <ToastProvider>+ <TimingOverrideControls+ duration={duration}+ progress={progress}+ onClose={onClose}+ onUseDefaultDuration={() =>+ setTimingOverrides((currentOverrides) => ({+ ...currentOverrides,+ duration: undefined,+ }))+ }+ onClearProgress={() =>+ setTimingOverrides((currentOverrides) => ({+ ...currentOverrides,+ progress: undefined,+ }))+ }+ />+ <Toaster+ aria-label="First lifecycle notifications"+ style={{ bottom: 180 }}+ getToastProps={() => timingOverrides}+ />+ <Toaster+ aria-label="Second lifecycle notifications"+ getToastProps={() => timingOverrides}+ />+ </ToastProvider>+ );+};diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleUnrelatedNotificationActions.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleUnrelatedNotificationActions.tsxnew file mode 100644index 00000000000..9e5180d0ae1--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterLifecycleUnrelatedNotificationActions.tsx@@ -0,0 +1,46 @@+import { useState } from 'react';++import { useToast } from '@ui/components/feedback/Toast/hooks/useToast';+import { Button } from '@ui/primitives/input/Button/Button';++type ToasterLifecycleUnrelatedNotificationActionsProps = {+ onClose?: (notification: string) => void;+};++export const ToasterLifecycleUnrelatedNotificationActions = ({+ onClose,+}: ToasterLifecycleUnrelatedNotificationActionsProps) => {+ const { enqueueToast, updateToast } = useToast();+ const [toastId, setToastId] = useState('');++ return (+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>+ <Button size="sm">Notification action</Button>+ <Button+ size="sm"+ onClick={() =>+ setToastId(+ enqueueToast({+ children: 'Unrelated notification',+ duration: 0,+ onClose: () => onClose?.('Unrelated notification'),+ }),+ )+ }+ >+ Add unrelated notification+ </Button>+ <Button+ size="sm"+ onClick={() =>+ updateToast({+ id: toastId,+ children: 'Updated unrelated notification',+ })+ }+ >+ Update unrelated notification+ </Button>+ </div>+ );+};diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterPortalExample.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterPortalExample.tsxnew file mode 100644index 00000000000..96076383d9d--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterPortalExample.tsx@@ -0,0 +1,67 @@+import { useState } from 'react';++import { ToastProvider } from '@ui/components/feedback/Toast/ToastProvider';+import { Button } from '@ui/primitives/input/Button/Button';+import { DirectionProvider } from '@ui/primitives/layout/DirectionProvider/DirectionProvider';+import { ThemeProvider } from '@ui/theme/ThemeProvider';++import { Toaster } from '../Toaster';+import { ToastControls } from './ToastControls';++type ToasterPortalExampleProps = {+ isScoped?: boolean;+};++export const ToasterPortalExample = ({+ isScoped = false,+}: ToasterPortalExampleProps) => {+ const [destination, setDestination] = useState<HTMLElement | null>(null);+ const [target, setTarget] = useState<'default' | 'explicit' | 'null'>(+ 'default',+ );+ const portalContainers = {+ default: undefined,+ explicit: destination,+ null: null,+ };+ const container = portalContainers[target];++ const example = (+ <div+ style={{+ backgroundColor: 'var(--t-background-primary)',+ color: 'var(--t-font-color-primary)',+ }}+ >+ <ToastProvider>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>+ <Button onClick={() => setTarget('default')}>+ Use default portal+ </Button>+ <Button onClick={() => setTarget('explicit')}>+ Use explicit portal+ </Button>+ <Button onClick={() => setTarget('null')}>Disable portal</Button>+ </div>+ <ToastControls />+ <section+ aria-label="Explicit portal destination"+ ref={setDestination}+ />+ <Toaster aria-label="Portal notifications" container={container} />+ </ToastProvider>+ </div>+ );++ return isScoped ? (+ <ThemeProvider+ colorScheme="dark"+ applyToRoot={false}+ className="toast-lifecycle-portal-scope"+ >+ <DirectionProvider direction="rtl">{example}</DirectionProvider>+ </ThemeProvider>+ ) : (+ example+ );+};diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderLayoutReplayEffect.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderLayoutReplayEffect.tsxnew file mode 100644index 00000000000..3d5155088ac--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderLayoutReplayEffect.tsx@@ -0,0 +1,28 @@+import { useLayoutEffect } from 'react';++import { useToast } from '@ui/components/feedback/Toast/hooks/useToast';++import { type ToasterLifecycleExampleProps } from './ToasterLifecycleExampleProps';++type ToasterProviderLayoutReplayEffectProps = Pick<+ ToasterLifecycleExampleProps,+ 'onClose'+>;++export const ToasterProviderLayoutReplayEffect = ({+ onClose,+}: ToasterProviderLayoutReplayEffectProps) => {+ const { enqueueToast, closeToast } = useToast();++ useLayoutEffect(() => {+ const id = enqueueToast({+ children: 'Layout effect notification',+ duration: 0,+ onClose: () => onClose?.(id),+ });++ return () => closeToast(id);+ }, [enqueueToast, closeToast, onClose]);++ return null;+};diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderPassiveReplayEffect.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderPassiveReplayEffect.tsxnew file mode 100644index 00000000000..e93b38221ec--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderPassiveReplayEffect.tsx@@ -0,0 +1,28 @@+import { useEffect } from 'react';++import { useToast } from '@ui/components/feedback/Toast/hooks/useToast';++import { type ToasterLifecycleExampleProps } from './ToasterLifecycleExampleProps';++type ToasterProviderPassiveReplayEffectProps = Pick<+ ToasterLifecycleExampleProps,+ 'onClose'+>;++export const ToasterProviderPassiveReplayEffect = ({+ onClose,+}: ToasterProviderPassiveReplayEffectProps) => {+ const { enqueueToast, closeToast } = useToast();++ useEffect(() => {+ const id = enqueueToast({+ children: 'Passive effect notification',+ duration: 0,+ onClose: () => onClose?.(id),+ });++ return () => closeToast(id);+ }, [enqueueToast, closeToast, onClose]);++ return null;+};diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderReplayExample.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderReplayExample.tsxnew file mode 100644index 00000000000..17224fb9b2f--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderReplayExample.tsx@@ -0,0 +1,32 @@+import { type ReactNode, StrictMode, useState } from 'react';++import { ToastProvider } from '@ui/components/feedback/Toast/ToastProvider';+import { Button } from '@ui/primitives/input/Button/Button';++import { Toaster } from '../Toaster';++type ToasterProviderReplayExampleProps = {+ children: ReactNode;+};++export const ToasterProviderReplayExample = ({+ children,+}: ToasterProviderReplayExampleProps) => {+ const [isProviderMounted, setIsProviderMounted] = useState(true);++ return (+ <>+ <Button onClick={() => setIsProviderMounted(false)}>+ Unmount notification provider+ </Button>+ {isProviderMounted && (+ <StrictMode>+ <ToastProvider>+ {children}+ <Toaster aria-label="Effect lifecycle notifications" />+ </ToastProvider>+ </StrictMode>+ )}+ </>+ );+};diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderSuspenseExample.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderSuspenseExample.tsxnew file mode 100644index 00000000000..488d4fcb596--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderSuspenseExample.tsx@@ -0,0 +1,68 @@+import { Suspense, useState } from 'react';++import { ToastProvider } from '@ui/components/feedback/Toast/ToastProvider';+import { Button } from '@ui/primitives/input/Button/Button';+import { Text } from '@ui/primitives/typography/Text/Text';++import { Toaster } from '../Toaster';+import { ToasterLifecycleControls } from './ToasterLifecycleControls';+import { type ToasterLifecycleExampleProps } from './ToasterLifecycleExampleProps';+import { ToasterProviderSuspension } from './ToasterProviderSuspension';++type ToasterProviderSuspenseExampleProps = Pick<+ ToasterLifecycleExampleProps,+ 'duration' | 'onClose'+>;++export const ToasterProviderSuspenseExample = ({+ duration,+ onClose,+}: ToasterProviderSuspenseExampleProps) => {+ const [isProviderMounted, setIsProviderMounted] = useState(true);+ const [pendingSuspension, setPendingSuspension] = useState<Promise<void>>();+ const [revealProvider, setRevealProvider] = useState<() => void>();++ const suspendProvider = () => {+ setPendingSuspension(+ new Promise<void>((resolve) => setRevealProvider(() => resolve)),+ );+ };++ return (+ <>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>+ <Button onClick={suspendProvider}>Suspend notification provider</Button>+ <Button+ onClick={() => {+ revealProvider?.();+ setPendingSuspension(undefined);+ }}+ >+ Reveal notification provider+ </Button>+ <Button onClick={() => setIsProviderMounted(false)}>+ Unmount notification provider+ </Button>+ </div>+ {isProviderMounted && (+ <Suspense+ fallback={+ <Text role="note" aria-label="Provider suspension state">+ Notification provider suspended+ </Text>+ }+ >+ <ToastProvider>+ <ToasterLifecycleControls+ duration={duration}+ onClose={onClose}+ onDetachRenderers={() => setIsProviderMounted(false)}+ />+ <Toaster aria-label="Suspense lifecycle notifications" />+ <ToasterProviderSuspension pendingSuspension={pendingSuspension} />+ </ToastProvider>+ </Suspense>+ )}+ </>+ );+};diff --git a/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderSuspension.tsx b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderSuspension.tsxnew file mode 100644index 00000000000..9a4b15d7b39--- /dev/null+++ b/packages/twenty-ui/src/components/feedback/Toaster/__stories__/ToasterProviderSuspension.tsx@@ -0,0 +1,15 @@+import { isDefined } from '@ui/utilities/utils/isDefined';++type ToasterProviderSuspensionProps = {+ pendingSuspension?: Promise<void>;+};++export const ToasterProviderSuspension = ({+ pendingSuspension,+}: ToasterProviderSuspensionProps) => {+ if (isDefined(pendingSuspension)) {+ throw pendingSuspension;+ }++ return null;+};diff --git a/packages/twenty-ui/src/components/feedback/Toaster/internal/ToasterItem.tsx b/packages/twenty-ui/src/components/feedback/Toaster/internal/ToasterItem.tsxindex a78982f0aac..deba83f0137 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 { useRef, useState } from 'react';import { Toast } from '@ui/components/feedback/Toast/Toast';+import { useToastContext } from '@ui/components/feedback/Toast/internal/hooks/useToastContext';import { ToastTimingContext } from '@ui/components/feedback/Toast/internal/contexts/ToastTimingContext';import { type ToastEntry } from '@ui/components/feedback/Toast/internal/types/ToastEntry';@@ -21,6 +22,9 @@ export const ToasterItem = ({}: ToasterItemProps) => {const { notification, status, durationRevision = 0 } = toastEntry;const { id, ...toastProps } = notification;+ const store = useToastContext();+ const customToastProps = getToastProps?.(notification);+ const [rendererKey] = useState(() => Symbol());const elementRef = useRef<HTMLDivElement>(null);return (@@ -33,18 +37,29 @@ export const ToasterItem = ({><div className={styles.itemContent}><ToastTimingContext.Provider- value={{ durationRevision, isActive: status === 'visible' }}+ value={{+ durationRevision,+ isActive: status === 'visible',+ lifecycle: store.lifecycle,+ id,+ rendererKey,+ timingOverrides: customToastProps,+ }}><Toast{...toastProps}- {...getToastProps?.(notification)}+ {...customToastProps}id={id}onClose={() => onClose(id)}/></ToastTimingContext.Provider></div></div>- <ToasterItemExitEffect elementRef={elementRef} toastEntry={toastEntry} />+ <ToasterItemExitEffect+ elementRef={elementRef}+ toastEntry={toastEntry}+ rendererKey={rendererKey}+ /></>);};diff --git a/packages/twenty-ui/src/components/feedback/Toaster/internal/ToasterItemExitEffect.tsx b/packages/twenty-ui/src/components/feedback/Toaster/internal/ToasterItemExitEffect.tsxindex fca2eee7a6b..1b7e171b357 100644--- a/packages/twenty-ui/src/components/feedback/Toaster/internal/ToasterItemExitEffect.tsx+++ b/packages/twenty-ui/src/components/feedback/Toaster/internal/ToasterItemExitEffect.tsx@@ -1,17 +1,19 @@+import { isNonEmptyArray } from '@sniptt/guards';import { type RefObject, useLayoutEffect } from 'react';import { useToastContext } from '@ui/components/feedback/Toast/internal/hooks/useToastContext';import { type ToastEntry } from '@ui/components/feedback/Toast/internal/types/ToastEntry';-import { completeToastExit } from '@ui/components/feedback/Toast/internal/utils/completeToastExit';type ToasterItemExitEffectProps = {elementRef: RefObject<HTMLDivElement | null>;toastEntry: ToastEntry;+ rendererKey: symbol;};export const ToasterItemExitEffect = ({elementRef,toastEntry,+ rendererKey,}: ToasterItemExitEffectProps) => {const store = useToastContext();@@ -20,10 +22,15 @@ export const ToasterItemExitEffect = ({return;}+ const finishExit = () =>+ store.lifecycle.finishExit({+ id: toastEntry.notification.id,+ key: rendererKey,+ });const exitAnimations = elementRef.current?.getAnimations?.() ?? [];- if (exitAnimations.length === 0) {- completeToastExit({ store, toast: toastEntry });+ if (!isNonEmptyArray(exitAnimations)) {+ finishExit();return;}@@ -32,14 +39,14 @@ export const ToasterItemExitEffect = ({exitAnimations.map((animation) => animation.finished),).then(() => {if (!isCancelled) {- completeToastExit({ store, toast: toastEntry });+ finishExit();}});return () => {isCancelled = true;};- }, [elementRef, toastEntry, store]);+ }, [elementRef, toastEntry, store, rendererKey]);- return <></>;+ return null;};diff --git a/packages/twenty-ui/src/primitives/input/Select/__stories__/Select.interactions.stories.tsx b/packages/twenty-ui/src/primitives/input/Select/__stories__/Select.interactions.stories.tsxindex 4807e823bbb..6cffce06ca1 100644--- a/packages/twenty-ui/src/primitives/input/Select/__stories__/Select.interactions.stories.tsx+++ b/packages/twenty-ui/src/primitives/input/Select/__stories__/Select.interactions.stories.tsx@@ -56,7 +56,7 @@ export const Keyboard: Story = {await expect(trigger).toHaveTextContent('Cherry');await expect(args.onValueChange).toHaveBeenCalledTimes(1);await expect(args.onOpenChange).toHaveBeenCalledTimes(2);- await expect(trigger).toHaveFocus();+ await waitFor(() => expect(trigger).toHaveFocus());await userEvent.keyboard(' ');await waitForSelectPopup(canvasElement);await expect(args.onOpenChange).toHaveBeenCalledTimes(3);