feat(island): toast close button, own motion and clock, one at a time
Toast follows the updated Lumina design system. - ✕ «بستن اعلان» on every toast shown by showToast: 44px, its hit area reaching into the padding; the label comes from the Toaster's new `closeLabel`. - Motion: in over 200ms (rise 16px, fade in), out over 160ms (drop 8px, fade out); reduced motion keeps a plain 120ms fade. The entrance plays once, even when the region moves into a dialog. - Text wraps evenly; with an action, text past two lines moves the action under it, measured again when the width changes. - Toast runs its own clock (sonner gets duration Infinity): it pauses while a pointer is on the region (hover, press, hold, swipe), while keyboard focus is inside it, and while the tab is hidden. - One toast at a time: a new one replaces the old; while keyboard focus is in the region it waits until focus leaves. Every toast gets a fresh id, so `showToast` drops its `id` option. - The Toaster slot overrides sonner's slide and stack with inline style instead of !important, and `toastOptions` is no longer a prop. - market: AppShell passes `closeLabel`; showActionError no longer passes an id. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9ea17684ad
commit
f4e9febad7
|
|
@ -1,12 +1,21 @@
|
||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||||
|
import type { AnimationEvent } from 'react';
|
||||||
|
|
||||||
import { FlexBox } from '../../atoms/flex-box';
|
import { FlexBox } from '../../atoms/flex-box';
|
||||||
|
import { GridBox } from '../../atoms/grid-box';
|
||||||
import { Icon } from '../../atoms/icon';
|
import { Icon } from '../../atoms/icon';
|
||||||
import { Typography } from '../../atoms/typography';
|
import { Typography } from '../../atoms/typography';
|
||||||
import { Element } from '../../primitives/element';
|
import { Element } from '../../primitives/element';
|
||||||
import { cn } from '../../tools/cn';
|
import { cn } from '../../tools/cn';
|
||||||
import { TOAST_ICONS } from './constants';
|
import { TOAST_ICONS } from './constants';
|
||||||
import type { ToastProps } from './types';
|
import { useCloseLabel } from './hooks/use-close-label';
|
||||||
|
import { useCloseTimer } from './hooks/use-close-timer';
|
||||||
|
import type { ToastLayout, ToastProps } from './types';
|
||||||
import {
|
import {
|
||||||
toastActionVariants,
|
toastActionVariants,
|
||||||
|
toastCloseVariants,
|
||||||
toastIconVariants,
|
toastIconVariants,
|
||||||
toastVariants,
|
toastVariants,
|
||||||
} from './variants';
|
} from './variants';
|
||||||
|
|
@ -19,23 +28,86 @@ export function Toast({
|
||||||
announce = true,
|
announce = true,
|
||||||
children,
|
children,
|
||||||
description,
|
description,
|
||||||
|
onClose,
|
||||||
|
duration,
|
||||||
|
closeLabel,
|
||||||
className,
|
className,
|
||||||
}: ToastProps) {
|
}: ToastProps) {
|
||||||
const role = tone === 'error' ? 'alert' : 'status';
|
const role = tone === 'error' ? 'alert' : 'status';
|
||||||
|
const hasAction = action !== undefined;
|
||||||
|
const resolvedCloseLabel = useCloseLabel(closeLabel);
|
||||||
|
const rootRef = useRef<HTMLDivElement>(null);
|
||||||
|
const messageRef = useRef<HTMLElement>(null);
|
||||||
|
// Text that runs past two lines next to an action moves the action under it.
|
||||||
|
const [layout, setLayout] = useState<ToastLayout>(
|
||||||
|
hasAction ? 'measuring' : 'row',
|
||||||
|
);
|
||||||
|
// The entrance plays once: moving the region into a dialog re-inserts it, which would replay it.
|
||||||
|
const [hasEntered, setEntered] = useState(false);
|
||||||
|
useCloseTimer(duration, onClose);
|
||||||
|
|
||||||
|
// Measured in the row layout, before paint, so the layout never jumps.
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const message = messageRef.current;
|
||||||
|
const text = message?.parentElement;
|
||||||
|
if (layout !== 'measuring' || !message || !text) return;
|
||||||
|
const style = getComputedStyle(message);
|
||||||
|
const lineHeight =
|
||||||
|
Number.parseFloat(style.lineHeight) ||
|
||||||
|
Number.parseFloat(style.fontSize) * 1.5;
|
||||||
|
setLayout(text.offsetHeight > lineHeight * 2.5 ? 'stacked' : 'row');
|
||||||
|
}, [layout]);
|
||||||
|
|
||||||
|
// A new width (rotation, a resized window) measures again.
|
||||||
|
useEffect(() => {
|
||||||
|
const root = rootRef.current;
|
||||||
|
if (!hasAction || !root) return undefined;
|
||||||
|
let width = root.offsetWidth;
|
||||||
|
const observer = new ResizeObserver(() => {
|
||||||
|
if (root.offsetWidth === width) return;
|
||||||
|
width = root.offsetWidth;
|
||||||
|
setLayout('measuring');
|
||||||
|
});
|
||||||
|
observer.observe(root);
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [hasAction]);
|
||||||
|
|
||||||
|
const handleAnimationEnd = (event: AnimationEvent<HTMLDivElement>) => {
|
||||||
|
if (event.target === event.currentTarget) setEntered(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const isStacked = layout === 'stacked';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<FlexBox
|
<GridBox
|
||||||
|
ref={rootRef}
|
||||||
|
data-toast=""
|
||||||
role={announce ? role : undefined}
|
role={announce ? role : undefined}
|
||||||
alignItems="items-center"
|
alignItems={isStacked ? 'items-start' : 'items-center'}
|
||||||
gap="gap-3"
|
onAnimationEnd={handleAnimationEnd}
|
||||||
className={cn(toastVariants(), className)}
|
className={cn(toastVariants({ entering: !hasEntered }), className)}
|
||||||
>
|
>
|
||||||
{icon && <Icon name={icon} className={toastIconVariants({ tone })} />}
|
{icon && <Icon name={icon} className={toastIconVariants({ tone })} />}
|
||||||
<FlexBox direction="flex-col" gap="gap-1" className="min-w-0 flex-1">
|
<FlexBox
|
||||||
<Typography tag="span" color="inverse">
|
direction="flex-col"
|
||||||
|
gap="gap-1"
|
||||||
|
className="col-start-2 row-start-1 min-w-0"
|
||||||
|
>
|
||||||
|
<Typography
|
||||||
|
ref={messageRef}
|
||||||
|
tag="span"
|
||||||
|
color="inverse"
|
||||||
|
className="text-pretty"
|
||||||
|
>
|
||||||
{children}
|
{children}
|
||||||
</Typography>
|
</Typography>
|
||||||
{description != null && (
|
{description != null && (
|
||||||
<Typography tag="span" variant="body-sm" color="inverse">
|
<Typography
|
||||||
|
tag="span"
|
||||||
|
variant="body-sm"
|
||||||
|
color="inverse"
|
||||||
|
className="text-pretty"
|
||||||
|
>
|
||||||
{description}
|
{description}
|
||||||
</Typography>
|
</Typography>
|
||||||
)}
|
)}
|
||||||
|
|
@ -45,13 +117,26 @@ export function Toast({
|
||||||
tag="button"
|
tag="button"
|
||||||
type="button"
|
type="button"
|
||||||
onClick={action.onClick}
|
onClick={action.onClick}
|
||||||
className={toastActionVariants()}
|
className={toastActionVariants({ stacked: isStacked })}
|
||||||
>
|
>
|
||||||
<Typography tag="span" color="inherit" className="font-semibold">
|
<Typography tag="span" color="inherit" className="font-semibold">
|
||||||
{action.label}
|
{action.label}
|
||||||
</Typography>
|
</Typography>
|
||||||
</Element>
|
</Element>
|
||||||
)}
|
)}
|
||||||
</FlexBox>
|
{onClose && resolvedCloseLabel && (
|
||||||
|
<GridBox
|
||||||
|
tag="button"
|
||||||
|
type="button"
|
||||||
|
justifyItems="justify-items-center"
|
||||||
|
alignItems="items-center"
|
||||||
|
aria-label={resolvedCloseLabel}
|
||||||
|
onClick={onClose}
|
||||||
|
className={toastCloseVariants()}
|
||||||
|
>
|
||||||
|
<Icon name="close" size={18} />
|
||||||
|
</GridBox>
|
||||||
|
)}
|
||||||
|
</GridBox>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,8 @@ import { createPortal } from 'react-dom';
|
||||||
import { Toaster as SonnerToaster } from 'sonner';
|
import { Toaster as SonnerToaster } from 'sonner';
|
||||||
|
|
||||||
import { DIALOG_CLOSE_EVENT, DIALOG_OPEN_EVENT } from '../../atoms/dialog';
|
import { DIALOG_CLOSE_EVENT, DIALOG_OPEN_EVENT } from '../../atoms/dialog';
|
||||||
|
import { CloseLabelContext } from './hooks/use-close-label';
|
||||||
|
import { syncKeyboardFocus, trackToastRegion } from './region-store';
|
||||||
import type { ToasterProps } from './types';
|
import type { ToasterProps } from './types';
|
||||||
|
|
||||||
const noSubscription = () => () => {};
|
const noSubscription = () => () => {};
|
||||||
|
|
@ -16,6 +18,25 @@ const TOASTER_STYLE = {
|
||||||
'--width': 'min(26.25rem, calc(100vw - 2rem))',
|
'--width': 'min(26.25rem, calc(100vw - 2rem))',
|
||||||
} as CSSProperties;
|
} as CSSProperties;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Each toast's slot. Toast animates itself (in 200ms, out 160ms), so the slot drops sonner's own
|
||||||
|
* slide, fade and collapsed stack; one toast shows at a time. Inline style beats sonner's
|
||||||
|
* stylesheet without `!important`, and a swipe still moves the slot.
|
||||||
|
*/
|
||||||
|
const TOAST_SLOT_STYLE = {
|
||||||
|
'--y': 'translateY(0)',
|
||||||
|
opacity: 1,
|
||||||
|
height: 'auto',
|
||||||
|
} as CSSProperties;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When sonner starts removing a toast (✕, its clock, its action, a newer toast or a swipe) it sets
|
||||||
|
* `data-removed` on the slot and unmounts it 200ms later (sonner 2.0.8), so the toast inside plays
|
||||||
|
* its 160ms exit. The toast sits two wrappers down, so the selector looks for `[data-toast]`.
|
||||||
|
*/
|
||||||
|
const TOAST_SLOT_CLASS =
|
||||||
|
'data-[removed=true]:pointer-events-none data-[removed=true]:[&_[data-toast]]:animate-toast-out';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The one toast region, rendered once by the app shell. Bottom centre, 24px from the bottom
|
* The one toast region, rendered once by the app shell. Bottom centre, 24px from the bottom
|
||||||
* (sonner would use 16px on phones), never at the top. Bull shows the bottom nav up to 1024px, so
|
* (sonner would use 16px on phones), never at the top. Bull shows the bottom nav up to 1024px, so
|
||||||
|
|
@ -26,9 +47,10 @@ const TOASTER_STYLE = {
|
||||||
* the rest of the page inert. So the region lives in a box of its own that moves into the topmost
|
* the rest of the page inert. So the region lives in a box of its own that moves into the topmost
|
||||||
* open dialog and back to `<body>` when it closes: a toast shows over an open sheet and its action
|
* open dialog and back to `<body>` when it closes: a toast shows over an open sheet and its action
|
||||||
* can be tapped there. The box is moved, never re-created, so toasts on screen survive the move.
|
* can be tapped there. The box is moved, never re-created, so toasts on screen survive the move.
|
||||||
* The lightbox doesn't host toasts, so it stays above them.
|
* The lightbox doesn't host toasts, so it stays above them. The box also reports the pointer and
|
||||||
|
* keyboard focus on the region, which pause the toasts' clocks.
|
||||||
*/
|
*/
|
||||||
export function Toaster({ label, style, ...props }: ToasterProps) {
|
export function Toaster({ label, closeLabel, style, ...props }: ToasterProps) {
|
||||||
// The box exists only in the browser; the region renders after hydration, as sonner does anyway.
|
// The box exists only in the browser; the region renders after hydration, as sonner does anyway.
|
||||||
const [box] = useState(() =>
|
const [box] = useState(() =>
|
||||||
typeof document === 'undefined' ? null : document.createElement('div'),
|
typeof document === 'undefined' ? null : document.createElement('div'),
|
||||||
|
|
@ -44,7 +66,11 @@ export function Toaster({ label, style, ...props }: ToasterProps) {
|
||||||
document.body.append(box);
|
document.body.append(box);
|
||||||
// Open dialogs that host toasts, oldest first; the region sits in the last one.
|
// Open dialogs that host toasts, oldest first; the region sits in the last one.
|
||||||
const stack: HTMLDialogElement[] = [];
|
const stack: HTMLDialogElement[] = [];
|
||||||
const place = () => (stack.at(-1) ?? document.body).append(box);
|
const place = () => {
|
||||||
|
(stack.at(-1) ?? document.body).append(box);
|
||||||
|
// Moving the box drops the focus inside it without a focusout.
|
||||||
|
syncKeyboardFocus();
|
||||||
|
};
|
||||||
const onOpen = (event: Event) => {
|
const onOpen = (event: Event) => {
|
||||||
const dialog = (event as CustomEvent<HTMLDialogElement>).detail;
|
const dialog = (event as CustomEvent<HTMLDialogElement>).detail;
|
||||||
stack.push(dialog);
|
stack.push(dialog);
|
||||||
|
|
@ -58,9 +84,11 @@ export function Toaster({ label, style, ...props }: ToasterProps) {
|
||||||
};
|
};
|
||||||
document.addEventListener(DIALOG_OPEN_EVENT, onOpen);
|
document.addEventListener(DIALOG_OPEN_EVENT, onOpen);
|
||||||
document.addEventListener(DIALOG_CLOSE_EVENT, onClose);
|
document.addEventListener(DIALOG_CLOSE_EVENT, onClose);
|
||||||
|
const untrack = trackToastRegion(box);
|
||||||
return () => {
|
return () => {
|
||||||
document.removeEventListener(DIALOG_OPEN_EVENT, onOpen);
|
document.removeEventListener(DIALOG_OPEN_EVENT, onOpen);
|
||||||
document.removeEventListener(DIALOG_CLOSE_EVENT, onClose);
|
document.removeEventListener(DIALOG_CLOSE_EVENT, onClose);
|
||||||
|
untrack();
|
||||||
box.remove();
|
box.remove();
|
||||||
};
|
};
|
||||||
}, [box]);
|
}, [box]);
|
||||||
|
|
@ -69,16 +97,22 @@ export function Toaster({ label, style, ...props }: ToasterProps) {
|
||||||
isHydrated &&
|
isHydrated &&
|
||||||
box &&
|
box &&
|
||||||
createPortal(
|
createPortal(
|
||||||
<SonnerToaster
|
<CloseLabelContext value={closeLabel}>
|
||||||
position="bottom-center"
|
<SonnerToaster
|
||||||
offset={24}
|
position="bottom-center"
|
||||||
mobileOffset={24}
|
offset={24}
|
||||||
gap={8}
|
mobileOffset={24}
|
||||||
containerAriaLabel={label}
|
gap={8}
|
||||||
toastOptions={{ unstyled: true }}
|
containerAriaLabel={label}
|
||||||
style={{ ...TOASTER_STYLE, ...style }}
|
toastOptions={{
|
||||||
{...props}
|
unstyled: true,
|
||||||
/>,
|
style: TOAST_SLOT_STYLE,
|
||||||
|
className: TOAST_SLOT_CLASS,
|
||||||
|
}}
|
||||||
|
style={{ ...TOASTER_STYLE, ...style }}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</CloseLabelContext>,
|
||||||
box,
|
box,
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -8,10 +8,9 @@ export const TOAST_ICONS: Record<ToastTone, IconName> = {
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Every toast closes by itself (0019); sonner pauses the clock while it is hovered or focused, or
|
* Every toast closes by itself (0019); its clock pauses while it is hovered or focused, or the tab
|
||||||
* the tab is hidden. About 4
|
* is hidden (`useCloseTimer`). About 4 seconds to read one line, 6 when there is an action to
|
||||||
* seconds to read one line, 6 when there is an action to reach. An error says what failed, why
|
* reach. An error says what failed, why and what to do, so it stays 8 seconds, 10 with its action.
|
||||||
* and what to do, so it stays 8 seconds, 10 with its action.
|
|
||||||
*/
|
*/
|
||||||
export const TOAST_DURATION_MS = 4000;
|
export const TOAST_DURATION_MS = 4000;
|
||||||
export const TOAST_WITH_ACTION_DURATION_MS = 6000;
|
export const TOAST_WITH_ACTION_DURATION_MS = 6000;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
'use client';
|
||||||
|
|
||||||
|
import { createContext, use } from 'react';
|
||||||
|
|
||||||
|
/** The accessible name of every toast's ✕, from the `Toaster` that shows it. */
|
||||||
|
export const CloseLabelContext = createContext<string | undefined>(undefined);
|
||||||
|
|
||||||
|
/** The toast's own `closeLabel`, else its `Toaster`'s. */
|
||||||
|
export function useCloseLabel(closeLabel?: string): string | undefined {
|
||||||
|
const regionCloseLabel = use(CloseLabelContext);
|
||||||
|
return closeLabel ?? regionCloseLabel;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,57 @@
|
||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useEffectEvent, useRef, useSyncExternalStore } from 'react';
|
||||||
|
import { useStore } from 'zustand';
|
||||||
|
|
||||||
|
import {
|
||||||
|
isRegionHeld,
|
||||||
|
syncKeyboardFocus,
|
||||||
|
toastRegionStore,
|
||||||
|
} from '../region-store';
|
||||||
|
|
||||||
|
const subscribeToVisibility = (onChange: () => void) => {
|
||||||
|
document.addEventListener('visibilitychange', onChange);
|
||||||
|
return () => document.removeEventListener('visibilitychange', onChange);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calls `onClose` after `duration` ms. The clock pauses while a pointer is on the toast region
|
||||||
|
* (hover, press, hold, swipe) or keyboard focus is inside it, and while the tab is hidden, so
|
||||||
|
* nobody loses a message they are reading or about to tap (0019, WCAG 2.2.1). It never runs
|
||||||
|
* without `onClose` or a finite, positive `duration`; outside a `Toaster` only the hidden tab
|
||||||
|
* pauses it.
|
||||||
|
*/
|
||||||
|
export function useCloseTimer(duration?: number, onClose?: () => void): void {
|
||||||
|
const isHeld = useStore(toastRegionStore, isRegionHeld);
|
||||||
|
const isHidden = useSyncExternalStore(
|
||||||
|
subscribeToVisibility,
|
||||||
|
() => document.hidden,
|
||||||
|
() => false,
|
||||||
|
);
|
||||||
|
const clock = useRef({ duration, remaining: duration ?? 0 });
|
||||||
|
const close = useEffectEvent(() => onClose?.());
|
||||||
|
const canRun =
|
||||||
|
onClose !== undefined &&
|
||||||
|
duration !== undefined &&
|
||||||
|
Number.isFinite(duration) &&
|
||||||
|
duration > 0;
|
||||||
|
const isRunning = canRun && !isHeld && !isHidden;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// A new duration starts a new clock.
|
||||||
|
if (clock.current.duration !== duration) {
|
||||||
|
clock.current = { duration, remaining: duration ?? 0 };
|
||||||
|
}
|
||||||
|
if (!isRunning) return undefined;
|
||||||
|
// Monotonic, so a system clock change can't shorten or stretch the wait.
|
||||||
|
const startedAt = performance.now();
|
||||||
|
const timer = setTimeout(() => close(), clock.current.remaining);
|
||||||
|
return () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
clock.current.remaining -= performance.now() - startedAt;
|
||||||
|
};
|
||||||
|
}, [duration, isRunning]);
|
||||||
|
|
||||||
|
// A focused toast that goes away fires no focusout.
|
||||||
|
useEffect(() => syncKeyboardFocus, []);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,73 @@
|
||||||
|
import { createStore } from 'zustand/vanilla';
|
||||||
|
|
||||||
|
export type ToastRegionState = {
|
||||||
|
/** A pointer is over the region: hovering, or pressing, holding or swiping a toast. */
|
||||||
|
isPointerInside: boolean;
|
||||||
|
/** Keyboard focus is inside the region: Tab, or sonner's Alt+T on the list. */
|
||||||
|
hasKeyboardFocus: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const REGION_ATTRIBUTE = 'data-toast-region';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether someone is on the toast region. Toasts pause their clock while they are, and
|
||||||
|
* `showToast` holds a new toast back while keyboard focus is inside, so focus and the message
|
||||||
|
* aren't lost. It lives outside React because `showToast` is a plain function.
|
||||||
|
*/
|
||||||
|
export const toastRegionStore = createStore<ToastRegionState>()(() => ({
|
||||||
|
isPointerInside: false,
|
||||||
|
hasKeyboardFocus: false,
|
||||||
|
}));
|
||||||
|
|
||||||
|
/** Someone is on the region: a toast there waits before it closes. */
|
||||||
|
export const isRegionHeld = (state: ToastRegionState): boolean =>
|
||||||
|
state.isPointerInside || state.hasKeyboardFocus;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removing or moving a focused element fires no focusout, so a toast that goes away, and the
|
||||||
|
* region when it moves, read again where focus is.
|
||||||
|
*/
|
||||||
|
export function syncKeyboardFocus(): void {
|
||||||
|
const active = document.activeElement;
|
||||||
|
toastRegionStore.setState({
|
||||||
|
hasKeyboardFocus: Boolean(
|
||||||
|
active?.closest(`[${REGION_ATTRIBUTE}]`) &&
|
||||||
|
active.matches(':focus-visible'),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reports the pointer and keyboard focus inside the region's box. Sonner's list and each toast
|
||||||
|
* slot are focusable, so focus on them counts too. Focus from a click doesn't: a pointer on the
|
||||||
|
* toast already pauses it, and a toast clicked once mustn't stay until the next click elsewhere.
|
||||||
|
* Returns the cleanup.
|
||||||
|
*/
|
||||||
|
export function trackToastRegion(box: HTMLElement): () => void {
|
||||||
|
const setRegion = toastRegionStore.setState;
|
||||||
|
const onPointerEnter = () => setRegion({ isPointerInside: true });
|
||||||
|
const onPointerLeave = () => setRegion({ isPointerInside: false });
|
||||||
|
const onFocusIn = (event: FocusEvent) => {
|
||||||
|
const target = event.target as Element;
|
||||||
|
setRegion({ hasKeyboardFocus: target.matches(':focus-visible') });
|
||||||
|
};
|
||||||
|
const onFocusOut = (event: FocusEvent) => {
|
||||||
|
// The next focusin inside the region sets it again.
|
||||||
|
if (!box.contains(event.relatedTarget as Node | null)) {
|
||||||
|
setRegion({ hasKeyboardFocus: false });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
box.setAttribute(REGION_ATTRIBUTE, '');
|
||||||
|
box.addEventListener('pointerenter', onPointerEnter);
|
||||||
|
box.addEventListener('pointerleave', onPointerLeave);
|
||||||
|
box.addEventListener('focusin', onFocusIn);
|
||||||
|
box.addEventListener('focusout', onFocusOut);
|
||||||
|
return () => {
|
||||||
|
box.removeEventListener('pointerenter', onPointerEnter);
|
||||||
|
box.removeEventListener('pointerleave', onPointerLeave);
|
||||||
|
box.removeEventListener('focusin', onFocusIn);
|
||||||
|
box.removeEventListener('focusout', onFocusOut);
|
||||||
|
setRegion({ isPointerInside: false, hasKeyboardFocus: false });
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -6,9 +6,19 @@ import {
|
||||||
TOAST_ERROR_WITH_ACTION_DURATION_MS,
|
TOAST_ERROR_WITH_ACTION_DURATION_MS,
|
||||||
TOAST_WITH_ACTION_DURATION_MS,
|
TOAST_WITH_ACTION_DURATION_MS,
|
||||||
} from './constants';
|
} from './constants';
|
||||||
|
import { toastRegionStore } from './region-store';
|
||||||
import { Toast } from './Toast';
|
import { Toast } from './Toast';
|
||||||
import type { ShowToastOptions } from './types';
|
import type { ShowToastOptions } from './types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every toast gets a new id. Reusing one while sonner is still removing that toast would merge the
|
||||||
|
* new toast into the leaving one, and sonner would remove both.
|
||||||
|
*/
|
||||||
|
let shownCount = 0;
|
||||||
|
|
||||||
|
/** The newest toast shown while keyboard focus was in the region; it shows when focus leaves. */
|
||||||
|
let heldBack: { id: number; show: () => void } | null = null;
|
||||||
|
|
||||||
/** How long a toast stays when the caller doesn't say: longer for an error, longer with an action. */
|
/** How long a toast stays when the caller doesn't say: longer for an error, longer with an action. */
|
||||||
function defaultDuration(
|
function defaultDuration(
|
||||||
tone: ShowToastOptions['tone'],
|
tone: ShowToastOptions['tone'],
|
||||||
|
|
@ -22,44 +32,74 @@ function defaultDuration(
|
||||||
return hasAction ? TOAST_WITH_ACTION_DURATION_MS : TOAST_DURATION_MS;
|
return hasAction ? TOAST_WITH_ACTION_DURATION_MS : TOAST_DURATION_MS;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function showHeldBackWhenFocusLeaves(): void {
|
||||||
|
const unsubscribe = toastRegionStore.subscribe((state) => {
|
||||||
|
if (state.hasKeyboardFocus) return;
|
||||||
|
unsubscribe();
|
||||||
|
const next = heldBack;
|
||||||
|
heldBack = null;
|
||||||
|
next?.show();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Shows a toast after an action completes or fails; never for a read. Every toast closes by
|
* Shows a toast after an action completes or fails; never for a read. One toast at a time: a new
|
||||||
* itself (0019). Tapping the action also closes the toast. Returns the toast's id for
|
* one replaces the one on screen. While keyboard focus is in the region it waits until focus
|
||||||
* `dismissToast`.
|
* leaves, so the person keeps their place and the message they are on. Every toast closes by
|
||||||
|
* itself (0019), from ✕, or when its action is tapped. Returns the toast's id for `dismissToast`.
|
||||||
*/
|
*/
|
||||||
export function showToast({
|
export function showToast({
|
||||||
id,
|
|
||||||
message,
|
message,
|
||||||
action,
|
action,
|
||||||
duration,
|
duration,
|
||||||
...props
|
...props
|
||||||
}: ShowToastOptions): string | number {
|
}: ShowToastOptions): number {
|
||||||
return toast.custom(
|
shownCount += 1;
|
||||||
(toastId) => (
|
const id = shownCount;
|
||||||
<Toast
|
const closesAfter =
|
||||||
{...props}
|
duration !== undefined && Number.isFinite(duration) && duration > 0
|
||||||
// The region already reads toasts politely; only an error keeps its own alert.
|
? duration
|
||||||
announce={props.tone === 'error'}
|
: defaultDuration(props.tone, Boolean(action));
|
||||||
action={
|
|
||||||
action && {
|
const show = () => {
|
||||||
label: action.label,
|
toast.dismiss();
|
||||||
onClick: () => {
|
toast.custom(
|
||||||
toast.dismiss(toastId);
|
() => (
|
||||||
action.onClick();
|
<Toast
|
||||||
},
|
{...props}
|
||||||
|
// The region already reads toasts politely; only an error keeps its own alert.
|
||||||
|
announce={props.tone === 'error'}
|
||||||
|
duration={closesAfter}
|
||||||
|
onClose={() => toast.dismiss(id)}
|
||||||
|
action={
|
||||||
|
action && {
|
||||||
|
label: action.label,
|
||||||
|
onClick: () => {
|
||||||
|
toast.dismiss(id);
|
||||||
|
action.onClick();
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
>
|
||||||
>
|
{message}
|
||||||
{message}
|
</Toast>
|
||||||
</Toast>
|
),
|
||||||
),
|
// Toast runs its own clock, which also pauses on keyboard focus; sonner only places it.
|
||||||
{
|
{ id, duration: Infinity },
|
||||||
id,
|
);
|
||||||
duration: duration ?? defaultDuration(props.tone, Boolean(action)),
|
};
|
||||||
},
|
|
||||||
);
|
if (toastRegionStore.getState().hasKeyboardFocus) {
|
||||||
|
if (heldBack === null) showHeldBackWhenFocusLeaves();
|
||||||
|
heldBack = { id, show };
|
||||||
|
} else {
|
||||||
|
show();
|
||||||
|
}
|
||||||
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function dismissToast(id?: string | number): void {
|
/** Closes one toast, or every toast without an id, including one waiting to show. */
|
||||||
|
export function dismissToast(id?: number): void {
|
||||||
|
if (id === undefined || heldBack?.id === id) heldBack = null;
|
||||||
toast.dismiss(id);
|
toast.dismiss(id);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,9 @@ import type { IconName } from '../../atoms/icon';
|
||||||
|
|
||||||
export type ToastTone = 'info' | 'success' | 'error';
|
export type ToastTone = 'info' | 'success' | 'error';
|
||||||
|
|
||||||
|
/** `measuring` renders the row layout once to see whether the text runs past two lines. */
|
||||||
|
export type ToastLayout = 'measuring' | 'row' | 'stacked';
|
||||||
|
|
||||||
export type ToastAction = {
|
export type ToastAction = {
|
||||||
/** Such as «تلاش مجدد» on a recoverable failure. */
|
/** Such as «تلاش مجدد» on a recoverable failure. */
|
||||||
label: ReactNode;
|
label: ReactNode;
|
||||||
|
|
@ -15,7 +18,7 @@ export type ToastProps = {
|
||||||
tone?: ToastTone;
|
tone?: ToastTone;
|
||||||
/** `null` hides the tone's icon. */
|
/** `null` hides the tone's icon. */
|
||||||
icon?: IconName | null;
|
icon?: IconName | null;
|
||||||
/** At most one action. */
|
/** At most one action. It moves under the text when the text runs past two lines. */
|
||||||
action?: ToastAction;
|
action?: ToastAction;
|
||||||
/**
|
/**
|
||||||
* Its own `role="status"` (`alert` for errors). `showToast` keeps it only for errors: the toast
|
* Its own `role="status"` (`alert` for errors). `showToast` keeps it only for errors: the toast
|
||||||
|
|
@ -26,21 +29,37 @@ export type ToastProps = {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
/** A second line under it: a failed action's reason and what to do, or the reference code. */
|
/** A second line under it: a failed action's reason and what to do, or the reference code. */
|
||||||
description?: ReactNode;
|
description?: ReactNode;
|
||||||
|
/** Called from ✕, or when `duration` runs out. ✕ shows only with it and a close label. */
|
||||||
|
onClose?: () => void;
|
||||||
|
/**
|
||||||
|
* Milliseconds before `onClose` runs, paused while someone is on the toast region or the tab is
|
||||||
|
* hidden. Without it or `onClose` the toast stays, for previews and tests.
|
||||||
|
*/
|
||||||
|
duration?: number;
|
||||||
|
/** The accessible name of ✕; defaults to the `Toaster`'s `closeLabel`. */
|
||||||
|
closeLabel?: string;
|
||||||
className?: string;
|
className?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ShowToastOptions = Omit<
|
export type ShowToastOptions = Omit<
|
||||||
ToastProps,
|
ToastProps,
|
||||||
'announce' | 'children' | 'className'
|
'announce' | 'children' | 'className' | 'onClose' | 'closeLabel' | 'duration'
|
||||||
> & {
|
> & {
|
||||||
message: ReactNode;
|
message: ReactNode;
|
||||||
/** A toast shown again under the same id replaces the old one instead of stacking. */
|
/**
|
||||||
id?: string;
|
* Defaults to 4 seconds (6 with an action); an error to 8 (10 with an action). Anything but a
|
||||||
/** Defaults to 4 seconds (6 with an action); an error to 8 (10 with an action). */
|
* finite, positive number gets the default, so every toast closes (0019).
|
||||||
|
*/
|
||||||
duration?: number;
|
duration?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ToasterProps = Omit<SonnerToasterProps, 'containerAriaLabel'> & {
|
/** `toastOptions` stays island's: it sets the slot that lets `Toast` animate itself. */
|
||||||
|
export type ToasterProps = Omit<
|
||||||
|
SonnerToasterProps,
|
||||||
|
'containerAriaLabel' | 'toastOptions'
|
||||||
|
> & {
|
||||||
/** The toast region's accessible name, from the translations: «اعلانها». */
|
/** The toast region's accessible name, from the translations: «اعلانها». */
|
||||||
label: string;
|
label: string;
|
||||||
|
/** The accessible name of every toast's ✕, from the translations: «بستن اعلان». */
|
||||||
|
closeLabel: string;
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,21 @@
|
||||||
import { cva } from 'class-variance-authority';
|
import { cva } from 'class-variance-authority';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Icon · text · action · ✕ on fixed grid lines. Spacing is margins, not a column gap, so a toast
|
||||||
|
* without an icon or an action keeps no empty gap.
|
||||||
|
*/
|
||||||
export const toastVariants = cva(
|
export const toastVariants = cva(
|
||||||
'min-h-12 w-full rounded-md bg-surface-inverse px-4 py-3 shadow-2',
|
'min-h-12 w-full grid-cols-[auto_minmax(0,1fr)_auto_auto] rounded-md bg-surface-inverse px-4 py-3 shadow-2',
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
entering: { true: 'animate-toast-in', false: '' },
|
||||||
|
},
|
||||||
|
defaultVariants: { entering: false },
|
||||||
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
/** Icons and the action use the opposite theme's tints, so they read on the inverse ground. */
|
/** Icons and the action use the opposite theme's tints, so they read on the inverse ground. */
|
||||||
export const toastIconVariants = cva('', {
|
export const toastIconVariants = cva('col-start-1 row-start-1 me-3', {
|
||||||
variants: {
|
variants: {
|
||||||
tone: {
|
tone: {
|
||||||
info: 'text-inverse-info',
|
info: 'text-inverse-info',
|
||||||
|
|
@ -17,5 +27,23 @@ export const toastIconVariants = cva('', {
|
||||||
});
|
});
|
||||||
|
|
||||||
export const toastActionVariants = cva(
|
export const toastActionVariants = cva(
|
||||||
'min-h-touch-target flex-none cursor-pointer rounded-full px-3 text-inverse-info focus-visible:focus-ring-inverse',
|
'min-h-touch-target cursor-pointer rounded-full px-3 text-inverse-info focus-visible:focus-ring-inverse',
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
/** Under the text, at the end, when the text runs past two lines; ✕ stays on the first. */
|
||||||
|
stacked: {
|
||||||
|
false: 'col-start-3 row-start-1 ms-3',
|
||||||
|
true: 'col-span-3 col-start-2 row-start-2 mt-1 -me-3 -mb-2 justify-self-end',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: { stacked: false },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A 44px ✕ whose hit area reaches 12px into the padding and the gap, so it takes only 32px from
|
||||||
|
* the message.
|
||||||
|
*/
|
||||||
|
export const toastCloseVariants = cva(
|
||||||
|
'col-start-4 row-start-1 -my-2.5 -me-3 size-touch-target rounded-full text-text-inverse/72 transition-colors duration-120 ease-standard focus-visible:text-text-inverse focus-visible:focus-ring-inverse actionable:cursor-pointer actionable:hover:bg-text-inverse/8 actionable:hover:text-text-inverse',
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -34,5 +34,12 @@
|
||||||
animation-duration: 2.4s !important;
|
animation-duration: 2.4s !important;
|
||||||
animation-iteration-count: infinite !important;
|
animation-iteration-count: infinite !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* A toast keeps a plain 120ms fade without the slide, so it never pops in or out. */
|
||||||
|
[data-toast] {
|
||||||
|
animation-duration: 120ms !important;
|
||||||
|
animation-timing-function: linear !important;
|
||||||
|
translate: none !important;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -92,7 +92,23 @@
|
||||||
/* The OTP caret, and the one shake of a wrong code. */
|
/* The OTP caret, and the one shake of a wrong code. */
|
||||||
--animate-blink: blink 1.1s steps(1) infinite;
|
--animate-blink: blink 1.1s steps(1) infinite;
|
||||||
--animate-shake: shake 320ms ease-out 1;
|
--animate-shake: shake 320ms ease-out 1;
|
||||||
|
/* A toast rises 16px as it fades in, and drops 8px as it fades out; sonner removes it 200ms
|
||||||
|
after it starts leaving, so the exit stays shorter than that. */
|
||||||
|
--animate-toast-in: toast-in 200ms var(--ease-standard) both;
|
||||||
|
--animate-toast-out: toast-out 160ms cubic-bezier(0.4, 0, 1, 1) forwards;
|
||||||
|
|
||||||
|
@keyframes toast-in {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
translate: 0 16px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes toast-out {
|
||||||
|
to {
|
||||||
|
opacity: 0;
|
||||||
|
translate: 0 8px;
|
||||||
|
}
|
||||||
|
}
|
||||||
@keyframes shimmer {
|
@keyframes shimmer {
|
||||||
from {
|
from {
|
||||||
background-position: -50% 0;
|
background-position: -50% 0;
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,11 @@ export function AppShell({ queryClient, i18n, children }: AppShellProps) {
|
||||||
<I18nextProvider i18n={i18n}>
|
<I18nextProvider i18n={i18n}>
|
||||||
<NetworkBoundary />
|
<NetworkBoundary />
|
||||||
{children}
|
{children}
|
||||||
<Toaster label={i18n.t('toaster')} dir={i18n.dir()} />
|
<Toaster
|
||||||
|
label={i18n.t('toaster')}
|
||||||
|
closeLabel={i18n.t('toast-close')}
|
||||||
|
dir={i18n.dir()}
|
||||||
|
/>
|
||||||
</I18nextProvider>
|
</I18nextProvider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@
|
||||||
"description": "پیشبینیهای ساختاریافته و ثبتشدهی تحلیلگران مالی ایرانی، با کارنامهای که پیش از اشتراک میبینید."
|
"description": "پیشبینیهای ساختاریافته و ثبتشدهی تحلیلگران مالی ایرانی، با کارنامهای که پیش از اشتراک میبینید."
|
||||||
},
|
},
|
||||||
"toaster": "اعلانها",
|
"toaster": "اعلانها",
|
||||||
|
"toast-close": "بستن اعلان",
|
||||||
"network": {
|
"network": {
|
||||||
"offline": "اینترنت قطع است",
|
"offline": "اینترنت قطع است",
|
||||||
"offline-description": "آخرین اطلاعات ذخیرهشده را میبینید.",
|
"offline-description": "آخرین اطلاعات ذخیرهشده را میبینید.",
|
||||||
|
|
|
||||||
|
|
@ -17,8 +17,8 @@ export type ShowActionErrorOptions = {
|
||||||
/**
|
/**
|
||||||
* The one error toast for a failed action. It handles the error once, says what failed, adds the
|
* The one error toast for a failed action. It handles the error once, says what failed, adds the
|
||||||
* server's message and hint (or a support sentence with the reference code), and offers the button
|
* server's message and hint (or a support sentence with the reference code), and offers the button
|
||||||
* the error's retry kind allows. It closes after 8 seconds (10 with its button) unless hovered
|
* the error's retry kind allows. It closes after 8 seconds (10 with its button), paused while
|
||||||
* (0019); a repeated failure replaces it.
|
* hovered or focused (0019); a repeated failure replaces it, as every new toast does.
|
||||||
*/
|
*/
|
||||||
export function showActionError(
|
export function showActionError(
|
||||||
error: unknown,
|
error: unknown,
|
||||||
|
|
@ -38,7 +38,6 @@ export function showActionError(
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
showToast({
|
showToast({
|
||||||
id: `action-error:${failedMessage}`,
|
|
||||||
tone: 'error',
|
tone: 'error',
|
||||||
message: failedMessage,
|
message: failedMessage,
|
||||||
description:
|
description:
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue