Toast stack
Agent notifications that stack and fan out on hover. Free and MIT licensed, as HTML, a typed React component or an Astro component, in three styles with light and dark mode.
Need this designed into your product? Book a call
Install
Add it to your project with the CLI.
HTML, CSS and JS
npx designme add toast-stackReact
npx designme add toast-stack --reactAstro
npx designme add toast-stack --astroshadcn, React
npx shadcn@latest add https://designme.dev/r/shadcn/toast-stack.json shadcn, Astro
npx shadcn@latest add https://designme.dev/r/shadcn/astro/toast-stack.json The CLI copies the source into your project, so you own it and can change anything. Where each version lands, what it needs and the shadcn theme bridge: Installation.
About
What it is for and what it does.
Toast stack collects the news an agent sends while it works and piles it into a small deck, newest in front. Each toast in it is a Toast card, so a job keeps its live glyph, its steps and its buttons, and a problem can become its fix in the same card. Hover the deck, or Tab into it, and it fans out into a list so a person can read each card, act on it and close the ones they are done with.
- When an agent sends several things in a row, like a job in progress, tests failing and frames syncing, and each should stay readable.
- When some of that news needs an answer, like a fix to run or a deck to open, without leaving the page.
- When a job runs in the background and its progress should stay in one card while other news arrives in front of it.
- When you want a quiet corner of the app that shows the last few events at a glance and tidies itself up.
- Pass
toastsoldest first. Each is Toast'sToastData: astatus, atitle, adescription, and optionally aglyph,steps, one or twoactions,onStopand aduration. The last one sits in front. - Keep a toast's
idand change it, and its card changes in place: its words crossfade (a counter ticks over at once), its status mark crossfades, its footer opens and closes, and the card eases to its new height. The demo turns "2 tests failed" into "Fixing 2 tests…" and then "42 tests passed" this way. - Collapsed, the two cards behind the front one take its height and peek out 8px above it, a step narrower each, with their words hidden. Fanned out, the four in front show at their own heights, 8px apart. The stack is as tall as what it shows, and the cards and the stack ease together, so nothing jumps when a card comes, goes or changes height.
- It fans out under a mouse, while the keyboard's focus is in it, and on a tap on touch screens (a tap anywhere else folds it). Set
expandedto fan it yourself. - Each card has Close with a countdown ring when it has a
duration, and Stop in its place while it isworkingwith anonStop. Every countdown holds while the stack is fanned out, and while the pointer or the focus is on its card. - Swipe a card sideways to dismiss it, or press Escape while the focus is in it.
onDismisstells you how it was closed:close,timeout,swipeorescape. A new card rises in at the front, and a closed one fades 8px down as the others close the gap. maxcaps how many toasts stay mounted (6 by default). Older ones drop off the back.- Each card looks as Toast does in each style: square in Blueprint, plush in Soft, and in Studio with its footer on an off-white strip, the ink primary, and the accent white in dark mode.
- The stack is a region named "Notifications" with two live regions: a card's
announce(or its title) is read each time it changes, politely, and anerroris read at once (assertive). - Close, Stop and the steps' chevron are real buttons with labels ("Close", "Stop the job", "Show the steps" or "Hide the steps"), and the chevron sets
aria-expanded. Glyphs and status marks are hidden from screen readers; the words carry the news. - Cards that can't be seen (behind the front one in the deck, or past the fourth when fanned out) and a card on its way out are
inert, so Tab only reaches cards on show. - Escape closes the card the focus is in and moves the focus to the next card's Close.
- The countdowns pause while the stack is open for reading, so there is time to reach a card's buttons.
- With reduced motion turned on, cards change place and size at once, with no rise, blur or swipe-off glide.
Usage
Import it in React and drive it from your own state, or place it in an Astro page.
React
import { ToastStack } from '@/components/designme/toast-stack/ToastStack';React example
The demo above as a React component, 104 lines you can copy.
'use client';
// The animated preview from designme.dev, rebuilt from the React component: an example of driving it from your own state.
import { useRef, useState } from 'react';
import { ToastStack } from './ToastStack';
import { DeckGlyph, type ToastData, type ToastStep } from '../toast/Toast';
import { Icon } from '../lib/icons';
import { useStory, useWait } from '../lib/useScript';
/* ---------- Toast stack: an agent's news as it comes. A job starts with its glyph at work, a success and a problem arrive; the
story opens the stack, fixes the problem (the same card becomes its fix, then the result), drops the success and lets the
stack fold back. Send notification sends more. An agent at work, so it keeps playing under the pointer ---------- */
const SEC = ['Cover', 'Agenda', 'Revenue', 'North', 'South', 'Plan vs actual', 'By region', 'Hiring', 'Open roles', 'Risks', 'Data move', 'Next steps'];
const POOL: Omit<ToastData, 'id' | 'actions'>[] = [
{ status: 'success', title: 'Frames synced', description: '6 frames from Pricing.fig', duration: 9000 },
{ status: 'info', title: 'PR #412 is ready', description: 'Use shared spacing tokens · 3 files', duration: 10000 },
{ status: 'warning', title: 'Budget at 80%', description: '1,600 of 2,000 credits', duration: 12000 },
{ status: 'success', title: 'Draft written', description: 'Launch email · 2 subject lines', duration: 9000 }
];
const TESTS = ['Cart total rounds down', 'Tax shows on the receipt', '40 other tests'];
export default function ToastStackDemo() {
const ref = useRef<HTMLDivElement>(null);
const [toasts, setToasts] = useState<ToastData[]>([]);
const [expanded, setExpanded] = useState<boolean | undefined>(undefined);
const wait = useWait(), live = useRef(new Map<string, number>()), all = useRef<ToastData[]>([]);
// one card per id: a known id changes in place, a new one comes in at the front; six at most
const put = (t: ToastData) => { const l = all.current; all.current = (l.some(x => x.id === t.id) ? l.map(x => x.id === t.id ? t : x) : [...l, t]).slice(-6); setToasts(all.current); };
const drop = (id: ToastData['id']) => { all.current = all.current.filter(x => x.id !== id); setToasts(all.current); };
const run = (id: string) => { const n = (live.current.get(id) ?? 0) + 1; live.current.set(id, n); return () => live.current.get(id) === n && all.current.some(t => t.id === id); };
/* a job the agent runs in the background: it reads the notes, outlines and drafts twelve slides; Stop pauses it */
const job = (from = 0, made = 0) => {
const id = 'job', ok = run(id);
const L = ['Read the notes', 'Outline 12 slides', 'Draft the slides'];
const steps = (at: number, s: ToastStep['status'], n: number): ToastStep[] => L.map((label, i) => ({ label, status: i < at ? 'done' : i === at ? s : 'waiting', detail: i === 2 && at >= 2 ? `${Math.min(n + (s === 'running' ? 1 : 0), 12)} of 12` : undefined }));
let n = made;
const stop = (at: number) => () => { run(id); put({ id, status: 'stopped', title: at === 2 ? `Stopped at slide ${n}` : 'Stopped before drafting', description: `${n} of 12 drafted · nothing lost`,
glyph: <DeckGlyph phase={at ? 'outlining' : 'idle'} made={n} />, steps: steps(at, 'paused', n), announce: `Stopped. ${n} of 12 drafted. Resume or discard.`,
actions: [{ label: 'Discard', onClick: () => drop(id) }, { label: 'Resume', variant: 'primary', onClick: () => job(at, n) }] }); };
const say = 'Making slides from your notes';
const done = () => put({ id, status: 'success', title: '12 slides ready', description: 'Q3 planning deck', glyph: <DeckGlyph phase="done" made={12} />, steps: steps(3, 'done', 12), duration: 12000,
announce: '12 slides ready. Open the deck or undo it.', actions: [
{ label: 'Undo', onClick: () => put({ id, status: 'success', title: 'Deck removed', description: 'Your notes are unchanged', glyph: <DeckGlyph phase="gone" />, steps: steps(3, 'done', 12), duration: 6000, actions: [{ label: 'Redo', onClick: done }] }) },
{ label: 'Open', variant: 'primary', onClick: () => drop(id) }] });
(async () => {
if (from === 0) { put({ id, status: 'working', title: 'Reading your notes…', description: '3 sections · 212 words', glyph: <DeckGlyph phase="reading" />, steps: steps(0, 'running', 0), onStop: stop(0), announce: say }); await wait(1600); if (!ok()) return; }
if (from <= 1) { put({ id, status: 'working', title: 'Outlining the deck…', description: '12 slides planned', glyph: <DeckGlyph phase="outlining" />, steps: steps(1, 'running', 0), onStop: stop(1), announce: say }); await wait(1200); if (!ok()) return; }
for (; n < 12; n++) {
put({ id, status: 'working', title: 'Drafting slides…', description: `Slide ${n + 1} of 12 · ${SEC[n]}`, glyph: <DeckGlyph phase="drafting" made={n} active={n} />, steps: steps(2, 'running', n), onStop: stop(2), announce: n >= 6 ? 'Half the slides are drafted' : say });
await wait(380); if (!ok()) return;
}
done();
})();
};
/* a problem the agent can fix: the card becomes its fix, then the result, in place */
const tests = () => {
const id = 'tests';
const fail = () => put({ id, status: 'error', title: '2 tests failed', description: 'checkout.spec · the total is 1¢ off', announce: '2 tests failed in checkout.spec. Fix them or ignore them.',
steps: TESTS.map((label, i) => ({ label, status: i < 2 ? 'failed' : 'done' })), actions: [{ label: 'Ignore', onClick: () => drop(id) }, { label: 'Fix', variant: 'primary', onClick: fix }] });
const fix = async () => {
const ok = run(id), stop = () => { run(id); fail(); };
put({ id, status: 'working', title: 'Fixing 2 tests…', description: 'Rounding in cart.ts', steps: TESTS.map((label, i) => ({ label, status: i < 2 ? 'running' : 'done' })), onStop: stop, announce: 'Fixing 2 tests' });
await wait(1700); if (!ok()) return;
for (let i = 6; i <= 42; i += 6) { put({ id, status: 'working', title: 'Running checkout.spec…', description: `Passed ${i} of 42`, steps: TESTS.map(label => ({ label, status: 'done' })), onStop: stop, announce: 'Fixing 2 tests' }); await wait(200); if (!ok()) return; }
put({ id, status: 'success', title: '42 tests passed', description: 'Fixed in cart.ts · 1 line', steps: TESTS.map(label => ({ label, status: 'done' })), duration: 10000,
announce: '42 tests passed. Fixed in cart.ts.', actions: [{ label: 'View diff', onClick: () => drop(id) }] });
};
fail();
};
/* plain news, and what Send notification sends: one action at most, and a countdown */
const sent = useRef(0);
const news = (k = sent.current++) => {
const id = 'n' + k, d = POOL[k % POOL.length];
const act = d.title === 'PR #412 is ready' ? [{ label: 'Review', variant: 'primary' as const, onClick: () => drop(id) }]
: d.title === 'Budget at 80%' ? [{ label: 'Raise cap', variant: 'warn' as const, onClick: () => put({ id, status: 'success', title: 'Cap raised to 3,000', description: '1,600 of 3,000 credits', duration: 6000 }) }] : undefined;
put({ ...d, id, actions: act });
return id;
};
useStory(ref, async s => {
const until = async (f: () => boolean) => { while (!f()) await s.wait(100); };
s.taken(() => setExpanded(undefined));
await s.wait(500); job();
await s.wait(1500); const frames = news(); sent.current = 1;
await s.wait(1500); tests();
await s.wait(1500); setExpanded(true);
await s.wait(1500); s.press('.dm-tst-fi .dm-primary');
await until(() => all.current.some(t => t.id === 'tests' && t.status === 'success'));
await s.wait(1000); drop(frames);
await s.wait(1500); setExpanded(undefined);
}, { hold: false });
return (
<div ref={ref} style={{ width: '100%', minHeight: 260, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 32 }}>
<div style={{ marginBlock: 'auto', width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<ToastStack toasts={toasts} expanded={expanded} onDismiss={id => drop(id)} />
</div>
<div data-dm=""><button type="button" className="dm-pill dm-line dm-sm" onClick={() => news()}><Icon name="bell" />Send notification</button></div>
</div>
);
}
Astro
In a page in src/pages. It plays the demo above; change its toast-stack.js to show your own data. Attributes like class go on its root element.
---
import ToastStack from '../components/designme/toast-stack/ToastStack.astro';
---
<ToastStack />
<ToastStack data-style="soft" class="my-class" />Props
Everything ToastStack takes.
| Prop | Type | What it does |
|---|---|---|
toastsrequired | ToastData[] | The toasts, oldest first: the last one sits in front. Each is a Toast (`ToastData`): keep its `id` and change it, and its card changes in place (a job's progress, a problem becoming its fix); a new `id` comes in at the front |
onDismiss | (id: ToastData['id'], reason: ToastDismissReason) => void | Called when a toast is closed: by Close, its countdown, a swipe or Escape. It leaves the stack either way; drop it from `toasts` too |
expanded | boolean | Fans the stack out (true) or keeps it a deck (false). Leave it out and it fans out under the pointer, while the keyboard's focus is in it, and on a tap |
max | number | How many toasts stay mounted. Older ones drop off the back. Default 6 |
className | string |
Code
The full source, as the CLI installs it.
ToastStack.tsxReact · 139 lines
'use client';
import { useEffect, useRef, useState, type CSSProperties } from 'react';
import { cx } from '../lib/cx';
import { useIsoLayoutEffect } from '../lib/hooks';
import { ToastCard, type ToastData, type ToastDismissReason } from '../toast/Toast';
import '../designme.css';
import './toast-stack.css';
export interface ToastStackProps {
/** The toasts, oldest first: the last one sits in front. Each is a Toast (`ToastData`): keep its `id` and change it, and its
card changes in place (a job's progress, a problem becoming its fix); a new `id` comes in at the front */
toasts: ToastData[];
/** Called when a toast is closed: by Close, its countdown, a swipe or Escape. It leaves the stack either way; drop it from
`toasts` too */
onDismiss?: (id: ToastData['id'], reason: ToastDismissReason) => void;
/** Fans the stack out (true) or keeps it a deck (false). Leave it out and it fans out under the pointer, while the keyboard's
focus is in it, and on a tap */
expanded?: boolean;
/** How many toasts stay mounted. Older ones drop off the back. Default 6 */
max?: number;
className?: string;
}
// collapsed, the two cards behind the front one peek out 8px each; fanned out, the four in front show, 8px apart
const PEEK = 8, GAP = 8, FAN = 4;
/** Where each card sits, counting from the front: collapsed into a deck (the cards behind take the front one's height and
peek out above it, a step narrower each), or fanned out into a list, each at its own height */
function place(i: number, fan: boolean, hs: number[]): { style: CSSProperties; height?: number; back: boolean; hidden: boolean } {
if (fan) {
let y = 0;
for (let k = 0; k < i; k++) y += hs[k] + GAP;
return { style: { transform: `translateY(${-y}px)`, opacity: i < FAN ? 1 : 0, zIndex: 100 - i }, back: false, hidden: i >= FAN };
}
const j = Math.min(i, 2);
return { style: { transform: j ? `translateY(${-j * PEEK}px) scale(${1 - j * .05})` : 'translateY(0px)', opacity: i > 2 ? 0 : 1, zIndex: 100 - i }, height: i ? hs[0] : undefined, back: i > 0, hidden: i > 0 };
}
/** Toasts that stack into a deck and fan out under the pointer or the focus. Each one is a Toast card, with its steps, its
footer, Close with its countdown, swipe and Escape; the stack reads each card's own height and moves them together */
export function ToastStack({ toasts, onDismiss, expanded, max = 6, className }: ToastStackProps) {
// a closed toast goes at once, whether or not the parent drops it
const [closed, setClosed] = useState<Set<ToastData['id']>>(() => new Set());
const live = toasts.filter(t => !closed.has(t.id)).slice(-max), front = live.slice().reverse();
const ids = live.map(t => t.id).join('\u0000');
// it fans out under a mouse, while the keyboard's focus is in it, and on a tap (touch has no hover)
const [hover, setHover] = useState(false), [focused, setFocused] = useState(false), [tapped, setTapped] = useState(false);
const fan = expanded ?? (hover || focused || tapped);
const root = useRef<HTMLDivElement>(null);
useEffect(() => {
const out = (e: PointerEvent) => { if (e.pointerType !== 'mouse' && !root.current?.contains(e.target as Node)) setTapped(false); };
document.addEventListener('pointerdown', out); return () => document.removeEventListener('pointerdown', out);
}, []);
// each card's own height, as it reports it
const [heights, setHeights] = useState<Record<string, number>>({});
const hs = front.map(t => heights[t.id] ?? 0);
// a new card waits two frames below its place, so its rise to it eases; the cards it covers step back as it comes
const [placed, setPlaced] = useState<Set<ToastData['id']>>(() => new Set());
useEffect(() => {
const fresh = live.filter(t => !placed.has(t.id)).map(t => t.id); if (!fresh.length) return;
let raf = requestAnimationFrame(() => { raf = requestAnimationFrame(() => setPlaced(p => new Set([...p, ...fresh]))); });
return () => cancelAnimationFrame(raf);
}, [ids]); // eslint-disable-line react-hooks/exhaustive-deps
// a card that goes keeps its place in the DOM for a moment, fading 8px down as the others close the gap (a swiped one has
// already gone on sideways)
type Leaving = { toast: ToastData; at: number; style: CSSProperties; height?: number };
const [prev, setPrev] = useState({ ids, live, fan, hs });
const [leaving, setLeaving] = useState<Leaving[]>([]);
if (prev.ids !== ids) {
const now = new Set(live.map(t => t.id)), n = prev.live.length;
const gone = prev.live.flatMap((t, at): Leaving[] => {
if (now.has(t.id) || leaving.some(l => l.toast.id === t.id)) return [];
const was = place(n - 1 - at, prev.fan, prev.hs);
return [{ toast: t, at, height: was.height, style: { ...was.style, transform: `${was.style.transform} translateY(8px) scale(.98)`, opacity: 0 } }];
});
setPrev({ ids, live, fan, hs });
if (gone.length) setLeaving(l => [...l, ...gone]);
} else if (prev.fan !== fan || prev.hs.join() !== hs.join()) setPrev({ ids, live, fan, hs });
const leavingIds = leaving.map(l => l.toast.id).join('\u0000');
useEffect(() => {
if (!leaving.length) return;
const t = setTimeout(() => setLeaving(l => l.filter(x => !leaving.includes(x))), 520);
return () => clearTimeout(t);
}, [leavingIds]); // eslint-disable-line react-hooks/exhaustive-deps
/* what screen readers hear, through the stack's two live regions: a card's `announce` (or its title) each time it changes;
an error at once, the rest politely */
const said = useRef(new Map<ToastData['id'], string>());
const [say, setSay] = useState<{ text: string; loud: boolean }>({ text: '', loud: false });
const news = live.map(t => [t.id, t.announce ?? t.title, t.status === 'error'] as const).filter(([id, text]) => said.current.get(id) !== text);
const newsKey = news.map(([id, text]) => id + ':' + text).join('\u0000');
useEffect(() => {
if (!news.length) return;
news.forEach(([id, text]) => said.current.set(id, text));
const [, text, loud] = news[news.length - 1];
setSay({ text: '', loud: false });
const t = setTimeout(() => setSay({ text, loud }), 60);
return () => clearTimeout(t);
}, [newsKey]); // eslint-disable-line react-hooks/exhaustive-deps
const close = (id: ToastData['id'], r: ToastDismissReason) => {
const had = !!root.current?.contains(document.activeElement);
setClosed(c => new Set(c).add(id)); onDismiss?.(id, r);
// the focus goes on to the next card's Close (or Stop)
if (had) setTimeout(() => { const b = root.current?.querySelectorAll<HTMLElement>('.dm-tst-t:not([inert]) :is(.dm-tst-x,.dm-tst-stop)'); b?.[b.length - 1]?.focus({ preventScroll: true }); }, 0);
};
// closed ids the parent has since dropped are forgotten
useEffect(() => { setClosed(c => { const has = new Set(toasts.map(t => t.id)); const next = new Set([...c].filter(id => has.has(id))); return next.size === c.size ? c : next; }); }, [toasts]);
// the stack is as tall as what it shows, so it stays centred where it is placed as it grows and shrinks
const fanh = hs.slice(0, FAN).reduce((a, h) => a + h + GAP, 0) - (live.length ? GAP : 0);
const deckh = live.length ? hs[0] + Math.min(live.length - 1, 2) * PEEK : 0;
useIsoLayoutEffect(() => { root.current?.style.setProperty('--dm-tsk-h', (fan ? fanh : deckh) + 'px'); });
const card = (t: ToastData, i: number) => {
const p = place(i, fan, hs), fresh = !placed.has(t.id);
return <ToastCard key={t.id} toast={t} motion="host" paused={fan} onClose={r => close(t.id, r)} inert={p.hidden}
className={cx(fresh && 'dm-tsk-new', p.back && 'dm-tsk-back')} style={fresh ? { zIndex: p.style.zIndex } : p.style} height={p.height}
onHeight={h => setHeights(x => x[t.id] === h ? x : { ...x, [t.id]: h })} />;
};
const gone = (l: Leaving) => <ToastCard key={l.toast.id} toast={l.toast} motion="host" leaving onClose={() => {}} className="dm-tsk-out" style={l.style} height={l.height} />;
return (
<div data-dm="" ref={root} className={cx('dm-tsk-stack', className)} role="region" aria-label="Notifications"
onPointerEnter={e => { if (e.pointerType === 'mouse') setHover(true); }} onPointerLeave={e => { if (e.pointerType === 'mouse') setHover(false); }}
onPointerDown={e => { if (e.pointerType !== 'mouse' && !(e.target as Element).closest('button')) setTapped(true); }}
onFocus={e => { if (e.target.matches(':focus-visible')) setFocused(true); }} onBlur={e => { if (!e.currentTarget.contains(e.relatedTarget as Node)) setFocused(false); }}>
{leaving.slice().sort((a, b) => a.at - b.at).reduce((all, l) => { all.splice(Math.min(l.at, all.length), 0, gone(l)); return all; },
live.map(t => card(t, front.indexOf(t))))}
<div className="dm-tst-sr" role="status" aria-live="polite">{say.loud ? '' : say.text}</div>
<div className="dm-tst-sr" role="alert" aria-live="assertive">{say.loud ? say.text : ''}</div>
</div>
);
}
toast-stack.cssReact · 20 lines
/* Generated from designme.dev by scripts/sync.mjs. Edit the site, then sync. */
/* ---------- Toast stack ---------- */
/* each toast in the stack is a Toast card (owner, 26 Nov: "Let's launch toast stack and toasts as launch components too"): the
same head, steps and footer, Close with its countdown ring, swipe and Escape, in each style's own corners, dividers and
shadow (Toast's section, which its installs carry too). The stack only places them. Collapsed, the cards behind the front one
take its height and peek out 8px above it, a step narrower each; under the pointer or the focus they fan out into a list, each
at its own height, 8px apart. The stack is as tall as what it shows (--dm-tsk-h, set as cards come, go and change height), so it
stays centred in its stage as it grows and shrinks; the cards and the stack move together on the motion pieces' spring */
.dm-tsk-stack{--dm-tsk-mv:calc(var(--dm-t-in) * 1.4) var(--dm-ease-spring);position:relative;width:100%;max-width:380px;height:var(--dm-tsk-h,0px);transition:height var(--dm-tsk-mv)}
.dm-tsk-stack>.dm-tst-t{position:absolute;left:0;right:0;bottom:0;max-width:none;transform-origin:50% 0;transition:transform var(--dm-tsk-mv),height var(--dm-tsk-mv),opacity var(--dm-t-fast) var(--dm-ease),filter var(--dm-t-fast) var(--dm-ease)}
/* a card arriving rises from 16px below out of a short blur (none in Blueprint and Studio); the cards behind it step back */
.dm-tsk-stack>.dm-tst-t.dm-tsk-new{transform:translateY(16px) scale(.97);opacity:0;filter:blur(var(--dm-blur-in));transition:none}
/* a card behind the front one in the deck shows only its edge: its words fade at once, so they never read through the card
that covers them, and come back as the stack fans out */
.dm-tsk-stack>.dm-tst-t>*{transition:opacity var(--dm-t-fast) var(--dm-ease)}
.dm-tsk-stack>.dm-tst-t.dm-tsk-back>*{opacity:0}
/* going: Close, its countdown or Escape fades it 8px down as the rest close the gap; a swipe carries it on sideways */
.dm-tsk-stack>.dm-tst-t.dm-tsk-out{pointer-events:none}
@media (prefers-reduced-motion:reduce){.dm-tsk-stack,.dm-tsk-stack>.dm-tst-t{transition-property:opacity}}
ToastStack.astroAstro · 30 lines
---
// Generated from designme.dev by scripts/sync.mjs. Edit the site, then sync.
// Toast stack: Agent notifications that stack and fan out on hover.
// The markup, CSS and script are designme.dev's own, run by the shared core in ../core, which mounts the component when it scrolls
// into view and plays its demo. To show your own data, change toast-stack.js. The markup is kept exactly as it is (is:raw).
import type { HTMLAttributes } from 'astro/types';
import '../core/designme.css';
import './toast-stack.css';
export interface Props extends HTMLAttributes<'div'> {
/** "soft" or "studio" draws it in that style. Leave it out for Blueprint, or for the style set on <html> (data-style="soft" or "studio") */
'data-style'?: 'soft' | 'studio';
}
const { class: className, ...rest } = Astro.props;
---
<div class:list={['card', className]} data-c="toast-stack" {...rest}>
<div class="stage-in"><Fragment is:raw>
<div class="tsk dm">
<div class="dm-main"><div class="tsk-stack" role="region" aria-label="Notifications"></div>
<div class="tst-sr" role="status" aria-live="polite"></div>
<div class="tst-sr" role="alert" aria-live="assertive"></div>
</div>
<div class="demo"><button type="button" class="pill line sm tsk-add"><svg class="i s"><use href="#i-bell"/></svg>Send notification</button></div>
</div>
</Fragment></div>
</div>
<script>
import './toast-stack.js';
</script>
toast-stack.htmlHTML · 12 lines
<div class="card" data-c="toast-stack">
<div class="stage-in">
<div class="tsk dm">
<div class="dm-main"><div class="tsk-stack" role="region" aria-label="Notifications"></div>
<div class="tst-sr" role="status" aria-live="polite"></div>
<div class="tst-sr" role="alert" aria-live="assertive"></div>
</div>
<div class="demo"><button type="button" class="pill line sm tsk-add"><svg class="i s"><use href="#i-bell"/></svg>Send notification</button></div>
</div>
</div>
</div>
toast-stack.cssHTML · 172 lines
/* ---------- Toast ---------- */
/* the Job toast (owner, 26 Nov, from the toast lab's 2a): a job the agent runs in the background lives in one toast from start
to finish. Its glyph is the news (a hand of slides, dealt as each one is drafted), its states change in place (working, a
problem with its fix, done), its steps open inside it, and Close drains a visible countdown. Plain toasts (a success or an
error with one action) are the same card: a status mark where the glyph goes, the words, Close, and the action in the
footer. It grows out of the button that started it, sits where its host puts it (centred in the stage here) and moves
with the library's own motion */
.tst{position:relative}
/* the toast on its way out and the one coming in share one cell, so each keeps its full width while they cross; the cell is
as tall as its toast and keeps no room when there is none */
.tst-slot{position:relative;width:100%;display:grid;grid-template-columns:minmax(0,1fr);justify-items:center;align-items:center}
.tst-slot>:is(.tst-t,.tst-make){grid-area:1/1}
/* the button that starts the job sits where its toast will: the toast grows out of it and, once closed, goes back into it */
.tst-make.under{visibility:hidden}
/* the card: up to 380px, the full width less its host's 16px gutters on a phone. Hover fills are a quiet 5% of the text
colour so they show on the white card. Its hairlines are 10% of the text colour, as the lab set them: half of --dm-line doesn't
show on Blueprint's dark raised grey */
.tst-t{width:100%;max-width:380px;box-sizing:border-box;background:var(--dm-raised);border-radius:var(--dm-r-card);box-shadow:var(--dm-shadow-pop);--dm-row:color-mix(in srgb,var(--dm-fg) 5%,transparent);--dm-tst-div:color-mix(in srgb,var(--dm-fg) 10%,transparent);overflow:clip;position:relative;touch-action:pan-y;user-select:none;-webkit-user-select:none}
.tst-t[hidden]{display:none}
/* (it grows with what it holds, grow(); its corners clip what is inside them exactly). The card's own height carries the motion,
so its steps and its footer open and shut at once and only fade: two eased heights on top of each other would leave the
card's edge trailing behind them */
.tst-t.growing{overflow-clip-margin:0px}
.tst-t .fold{transition:opacity var(--dm-t-fast) var(--dm-ease)}
.tst-t .fold.shut{transition:opacity var(--dm-t-fast) var(--dm-ease),visibility 0s var(--dm-t-fast)}
/* the head: the glyph, the words, then the toast's own buttons, all on one centre line, 16px in from every edge */
.tst-hd{display:flex;align-items:center;gap:var(--dm-s-3);padding:var(--dm-s-4)}
.tst-tx{flex:1;min-width:0}
.tst-ti{display:block;width:fit-content;max-width:100%;font-size:13px;font-weight:500;line-height:18px}
/* the line under the title wraps on a narrow toast rather than cutting off its news ("The sheet says 41k, not 14k") */
.tst-de{display:block;font-size:12px;line-height:18px;color:var(--dm-muted);font-variant-numeric:tabular-nums}
/* its icon buttons fill on hover, so they are measured by their box (ui-qa-gate, "boxes that fill"): Close's box, and the
countdown ring drawn on it, end on the content's right edge, 16px in, where the footer's buttons end */
.tst-hb{display:flex;align-items:center;gap:var(--dm-s-1);flex:none}
.tst-hb .ib{width:28px;height:28px;position:relative}
.tst-hb .ib[hidden]{display:none}
.tst-more .i{transition:transform var(--dm-t) var(--dm-ease)}
.tst-more[aria-expanded="true"] .i{transform:rotate(180deg)}
/* a plain toast's status mark sits where the glyph goes: the vivid green tick, the red alert, the warning sign in the bright
orange (its words stay in the text colour and its fix is .pill.warn, as the warning notices have them), a grey info mark or a spinner,
with no disc behind it, so a toast carries two hues at most */
.tst-g{flex:none;width:20px;height:20px;display:grid;place-items:center;color:var(--dm-fg2)}
.tst-g .i{width:20px;height:20px}
.tst-g .spin{width:14px;height:14px;color:var(--dm-accent-mark)}
.tst-g[data-s="success"]{color:var(--dm-ok-mark)}
.tst-g[data-s="error"]{color:var(--dm-bad-mark)}
.tst-g[data-s="warning"]{color:var(--dm-warn-mark)}
.tst-g[data-s="stopped"]{color:var(--dm-muted)}
/* the countdown you can see: a ring round Close that drains; the pointer or the focus on the toast holds it */
.tst-ring{position:absolute;inset:0;width:28px;height:28px;pointer-events:none;fill:none}
.tst-ring rect{rx:13.25px;ry:13.25px;stroke-width:1.5}
:root:not([data-style="soft"],[data-style="studio"]) .tst-ring rect:not(:where([data-style="soft"],[data-style="soft"] *,[data-style="studio"],[data-style="studio"] *)){rx:0;ry:0}
.tst-ring .tst-tk{stroke:color-mix(in srgb,var(--dm-line) 70%,transparent)}
.tst-ring .tst-rn{stroke:var(--dm-muted);stroke-dasharray:100 100;stroke-linecap:round}
.tst-ring[hidden]{display:none}
/* the steps, opened from the chevron, under a hairline: each step's mark sits centred in the glyph's column and its words
start where the title's words do; a step's count is the same size as its words, so the two share a baseline */
/* (12px round the 28px rows puts the first and last step's words 16px and more from the hairline and the card's edge) */
.tst-st{list-style:none;margin:0;padding:var(--dm-s-3) 0;border-top:1px solid var(--dm-tst-div)}
.tst-st li{display:grid;grid-template-columns:var(--dm-tst-gw,64px) minmax(0,1fr) auto;column-gap:var(--dm-s-3);align-items:center;height:28px;padding:0 var(--dm-s-4);font-size:12.5px;line-height:18px;color:var(--dm-fg2)}
.tst-st .tst-lb{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.tst-st .tst-mk{justify-self:center;width:16px;height:16px;display:grid;place-items:center}
.tst-st .tst-mk .i{width:16px;height:16px}
.tst-st .tst-mk .spin{width:12px;height:12px}
.tst-st .tst-vl{color:var(--dm-muted);font-variant-numeric:tabular-nums;white-space:nowrap}
.tst-st li[data-s="done"] .tst-mk{color:var(--dm-ok-mark)}
.tst-st li[data-s="done"] .tst-mk .i{stroke-width:2}
.tst-st li[data-s="now"]{color:var(--dm-fg)}
.tst-st li[data-s="now"] .tst-mk{color:var(--dm-accent-mark)}
.tst-st li[data-s="bad"]{color:var(--dm-fg)}
.tst-st li[data-s="bad"] .tst-mk{color:var(--dm-bad-mark)}
.tst-st li[data-s="paused"] .tst-mk{color:var(--dm-muted)}
.tst-st li[data-s="wait"]{color:var(--dm-muted)}
.tst-st .tst-pend{width:8px;height:8px;border-radius:50%;box-shadow:inset 0 0 0 1.5px var(--dm-line-strong)}
/* the footer: the actions under a hairline, on the right, 16px from the hairline, the card's bottom and its side */
.tst-fi{display:flex;align-items:center;justify-content:flex-end;gap:var(--dm-s-2);padding:var(--dm-s-4);border-top:1px solid var(--dm-tst-div)}
.tst-fi .pill{min-width:0}
.tst-fi .pill.in{animation:tstbtn var(--dm-t) var(--dm-ease) backwards}
@keyframes tstbtn{from{opacity:0;transform:translateY(4px)}}
/* the box the toast grows out of: the button that started it, easing to where the toast sits and opening into it */
.tst-fly{position:absolute;z-index:3;background:var(--dm-raised);box-shadow:var(--dm-shadow-pop);pointer-events:none}
.tst-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap}
.tst-make .i{width:14px;height:14px}
/* coming in without a button to grow from, and going: the library's own entrance for each style */
.tst-in{animation:tstin var(--dm-t-slow) var(--dm-ease) backwards}
@keyframes tstin{from{opacity:0;transform:translateY(14px) scale(.97);filter:blur(5px)}}
.tst-out{animation:tstout var(--dm-t) var(--dm-ease) both;pointer-events:none}
@keyframes tstout{to{opacity:0;transform:translateY(8px) scale(.98);filter:blur(4px)}}
/* the glyph: a hand of slides, dealt as each one is drafted */
.tst-dk{flex:none;width:64px;height:40px;display:block}
.tst-dk svg{width:64px;height:40px;display:block;overflow:visible}
/* the notes being read: a page with a line sweeping down it */
.tst-dk .tst-pg{transform-box:view-box;transform-origin:32px 24px;transition:opacity var(--dm-t-fast) var(--dm-ease),transform var(--dm-t) var(--dm-ease)}
.tst-dk .tst-pp{fill:var(--dm-raised);stroke:var(--dm-muted);stroke-width:1.2}
.tst-dk .tst-pl{stroke:var(--dm-faint);stroke-width:1.4;stroke-linecap:round}
.tst-dk .tst-sc{stroke:var(--dm-accent-mark);stroke-width:1.6;stroke-linecap:round;opacity:0}
.tst-dk.read .tst-sc{opacity:1;animation:tstscan 1s var(--dm-ease-io) infinite alternate}
@keyframes tstscan{to{transform:translateY(13px)}}
.tst-dk:not(.read,.idle,.gone) .tst-pg{opacity:0;transform:scale(.6) translateY(10px)}
/* the cards: an outline of dashed slots once the deck is planned; each slide dealt into its slot as it is drafted, the one being
drafted in the accent and in front; red where the check stopped */
.tst-dk .tst-cd{transform-box:view-box;transform-origin:32px 56px;transform:scale(.7);opacity:0;transition:transform var(--dm-t) var(--dm-ease),opacity var(--dm-t-fast) var(--dm-ease)}
.tst-dk .tst-cd .tst-b{fill:var(--dm-raised);stroke:var(--dm-faint);stroke-width:1.2;transition:fill var(--dm-t-fast) var(--dm-ease),stroke var(--dm-t-fast) var(--dm-ease)}
.tst-dk .tst-cd .tst-l{fill:none;stroke:var(--dm-faint);stroke-width:1.3;stroke-linecap:round;stroke-dasharray:8 8;stroke-dashoffset:8;transition:stroke-dashoffset var(--dm-t) var(--dm-ease),stroke var(--dm-t-fast) var(--dm-ease)}
:root:not([data-style="soft"],[data-style="studio"]) .tst-dk :is(.tst-cd .tst-b,.tst-pp):not(:where([data-style="soft"],[data-style="soft"] *,[data-style="studio"],[data-style="studio"] *)){rx:0}
.tst-dk .tst-gh .tst-b{stroke:color-mix(in srgb,var(--dm-muted) 38%,var(--dm-raised));stroke-dasharray:2 1.6}
.tst-dk .tst-gh .tst-l{display:none}
.tst-dk.plan .tst-gh{opacity:1;transform:rotate(var(--dm-a));transition-delay:calc(var(--dm-i) * 36ms)}
.tst-dk .tst-cd:is(.made,.now,.chk,.bad){opacity:1;transform:rotate(var(--dm-a))}
.tst-dk .tst-cd.made .tst-b{stroke:var(--dm-fg2)}
.tst-dk .tst-cd.made .tst-l{stroke-dashoffset:0;stroke:color-mix(in srgb,var(--dm-muted) 70%,var(--dm-raised))}
.tst-dk .tst-cd.now{transform:rotate(var(--dm-a)) translateY(-3px)}
.tst-dk .tst-cd:is(.now,.chk) .tst-b{stroke:var(--dm-accent-mark);fill:color-mix(in srgb,var(--dm-accent-mark) 10%,var(--dm-raised))}
.tst-dk .tst-cd.now .tst-b{stroke-width:1.5}
.tst-dk .tst-cd.now .tst-l{stroke:var(--dm-accent-mark);stroke-dashoffset:0}
.tst-dk .tst-cd.chk{transform:rotate(var(--dm-a)) translateY(-2px)}
.tst-dk .tst-cd.bad{transform:rotate(var(--dm-a)) translateY(-4px)}
.tst-dk .tst-cd.bad .tst-b{fill:var(--dm-bad-mark);stroke:var(--dm-bad-mark)}
.tst-dk .tst-cd.bad .tst-l{stroke:#fff;stroke-dashoffset:0}
/* done: the hand closes into a neat deck and the green tick lands in front of it */
.tst-dk.done .tst-gh{opacity:0;transition-delay:0s}
.tst-dk.done .tst-cd:not(.tst-gh){transform:rotate(calc(var(--dm-a) * .16)) translateY(3px)}
.tst-dk .tst-ok{transform-box:fill-box;transform-origin:center;transform:scale(0);opacity:0;transition:transform var(--dm-t) var(--dm-ease),opacity var(--dm-t-fast) var(--dm-ease)}
.tst-dk .tst-ok circle{fill:var(--dm-ok-mark);stroke:var(--dm-raised);stroke-width:2}
.tst-dk .tst-ok path{fill:none;stroke:#fff;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
.tst-dk.done .tst-ok{transform:none;opacity:1;transition-delay:.2s}
/* gone (undone or discarded): the cards fold back to where they came from, and the notes they were made from are back */
.tst-dk.gone .tst-cd{opacity:0;transform:scale(.6);transition-delay:0s}
/* reduced motion: things only fade; moves and turns happen at once */
@media (prefers-reduced-motion:reduce){
.tst-dk *,.tst-more .i{transition-property:opacity!important;transition-delay:0s!important}
.tst-dk .tst-sc{animation:none}
}
@keyframes tstfade{from{opacity:0}}
@keyframes tstfadeo{to{opacity:0}}
/* Studio: the card's ordinary round corners (16px), the footer an off-white strip with its buttons 16px from its hairline, the
card's bottom and its side; the ink primary and the flat secondary are Studio's own. It rises 8px from .98 and leaves with a
fade, with no blur */
:root[data-style="studio"] .tst-t,:root [data-style="studio"] .tst-t,:root [data-style="studio"].tst-t{border-radius:calc(12px * var(--dm-rk-l,var(--dm-rk)))}
:root[data-style="studio"] .tst-st,:root [data-style="studio"] .tst-st,:root [data-style="studio"].tst-st{border-top-color:var(--dm-line)}
:root[data-style="studio"] .tst-fi,:root [data-style="studio"] .tst-fi,:root [data-style="studio"].tst-fi{padding:var(--dm-strip-y) var(--dm-s-4);background:var(--dm-strip);border-top-color:var(--dm-line)}
:root[data-style="studio"] .tst-in,:root [data-style="studio"] .tst-in,:root [data-style="studio"].tst-in{animation-name:clcard}
@keyframes tstoutc{to{opacity:0;transform:translateY(6px) scale(.98)}}
:root[data-style="studio"] .tst-out,:root [data-style="studio"] .tst-out,:root [data-style="studio"].tst-out{animation-name:tstoutc;animation-duration:var(--dm-t-fast)}
/* Blueprint wipes in and goes in a short hard beat */
@keyframes tstinb{from{opacity:0;clip-path:inset(0 0 100% 0)}35%{opacity:1}to{clip-path:inset(0 0 0 0)}}
:root:not([data-style="soft"],[data-style="studio"]) .tst-in:not(:where([data-style="soft"],[data-style="soft"] *,[data-style="studio"],[data-style="studio"] *)){animation-name:tstinb}
@keyframes tstoutb{to{opacity:0;transform:translateY(4px)}}
:root:not([data-style="soft"],[data-style="studio"]) .tst-out:not(:where([data-style="soft"],[data-style="soft"] *,[data-style="studio"],[data-style="studio"] *)){animation-name:tstoutb;animation-duration:var(--dm-t-fast)}
/* reduced motion: it only fades in and out, in every style (after the styles' own, which it outranks or ties) */
@media (prefers-reduced-motion:reduce){.tst-slot .tst-t.tst-in,.tst-fi .pill.in{animation-name:tstfade}.tst-slot .tst-t.tst-out{animation-name:tstfadeo}}
/* ---------- Toast stack ---------- */
/* each toast in the stack is a Toast card (owner, 26 Nov: "Let's launch toast stack and toasts as launch components too"): the
same head, steps and footer, Close with its countdown ring, swipe and Escape, in each style's own corners, dividers and
shadow (Toast's section, which its installs carry too). The stack only places them. Collapsed, the cards behind the front one
take its height and peek out 8px above it, a step narrower each; under the pointer or the focus they fan out into a list, each
at its own height, 8px apart. The stack is as tall as what it shows (--dm-tsk-h, set as cards come, go and change height), so it
stays centred in its stage as it grows and shrinks; the cards and the stack move together on the motion pieces' spring */
.tsk-stack{--dm-tsk-mv:calc(var(--dm-t-in) * 1.4) var(--dm-ease-spring);position:relative;width:100%;max-width:380px;height:var(--dm-tsk-h,0px);transition:height var(--dm-tsk-mv)}
.tsk-stack>.tst-t{position:absolute;left:0;right:0;bottom:0;max-width:none;transform-origin:50% 0;transition:transform var(--dm-tsk-mv),height var(--dm-tsk-mv),opacity var(--dm-t-fast) var(--dm-ease),filter var(--dm-t-fast) var(--dm-ease)}
/* a card arriving rises from 16px below out of a short blur (none in Blueprint and Studio); the cards behind it step back */
.tsk-stack>.tst-t.tsk-new{transform:translateY(16px) scale(.97);opacity:0;filter:blur(var(--dm-blur-in));transition:none}
/* a card behind the front one in the deck shows only its edge: its words fade at once, so they never read through the card
that covers them, and come back as the stack fans out */
.tsk-stack>.tst-t>*{transition:opacity var(--dm-t-fast) var(--dm-ease)}
.tsk-stack>.tst-t.tsk-back>*{opacity:0}
/* going: Close, its countdown or Escape fades it 8px down as the rest close the gap; a swipe carries it on sideways */
.tsk-stack>.tst-t.tsk-out{pointer-events:none}
@media (prefers-reduced-motion:reduce){.tsk-stack,.tsk-stack>.tst-t{transition-property:opacity}}
toast-stack.jsHTML · 246 lines
// each toast in the stack is a Toast card (owner, 26 Nov): its head (a live glyph or a status mark, the words, Close with its
// countdown ring), its steps and its footer, swiped or Escaped away. The stack collapses into a deck and fans out under the
// pointer or the keyboard's focus; it reads each card's own height, and the cards and the stack ease together on the motion
// pieces' spring. Its demo is an agent's news as it comes, so it keeps playing under a resting pointer (DM.PLAYS): a job with
// its glyph at work, a success, a problem that becomes its fix in place, and one swiped away. Its timing goes through the
// controller (c.later, the story's beats), and what the visitor sets off keeps running once they take over
DM.def('toast-stack', (r, c) => {
const stack = $('.tsk-stack', r), addB = $('.tsk-add', r), [polite, loud] = $$('.tst-sr', r);
const wait = ms => new Promise(res => c.later(REDUCE ? Math.min(ms, 400) : ms, res));
const motion = () => { const cs = getComputedStyle(r), s = v => parseFloat(cs.getPropertyValue(v)) * 1000 || 340; return { ease:cs.getPropertyValue('--dm-ease').trim() || 'ease', t:s('--dm-t'), fast:s('--dm-t-fast'), tin:s('--dm-t-in') }; };
// collapsed, the two cards behind the front one peek out 8px each; fanned out, the four in front show, 8px apart; six at most
const PEEK = 8, GAP = 8, FAN = 4, MAX = 6;
const MARK = { success:I('ok'), error:I('alert'), warning:I('warn'), info:I('info'), stopped:I('pause'), working:'<span class="spin"></span>' };
const STEP = { done:I('check'), now:'<span class="spin"></span>', bad:I('alert'), paused:I('pause'), wait:'<span class="tst-pend"></span>' };
// announcements, through the stack's two live regions: news politely, a problem at once
const tell = (text, now) => { const el = now ? loud : polite; el.textContent = ''; c.later(60, () => { el.textContent = text; }); };
/* the stack fans out under a mouse, while the keyboard's focus is in it, on a tap, or while the demo's pointer rests on it */
let cards = [], hover = false, focused = false, tapped = false, shown = false;
const fanned = () => hover || focused || tapped || shown;
const layout = () => {
const fan = fanned(), front = cards.slice().reverse(), H0 = front.length ? front[0].h : 0;
let y = 0;
front.forEach((k, i) => {
let t, h = k.h, o = 1;
if (fan){ t = `translateY(${-y}px)`; if (i < FAN) y += k.h + GAP; else o = 0; }
// the cards behind the front one take its height, so each peeks out by the same 8px whatever it holds
else { const j = Math.min(i, 2); t = j ? `translateY(${-j * PEEK}px) scale(${1 - j * .05})` : 'translateY(0px)'; if (i) h = H0; if (i > 2) o = 0; }
k.base = t; k.el.style.height = h + 'px'; k.el.style.zIndex = 100 - i;
if (!k.fresh && !k.drag){ k.el.style.transform = t; k.el.style.opacity = o; }
k.el.inert = fan ? i >= FAN : i > 0;
k.el.classList.toggle('tsk-back', !fan && i > 0);
});
stack.style.setProperty('--dm-tsk-h', (fan ? Math.max(0, y - GAP) : H0 + Math.min(Math.max(front.length - 1, 0), 2) * PEEK) + 'px');
// the countdowns hold while the stack is open for reading
cards.forEach(k => { if (!k.cd) return; if (fan) k.cd.pause(); else if (k.cd.playState === 'paused') k.cd.play(); });
};
c.on(stack, 'pointerenter', e => { if (e.pointerType === 'mouse'){ hover = true; layout(); } });
c.on(stack, 'pointerleave', e => { if (e.pointerType === 'mouse'){ hover = false; layout(); } });
c.on(stack, 'focusin', e => { if (!focused && e.target.matches(':focus-visible')){ focused = true; layout(); } });
c.on(stack, 'focusout', e => { if (focused && !stack.contains(e.relatedTarget)){ focused = false; layout(); } });
// touch has no hover: a tap on the deck opens it, a tap anywhere else closes it
c.on(document, 'pointerdown', e => { if (e.pointerType === 'mouse') return; const on = stack.contains(e.target); if (on !== tapped && !(on && e.target.closest('button'))){ tapped = on; layout(); } });
/* the job's glyph: Toast's hand of slides, dealt as each one is drafted */
const N = 12, ang = i => -32 + i * 64 / (N - 1);
const slide = (i, k) => `<g class="tst-cd${k}" style="--dm-a:${ang(i).toFixed(2)}deg;--dm-i:${i}"><rect class="tst-b" x="26" y="6" width="12" height="20" rx="2"/><path class="tst-l" d="M28.5 10h6M28.5 13.5h7M28.5 17h4.5" pathLength="8"/></g>`;
const deck = '<span class="tst-dk idle" aria-hidden="true"><svg viewBox="0 0 64 40"><g class="tst-pg"><rect class="tst-pp" x="23.5" y="6.5" width="17" height="22" rx="2.5"/><path class="tst-pl" d="M27 12h10M27 15.5h8M27 19h10M27 22.5h6"/><path class="tst-sc" d="M25.5 10h13"/></g>'
+ '<g>' + Array.from({ length:N }, (_, i) => slide(i, ' tst-gh')).join('') + '</g><g class="tst-fan">' + Array.from({ length:N }, (_, i) => slide(i, '')).join('') + '</g>'
+ '<g class="tst-ok"><circle cx="41" cy="27" r="6.5"/><path d="M38.3 27.1l1.9 1.9 3.5-3.6"/></g></svg></span>';
// look: idle, read, plan, done or gone; n slides drafted, the next one in the accent while drafting
const glyph = (k, look, n = 0, now = false) => { const G = k.dk; G.setAttribute('class', 'tst-dk ' + look);
$$('.tst-fan .tst-cd', G).forEach((e, i) => { e.classList.toggle('made', look !== 'gone' && i < n); e.classList.toggle('now', now && i === n); }); };
/* a card: Toast's own markup */
const make = job => {
const el = html(`<div class="tst-t tsk-new"><div class="tsk-in">
<div class="tst-hd">${job ? deck : '<span class="tst-g mx-ic" aria-hidden="true"></span>'}
<div class="tst-tx"><span class="tst-ti"></span><span class="tst-de"></span></div>
<div class="tst-hb">
<button type="button" class="ib tst-more" aria-expanded="false" aria-label="Show the steps" data-tip="Steps" hidden>${I('chev-d')}</button>
<button type="button" class="ib tst-stop" aria-label="Stop the job" data-tip="Stop" hidden>${I('stop')}</button>
<button type="button" class="ib tst-x" aria-label="Close" data-tip="Close"><svg class="tst-ring" viewBox="0 0 28 28" aria-hidden="true" hidden><rect class="tst-tk" x=".75" y=".75" width="26.5" height="26.5"/><rect class="tst-rn" x=".75" y=".75" width="26.5" height="26.5" pathLength="100"/></svg>${I('x')}</button>
</div>
</div>
<div class="fold shut tst-mf"><div><ol class="tst-st" aria-label="Steps"></ol></div></div>
<div class="fold shut tst-ft"><div><div class="tst-fi"></div></div></div>
</div></div>`);
const q = s => $(s, el);
const k = { el, inner:q('.tsk-in'), g:q('.tst-g'), dk:q('.tst-dk'), ti:q('.tst-ti'), de:q('.tst-de'), moreB:q('.tst-more'), stopB:q('.tst-stop'), xB:q('.tst-x'),
ring:q('.tst-ring'), rn:q('.tst-rn'), mf:q('.tst-mf'), st:q('.tst-st'), ft:q('.tst-ft'), fi:q('.tst-fi'), h:0, d:{}, cd:null, base:'' };
el.style.setProperty('--dm-tst-gw', job ? '64px' : '20px');
c.on(k.moreB, 'click', () => openSteps(k));
c.on(k.stopB, 'click', () => k.d.onStop && k.d.onStop());
c.on(k.xB, 'click', () => dismiss(k));
// Escape closes the card the focus is in; the focus goes on to the next card's Close, or to the button that sends them
c.on(el, 'keydown', e => { if (e.key === 'Escape'){ e.stopPropagation(); dismiss(k, 'escape'); } });
swipe(k);
return k;
};
const openSteps = (k, open) => { open = open ?? k.mf.classList.contains('shut'); k.mf.classList.toggle('shut', !open);
k.moreB.setAttribute('aria-expanded', open); k.moreB.setAttribute('aria-label', open ? 'Hide the steps' : 'Show the steps'); k.moreB.dataset.tip = open ? 'Hide steps' : 'Steps'; };
/* what a card says and offers: d = { status, title, desc, steps:[[label, state, detail]], acts:[[variant, label, fn]], time,
onStop, say }. The same card changes in place: its words crossfade (a counter ticks over at once), its mark crossfades
(iconSwap), its footer opens and shuts, and the card eases to its new height */
const lead = x => { const m = (x || '').match(/^(\D*)\d/); return m ? m[1] : null; };
const set = (k, d) => {
const was = k.d, first = !was.title, working = d.status === 'working'; k.d = d;
if (first){ k.ti.textContent = d.title; k.ti.classList.toggle('shim', working); }
else { swap(k.ti, d.title); c.later(REDUCE ? 0 : 170, () => k.ti.classList.toggle('shim', k.d.status === 'working')); }
if (first || (lead(was.desc) !== null && lead(was.desc) === lead(d.desc))){ if (k.de._sw){ clearTimeout(k.de._sw.t); k.de._sw = null; k.de.classList.remove('out'); } k.de.textContent = d.desc; }
else swap(k.de, d.desc);
if (k.g && k.g.dataset.s !== d.status){ const to = () => { k.g.dataset.s = d.status; k.g.innerHTML = MARK[d.status]; }; first ? to() : iconSwap(k.g, to); }
k.stopB.hidden = !(working && d.onStop); k.xB.hidden = !k.stopB.hidden; k.moreB.hidden = !d.steps;
if (d.steps){
if (k.st.children.length !== d.steps.length) k.st.innerHTML = d.steps.map(() => '<li><span class="tst-mk"></span><span class="tst-lb"></span><span class="tst-vl"></span></li>').join('');
d.steps.forEach(([lb, s, v = ''], i) => { const li = k.st.children[i]; if (li.dataset.s !== s){ li.dataset.s = s; $('.tst-mk', li).innerHTML = STEP[s]; } $('.tst-lb', li).textContent = lb; $('.tst-vl', li).textContent = v; });
} else openSteps(k, false);
if (!d.acts) k.ft.classList.add('shut');
else if (d.acts !== was.acts){
const open = !k.ft.classList.contains('shut');
k.fi.innerHTML = d.acts.map(([v, t]) => `<button type="button" class="pill sm ${v}${open ? ' in' : ''}">${t}</button>`).join('');
[...k.fi.children].forEach((b, i) => b.addEventListener('click', d.acts[i][2]));
k.ft.classList.remove('shut');
}
countdown(k, working ? 0 : d.time || 0);
// (say:false changes it quietly: a counter ticking, a step on the way; the milestones are announced)
const say = d.say === false ? k.said : d.say || d.title; if (say !== k.said){ k.said = say; tell(say, d.status === 'error'); }
};
const btn = (k, t) => [...k.fi.querySelectorAll('button')].find(b => b.textContent === t);
/* the countdown on Close: a ring that drains, held while the stack is open for reading (pointer or focus); it closes the card */
const countdown = (k, ms) => { if (k.cd){ k.cd.cancel(); k.cd = null; } k.ring.toggleAttribute('hidden', !ms); if (!ms) return;
k.cd = k.rn.animate([{ strokeDashoffset:0 }, { strokeDashoffset:100 }], { duration:ms, fill:'forwards', easing:'linear' });
if (fanned()) k.cd.pause();
k.cd.onfinish = () => { k.cd = null; dismiss(k, 'timeout'); }; };
c.offs.push(() => cards.forEach(k => k.cd && k.cd.cancel()));
/* a new card comes in at the front: it rises out of a short blur as the cards it covers step back and lose their words */
const push = (d, job) => {
const k = make(job); k.fresh = true; stack.appendChild(k.el); cards.push(k);
set(k, d);
k.h = k.inner.offsetHeight;
const ro = new ResizeObserver(() => { const h = k.inner.offsetHeight; if (h && h !== k.h && !k.gone){ k.h = h; layout(); } }); ro.observe(k.inner); c.offs.push(() => ro.disconnect()); k.ro = ro;
while (cards.length > MAX) dismiss(cards[0], 'drop');
layout();
requestAnimationFrame(() => requestAnimationFrame(() => { if (c.dead || k.gone) return; k.fresh = false; k.el.classList.remove('tsk-new'); layout(); }));
return k;
};
/* a card goes: Close, its countdown or Escape fade it 8px down while the others close the gap; a swipe has carried it off */
const dismiss = (k, how = 'close') => {
if (k.gone) return; k.gone = true; countdown(k, 0); k.ro && k.ro.disconnect();
const had = k.el.contains(document.activeElement);
cards = cards.filter(x => x !== k); k.el.inert = true; k.el.classList.add('tsk-out');
const end = () => k.el.remove();
if (how === 'swipe') c.later(motion().t, end);
else { const from = getComputedStyle(k.el).transform, t0 = from === 'none' ? '' : from;
const a = k.el.animate(REDUCE ? [{ opacity:getComputedStyle(k.el).opacity }, { opacity:0 }] : [{ transform:t0 || 'none', opacity:getComputedStyle(k.el).opacity }, { transform:t0 + ' translateY(8px) scale(.98)', opacity:0 }], { duration:motion().tin, easing:motion().ease, fill:'forwards' });
a.finished.then(end, end); }
layout();
if (had && how !== 'drop'){ const next = cards[cards.length - 1]; c.later(0, () => ((next && !next.xB.hidden ? next.xB : next && next.stopB) || addB).focus({ preventScroll:true })); }
};
/* swipe a card away: it follows the finger or the pointer sideways and goes once it has moved far enough, or eases back */
const fling = (k, dx, v) => {
if (Math.abs(dx) > 90 || v > .6){ const dir = Math.sign(dx) || 1, M = motion();
// (with reduced motion it only fades where it was let go)
k.el.animate([{ transform:`${k.base} translateX(${dx}px)`, opacity:k.el.style.opacity }, { transform:`${k.base} translateX(${REDUCE ? dx : dx + dir * 140}px)`, opacity:0 }], { duration:REDUCE ? M.fast : M.t, easing:M.ease, fill:'forwards' });
k.drag = false; k.el.style.transition = ''; dismiss(k, 'swipe'); }
else { k.drag = false; k.el.style.transition = ''; k.el.style.transform = k.base; k.el.style.opacity = 1; }
};
const drag = (k, dx) => { k.drag = true; k.el.style.transition = 'none'; k.el.style.transform = `${k.base} translateX(${dx}px)`; k.el.style.opacity = String(Math.max(.2, 1 - Math.abs(dx) / 260)); };
const swipe = k => { let sw = null;
c.on(k.el, 'pointerdown', e => { if (e.button || e.target.closest('button')) return; sw = { x:e.clientX, y:e.clientY, t:performance.now(), dx:0, id:e.pointerId, on:false }; });
c.on(k.el, 'pointermove', e => { if (!sw || e.pointerId !== sw.id) return; const dx = e.clientX - sw.x, dy = e.clientY - sw.y;
if (!sw.on){ if (Math.abs(dx) < 6 || Math.abs(dy) > Math.abs(dx)) return; sw.on = true; k.el.setPointerCapture(e.pointerId); }
sw.dx = dx; drag(k, dx); });
const up = e => { if (!sw || e.pointerId !== sw.id) return; const s = sw; sw = null; if (s.on) fling(k, s.dx, Math.abs(s.dx) / Math.max(1, performance.now() - s.t)); };
c.on(k.el, 'pointerup', up); c.on(k.el, 'pointercancel', up); };
/* the news */
const SEC = ['Cover', 'Agenda', 'Revenue', 'North', 'South', 'Plan vs actual', 'By region', 'Hiring', 'Open roles', 'Risks', 'Data move', 'Next steps'];
// a job the agent runs in the background: it reads the notes, outlines and drafts twelve slides; Stop pauses it
const job = () => {
let tok = 0, n = 0, at = 0;
const L = ['Read the notes', 'Outline 12 slides', 'Draft the slides'];
const steps = (s, v) => L.map((lb, i) => [lb, i < at ? 'done' : i === at ? s : 'wait', i === 2 && i <= at && v ? v : '']);
const work = (title, desc) => ({ status:'working', title, desc, steps:steps('now', at === 2 ? `${Math.min(n + 1, N)} of 12` : ''), onStop:stop, say:at ? false : 'Making slides from your notes' });
const k = push({ status:'working', title:'Reading your notes…', desc:'3 sections · 212 words', steps:steps('now'), onStop:() => stop(), say:'Making slides from your notes' }, true);
const live = t => t === tok && !k.gone && !c.dead;
async function go(t){
if (at === 0){ glyph(k, 'read'); set(k, work('Reading your notes…', '3 sections · 212 words')); await wait(1600); if (!live(t)) return; at = 1; }
if (at === 1){ glyph(k, 'plan'); set(k, { ...work('Outlining the deck…', '12 slides planned'), say:false }); await wait(1200); if (!live(t)) return; at = 2; }
while (n < N){ glyph(k, 'plan', n, true); set(k, { ...work('Drafting slides…', `Slide ${n + 1} of 12 · ${SEC[n]}`), say:n === 6 ? 'Half the slides are drafted' : false }); await wait(380); if (!live(t)) return; n++; }
at = 3; glyph(k, 'done', N); done();
}
const done = () => set(k, { status:'success', title:'12 slides ready', desc:'Q3 planning deck', steps:steps('done'), time:12000, say:'12 slides ready. Open the deck or undo it.',
acts:[['line', 'Undo', () => { glyph(k, 'gone'); set(k, { status:'success', title:'Deck removed', desc:'Your notes are unchanged', steps:steps('done'), time:6000, acts:[['line', 'Redo', () => { glyph(k, 'done', N); done(); }]] }); }], ['primary', 'Open', () => dismiss(k)]] });
function stop(){ tok++; glyph(k, at ? 'plan' : 'idle', n); set(k, { status:'stopped', title:at === 2 ? `Stopped at slide ${n}` : 'Stopped before drafting', desc:`${n} of 12 drafted · nothing lost`, steps:steps('paused', `${n} of 12`), say:`Stopped. ${n} of 12 drafted. Resume or discard.`,
acts:[['line', 'Discard', () => dismiss(k)], ['primary', 'Resume', () => go(++tok)]] }); }
go(++tok);
return k;
};
// a problem the agent can fix: the card becomes its fix, then the result, in place
const tests = () => {
let tok = 0;
const T = [['Cart total rounds down', 'bad'], ['Tax shows on the receipt', 'bad'], ['40 other tests', 'done']];
const fail = () => ({ status:'error', title:'2 tests failed', desc:'checkout.spec · the total is 1¢ off', steps:T, say:'2 tests failed in checkout.spec. Fix them or ignore them.',
acts:[['line', 'Ignore', () => dismiss(k)], ['primary', 'Fix', () => fix()]] });
const k = push(fail());
async function fix(){ const t = ++tok, live = () => t === tok && !k.gone && !c.dead;
const stop = () => { tok++; set(k, fail()); };
set(k, { status:'working', title:'Fixing 2 tests…', desc:'Rounding in cart.ts', steps:T.map(([l, s]) => [l, s === 'bad' ? 'now' : s]), onStop:stop, say:'Fixing 2 tests' }); await wait(1700); if (!live()) return;
for (let i = 6; i <= 42; i += 6){ set(k, { status:'working', title:'Running checkout.spec…', desc:`Passed ${i} of 42`, steps:T.map(([l]) => [l, 'done']), onStop:stop, say:false }); await wait(200); if (!live()) return; }
set(k, { status:'success', title:'42 tests passed', desc:'Fixed in cart.ts · 1 line', steps:T.map(([l]) => [l, 'done']), time:10000, acts:[['line', 'View diff', () => dismiss(k)]], say:'42 tests passed. Fixed in cart.ts.' });
}
return k;
};
// plain news, and what Send notification sends: one action at most, and a countdown
const POOL = [
{ status:'success', title:'Frames synced', desc:'6 frames from Pricing.fig', time:9000 },
{ status:'info', title:'PR #412 is ready', desc:'Use shared spacing tokens · 3 files', time:10000, acts:[['primary', 'Review', null]] },
{ status:'warning', title:'Budget at 80%', desc:'1,600 of 2,000 credits', time:12000, acts:[['warn', 'Raise cap', null]] },
{ status:'success', title:'Draft written', desc:'Launch email · 2 subject lines', time:9000 }
];
let sent = 0;
const news = (d = POOL[sent++ % POOL.length]) => { let k;
const acts = d.acts && d.acts.map(([v, t]) => [v, t, () => t === 'Raise cap' ? set(k, { status:'success', title:'Cap raised to 3,000', desc:'1,600 of 3,000 credits', time:6000 }) : dismiss(k)]);
k = push({ ...d, acts }); return k; };
c.on(addB, 'click', () => news());
/* the demo: a job starts, a success and a problem arrive; the pointer opens the stack, fixes the problem, swipes the success
away, and leaves the stack to fold back */
c.story(async s => {
await s.beat(1);
const J = job();
await s.beat(3);
const F = news(POOL[0]); sent = 1;
await s.beat(3);
const P = tests();
await s.beat(3);
await s.point(P.ti, false); shown = true; layout();
await s.beat(3);
await s.tap(btn(P, 'Fix'));
await s.until(() => P.d.status === 'success');
await s.beat(2);
// the swipe: the pointer takes the synced frames' card and drags it off to the right
if (!F.gone){
await s.point(F.de, false);
const hand = $('.hand', c.st), m = /translate\(([-\d.]+)px,\s*([-\d.]+)px\)/.exec(hand ? hand.style.transform : '');
if (hand){ hand.classList.add('down'); hand.style.transition = 'none'; }
await tween(0, 120, REDUCE ? 1 : 360, dx => { if (c.mine || c.dead || F.gone) return; drag(F, dx); if (hand && m) hand.style.transform = `translate(${+m[1] + dx}px,${m[2]}px)`; }, t => t * t);
if (hand){ hand.style.transition = ''; hand.classList.remove('down'); }
if (c.mine || c.dead) throw 'stop';
if (!F.gone) fling(F, 120, 1);
}
await s.beat(3);
s.away(); shown = false; layout();
await s.until(() => J.d.title === '12 slides ready');
await s.beat(5);
});
// the visitor takes over: the stack follows their pointer and focus alone
c.taken(() => { if (shown){ shown = false; layout(); } });
});
Questions
What people ask about it.
- How do I add a new notification?
- Append a toast with a new
idto the end oftoasts. It rises in at the front and the others step back. - How does a problem become its fix in the same card?
- Keep its
id. Show the problem withstatus: 'error'and the fix as the primary action; when it is pressed, setstatus: 'working'with a title like "Fixing 2 tests…", thenstatus: 'success'with the result. The card changes in place wherever it sits in the stack. - Do I have to remove a closed toast from my state?
- It leaves the stack as soon as it is closed, by Close, its countdown, a swipe or Escape, and
onDismisstells you which. Drop it fromtoaststoo, so it doesn't come back if you reuse the list. - Can I keep the stack fanned out all the time?
- Yes. Pass
expanded={true}to keep it open, orexpanded={false}to keep it collapsed. While it is fanned out, the countdowns hold. - Does it need Toast too?
- Yes: every card is Toast's card.
npx designme add toast-stack --reactadds Toast beside it, and the HTML and Astro versions carry Toast's styles in their own CSS.
More in Agent status
Show what the agent is doing, how far along it is, and what it is working with.