@c9up/nebula 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +9 -8
  2. package/dist/atoms/AspectRatio.d.ts +10 -4
  3. package/dist/atoms/AspectRatio.js +21 -6
  4. package/dist/atoms/Avatar.d.ts +14 -0
  5. package/dist/atoms/Avatar.js +46 -8
  6. package/dist/atoms/NativeSelect.d.ts +10 -0
  7. package/dist/atoms/NativeSelect.js +4 -1
  8. package/dist/atoms/Progress.d.ts +9 -1
  9. package/dist/atoms/Progress.js +21 -5
  10. package/dist/atoms/Switch.d.ts +7 -1
  11. package/dist/atoms/Switch.js +7 -1
  12. package/dist/cli/add.d.ts +2 -0
  13. package/dist/cli/add.js +4 -1
  14. package/dist/cli/diff.d.ts +48 -0
  15. package/dist/cli/diff.js +77 -3
  16. package/dist/cli/projectConfig.d.ts +16 -0
  17. package/dist/cli/projectConfig.js +61 -0
  18. package/dist/console/AddCommand.js +6 -1
  19. package/dist/console/DiffCommand.js +12 -12
  20. package/dist/lib/icons.d.ts +8 -0
  21. package/dist/lib/icons.js +8 -0
  22. package/dist/lib/image.js +12 -1
  23. package/dist/molecules/Accordion.js +1 -2
  24. package/dist/molecules/Collapsible.js +1 -2
  25. package/dist/molecules/InputOTP.d.ts +12 -0
  26. package/dist/molecules/InputOTP.js +68 -27
  27. package/dist/molecules/Resizable.d.ts +6 -0
  28. package/dist/molecules/Resizable.js +8 -2
  29. package/dist/molecules/index.d.ts +1 -1
  30. package/dist/molecules/index.js +1 -1
  31. package/dist/organisms/AlertDialog.js +4 -5
  32. package/dist/organisms/Chart.d.ts +103 -15
  33. package/dist/organisms/Chart.js +518 -99
  34. package/dist/organisms/Combobox.d.ts +13 -0
  35. package/dist/organisms/Combobox.js +5 -2
  36. package/dist/organisms/Command.js +56 -8
  37. package/dist/organisms/Dialog.js +7 -7
  38. package/dist/organisms/Form.d.ts +15 -0
  39. package/dist/organisms/Form.js +10 -0
  40. package/dist/organisms/Select.d.ts +6 -4
  41. package/dist/organisms/Select.js +1 -0
  42. package/dist/organisms/Sidebar.d.ts +9 -9
  43. package/dist/organisms/Sidebar.js +77 -32
  44. package/dist/organisms/Sonner.d.ts +243 -0
  45. package/dist/organisms/Sonner.js +916 -0
  46. package/dist/organisms/Toaster.d.ts +9 -0
  47. package/dist/organisms/Toaster.js +28 -5
  48. package/dist/organisms/Tooltip.d.ts +4 -0
  49. package/dist/organisms/index.d.ts +7 -1
  50. package/dist/organisms/index.js +7 -1
  51. package/dist/primitives/dismissable.d.ts +11 -4
  52. package/dist/primitives/dismissable.js +8 -6
  53. package/dist/primitives/floating.d.ts +5 -1
  54. package/dist/primitives/floating.js +8 -1
  55. package/dist/primitives/menu.js +2 -1
  56. package/dist/primitives/menuParts.js +3 -3
  57. package/dist/primitives/modalSurface.js +70 -36
  58. package/dist/primitives/portal.d.ts +15 -0
  59. package/dist/primitives/portal.js +18 -1
  60. package/dist/primitives/presence.js +8 -5
  61. package/nebula.css +2 -2
  62. package/package.json +1 -1
  63. package/registry.json +13 -0
  64. package/src/atoms/AspectRatio.ts +21 -6
  65. package/src/atoms/Avatar.ts +54 -7
  66. package/src/atoms/NativeSelect.ts +14 -1
  67. package/src/atoms/Progress.ts +21 -5
  68. package/src/atoms/Switch.ts +7 -1
  69. package/src/cli/add.ts +7 -1
  70. package/src/cli/diff.ts +130 -3
  71. package/src/cli/projectConfig.ts +71 -0
  72. package/src/console/AddCommand.ts +6 -1
  73. package/src/console/DiffCommand.ts +18 -16
  74. package/src/lib/icons.ts +28 -0
  75. package/src/lib/image.ts +13 -1
  76. package/src/molecules/Accordion.ts +1 -2
  77. package/src/molecules/Collapsible.ts +1 -3
  78. package/src/molecules/InputOTP.ts +81 -27
  79. package/src/molecules/Resizable.ts +8 -2
  80. package/src/molecules/index.ts +3 -0
  81. package/src/organisms/AlertDialog.ts +3 -5
  82. package/src/organisms/Chart.ts +633 -125
  83. package/src/organisms/Combobox.ts +18 -2
  84. package/src/organisms/Command.ts +66 -7
  85. package/src/organisms/Dialog.ts +6 -7
  86. package/src/organisms/Form.ts +21 -0
  87. package/src/organisms/Select.ts +7 -4
  88. package/src/organisms/Sidebar.ts +75 -25
  89. package/src/organisms/Sonner.ts +1373 -0
  90. package/src/organisms/Toaster.ts +30 -6
  91. package/src/organisms/Tooltip.ts +4 -0
  92. package/src/organisms/index.ts +29 -0
  93. package/src/primitives/dismissable.ts +16 -8
  94. package/src/primitives/floating.ts +13 -2
  95. package/src/primitives/menu.ts +2 -1
  96. package/src/primitives/menuParts.ts +3 -3
  97. package/src/primitives/modalSurface.ts +77 -40
  98. package/src/primitives/portal.ts +27 -1
  99. package/src/primitives/presence.ts +12 -9
@@ -0,0 +1,1373 @@
1
+ /**
2
+ * Sonner — toasts, the way shadcn ships them now.
3
+ *
4
+ * shadcn deprecated its own `toast` component in favour of `sonner`, a thin
5
+ * wrapper over Emil Kowalski's library of the same name. This is that pair in
6
+ * one file, ported to aurora without the library: a `Toaster` region mounted
7
+ * once near the root, and a `toast` function callable from anywhere in the
8
+ * browser — a route handler's error branch included — with no reference to
9
+ * the region. On the server a toast is not kept: the region renders empty
10
+ * there, and page code that raises one runs again in the browser.
11
+ *
12
+ * Toaster({ richColors: true, closeButton: true })
13
+ *
14
+ * toast('Event created', { description: 'Sunday, 9:00' })
15
+ * toast.error('Could not save', { action: { label: 'Retry', onClick: save } })
16
+ * toast.promise(save(form), {
17
+ * loading: 'Saving…',
18
+ * success: (saved) => `Saved ${saved.name}`,
19
+ * error: 'Could not save',
20
+ * })
21
+ *
22
+ * The API is sonner's, read from its published source: the same `toast`
23
+ * methods, the same options, the same Toaster props, the same defaults (four
24
+ * seconds on screen, three toasts visible, a 14px gap, 356px wide, `Alt+T` to
25
+ * reach the region). The look is shadcn's: the surface takes the popover
26
+ * colours, and the icons are the lucide set shadcn hands to sonner. The stack
27
+ * is sonner's too — toasts pile up behind the newest one, scaled down, and fan
28
+ * out while the pointer is over them, which also pauses their timers.
29
+ *
30
+ * NAMED DEVIATIONS, all deliberate:
31
+ *
32
+ * - **Announcements go through two hidden live regions**, mounted empty with
33
+ * the region: `polite` for every toast, `assertive` for an error. sonner
34
+ * makes its whole list one polite region, so an error waits its turn behind
35
+ * whatever is being read, and a list inserted with content in it is not
36
+ * announced by most screen readers at all.
37
+ * - **The layout is computed, not styled.** sonner drives its stack from a
38
+ * stylesheet it injects, reading custom properties it sets per toast. Here
39
+ * the same rules produce an inline `transform`, `opacity` and `height`, so
40
+ * the stack works under every adapter — nothing depends on a stylesheet that
41
+ * might not be there, or on compound selectors an engine might not emit.
42
+ * - **`class`, `descriptionClass`**, where React says `className`. Every
43
+ * nebula component spells it that way.
44
+ * - **`toast.promise` returns `{ id, unwrap }`**, not the id with `unwrap`
45
+ * grafted on: a number or a string cannot carry a method without being
46
+ * boxed into something that is no longer equal to the id.
47
+ * - **No swipe to dismiss, no `getHistory`, no focus hand-back on blur.**
48
+ * The close button, the timer and `Alt+T` remain; an app that needs a swipe
49
+ * gesture has the `data-*` attributes sonner's own CSS reads.
50
+ * - `action` and `cancel` take `{ label, onClick }` only, not an arbitrary
51
+ * element; `toast.custom` is the way to render something of your own.
52
+ */
53
+
54
+ import {
55
+ component,
56
+ each,
57
+ effect,
58
+ html,
59
+ isEach,
60
+ isTemplateResult,
61
+ onMount,
62
+ onUnmount,
63
+ type ReadSignal,
64
+ signal,
65
+ uid,
66
+ untrack,
67
+ } from "@c9up/aurora";
68
+ import type { Child, Slot } from "../lib/children.js";
69
+ import { cn } from "../lib/cn.js";
70
+ import {
71
+ CircleCheckIcon,
72
+ InfoIcon,
73
+ LoaderIcon,
74
+ OctagonXIcon,
75
+ TriangleAlertIcon,
76
+ XIcon,
77
+ } from "../lib/icons.js";
78
+ import { type Reactive, read } from "../lib/props.js";
79
+
80
+ // ─── Types ───────────────────────────────────────────────────────────
81
+
82
+ /** `undefined` is a plain `toast()`: no icon, no rich colour. */
83
+ export type ToastType =
84
+ | "default"
85
+ | "success"
86
+ | "info"
87
+ | "warning"
88
+ | "error"
89
+ | "loading";
90
+
91
+ export type Position =
92
+ | "top-left"
93
+ | "top-right"
94
+ | "bottom-left"
95
+ | "bottom-right"
96
+ | "top-center"
97
+ | "bottom-center";
98
+
99
+ /** A number when `toast` minted it, the caller's own when one was given. */
100
+ export type ToastId = number | string;
101
+
102
+ export interface Action {
103
+ label: Child;
104
+ onClick: (event: MouseEvent) => void;
105
+ }
106
+
107
+ /** Extra classes per part, merged after nebula's own. */
108
+ export interface ToastClassnames {
109
+ toast?: string;
110
+ title?: string;
111
+ description?: string;
112
+ loader?: string;
113
+ closeButton?: string;
114
+ cancelButton?: string;
115
+ actionButton?: string;
116
+ success?: string;
117
+ error?: string;
118
+ info?: string;
119
+ warning?: string;
120
+ loading?: string;
121
+ default?: string;
122
+ content?: string;
123
+ icon?: string;
124
+ }
125
+
126
+ /** Replaces shadcn's icons. `null` for a type shows none. */
127
+ export interface ToastIcons {
128
+ success?: Child;
129
+ info?: Child;
130
+ warning?: Child;
131
+ error?: Child;
132
+ loading?: Child;
133
+ close?: Child;
134
+ }
135
+
136
+ /** What every `toast` call takes after its message. */
137
+ export interface ExternalToast {
138
+ /**
139
+ * A stable id. A toast raised under an id already on screen UPDATES it —
140
+ * which is how a loading toast becomes its outcome, and how "you are
141
+ * offline", raised on every failed request, stays one toast.
142
+ */
143
+ id?: ToastId;
144
+ /** Shown only by the `Toaster` whose `id` is this. */
145
+ toasterId?: string;
146
+ description?: Slot;
147
+ /** Replaces the type's icon; `null` shows none. */
148
+ icon?: Child;
149
+ richColors?: boolean;
150
+ invert?: boolean;
151
+ closeButton?: boolean;
152
+ /** `false` keeps the close button and the timer from removing it. */
153
+ dismissible?: boolean;
154
+ /** Milliseconds on screen. `Infinity` keeps it until dismissed. */
155
+ duration?: number;
156
+ action?: Action;
157
+ cancel?: Action;
158
+ /** Called when it is dismissed: the close button, `cancel`, `toast.dismiss`. */
159
+ onDismiss?: (toast: ToastT) => void;
160
+ /** Called when its time runs out. */
161
+ onAutoClose?: (toast: ToastT) => void;
162
+ class?: string;
163
+ descriptionClass?: string;
164
+ classNames?: ToastClassnames;
165
+ /** Drops nebula's look, keeping only the layout. */
166
+ unstyled?: boolean;
167
+ /** A corner of its own, other than the Toaster's. */
168
+ position?: Position;
169
+ testId?: string;
170
+ }
171
+
172
+ /** A toast as the region holds it. */
173
+ export interface ToastT extends ExternalToast {
174
+ readonly id: ToastId;
175
+ title?: Slot;
176
+ type?: ToastType;
177
+ /** What `toast.custom` rendered, in place of the title and the styling. */
178
+ custom?: Child;
179
+ /** Raised by `toast.promise`. */
180
+ promise?: boolean;
181
+ }
182
+
183
+ /** A stage of `toast.promise` that says more than its message. */
184
+ export interface PromiseExtendedResult extends ExternalToast {
185
+ message: Child;
186
+ }
187
+
188
+ type StageValue = Child | PromiseExtendedResult;
189
+
190
+ /** A stage of `toast.promise`: its message, or a function of the outcome. */
191
+ export type PromiseResult<Value> =
192
+ | StageValue
193
+ | ((value: Value) => StageValue | Promise<StageValue>);
194
+
195
+ export interface PromiseData<Value> extends Omit<ExternalToast, "description"> {
196
+ loading?: Child;
197
+ success?: PromiseResult<Value>;
198
+ error?: PromiseResult<unknown>;
199
+ description?: Child | ((value: unknown) => Child | Promise<Child>);
200
+ finally?: () => void | Promise<void>;
201
+ }
202
+
203
+ // ─── State ───────────────────────────────────────────────────────────
204
+
205
+ /** sonner's defaults, as its source declares them. */
206
+ const VISIBLE_TOASTS_AMOUNT = 3;
207
+ const VIEWPORT_OFFSET = "24px";
208
+ const MOBILE_VIEWPORT_OFFSET = "16px";
209
+ const TOAST_LIFETIME = 4000;
210
+ const TOAST_WIDTH = 356;
211
+ const GAP = 14;
212
+ const TIME_BEFORE_UNMOUNT = 200;
213
+ /** How long an announcement stays in its live region once read. */
214
+ const ANNOUNCEMENT_LIFETIME = 7000;
215
+
216
+ interface ToastRecord extends ToastT {
217
+ /** One per toast raised, so a new toast under a reused id is a new row. */
218
+ readonly serial: number;
219
+ /** Dismissed: playing its exit before it leaves the list. */
220
+ readonly removing: boolean;
221
+ }
222
+
223
+ type ToastInput = Omit<ToastT, "id"> & { id?: ToastId };
224
+
225
+ /** Newest first, as sonner stacks them. */
226
+ const records = signal<readonly ToastRecord[]>([]);
227
+ let counter = 1;
228
+ let serials = 0;
229
+
230
+ function idFor(data: { id?: ToastId }): ToastId {
231
+ if (typeof data.id === "number") return data.id;
232
+ if (typeof data.id === "string" && data.id.length > 0) return data.id;
233
+ const id = counter;
234
+ counter += 1;
235
+ return id;
236
+ }
237
+
238
+ /**
239
+ * No document: this is the server, rendering a page for one request in a
240
+ * process that renders everyone's. A toast kept here would reach the next
241
+ * user's markup and never leave, its timer belonging to a mounted row.
242
+ */
243
+ function onServer(): boolean {
244
+ return typeof document === "undefined";
245
+ }
246
+
247
+ function create(data: ToastInput): ToastId {
248
+ const id = idFor(data);
249
+ // The page code that raised it runs again in the browser, where it is kept.
250
+ if (onServer()) return id;
251
+ const list = records();
252
+ const existing = list.find((entry) => entry.id === id && !entry.removing);
253
+ if (existing !== undefined) {
254
+ records(
255
+ list.map((entry) =>
256
+ entry === existing ? { ...entry, ...data, id } : entry,
257
+ ),
258
+ );
259
+ return id;
260
+ }
261
+ // One still leaving under the same id is gone: this is a new toast, not
262
+ // a merge, or its old `action` would leak into the new one.
263
+ serials += 1;
264
+ const fresh: ToastRecord = { ...data, id, serial: serials, removing: false };
265
+ records([fresh, ...list.filter((entry) => entry.id !== id)]);
266
+ return id;
267
+ }
268
+
269
+ /**
270
+ * Run an application callback without letting it take the caller down: they
271
+ * run from a timer, a click and `dismiss()` alike, and one that throws would
272
+ * leave the list half-updated.
273
+ */
274
+ function notify(
275
+ callback: ((toast: ToastT) => void) | undefined,
276
+ toast: ToastT,
277
+ ): void {
278
+ if (callback === undefined) return;
279
+ try {
280
+ callback(toast);
281
+ } catch (error) {
282
+ console.error("[nebula] a toast callback threw", error);
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Start a toast's exit, and drop it once the exit has played.
288
+ *
289
+ * The drop is scheduled here, not by the region, so a toast dismissed while
290
+ * no `Toaster` is mounted still leaves.
291
+ */
292
+ function remove(id: ToastId, reason: "dismiss" | "autoClose" | "silent"): void {
293
+ const target = records().find((entry) => entry.id === id && !entry.removing);
294
+ if (target === undefined) return;
295
+ records(
296
+ records().map((entry) =>
297
+ entry === target ? { ...entry, removing: true } : entry,
298
+ ),
299
+ );
300
+ if (reason === "dismiss") notify(target.onDismiss, target);
301
+ if (reason === "autoClose") notify(target.onAutoClose, target);
302
+ setTimeout(() => {
303
+ records(records().filter((entry) => entry.serial !== target.serial));
304
+ }, TIME_BEFORE_UNMOUNT);
305
+ }
306
+
307
+ function dismiss(id?: ToastId): ToastId | undefined {
308
+ if (id === undefined) {
309
+ for (const entry of records()) {
310
+ if (!entry.removing) remove(entry.id, "dismiss");
311
+ }
312
+ return id;
313
+ }
314
+ remove(id, "dismiss");
315
+ return id;
316
+ }
317
+
318
+ function isNodeLike(value: object): boolean {
319
+ return typeof Node !== "undefined" && value instanceof Node;
320
+ }
321
+
322
+ /** A stage that carries options, rather than a message to show. */
323
+ function isExtendedResult(value: unknown): value is PromiseExtendedResult {
324
+ return (
325
+ typeof value === "object" &&
326
+ value !== null &&
327
+ !Array.isArray(value) &&
328
+ !isTemplateResult(value) &&
329
+ !isNodeLike(value) &&
330
+ "message" in value
331
+ );
332
+ }
333
+
334
+ function isHttpResponse(
335
+ value: unknown,
336
+ ): value is { ok: boolean; status: number } {
337
+ return (
338
+ typeof value === "object" &&
339
+ value !== null &&
340
+ "ok" in value &&
341
+ typeof value.ok === "boolean" &&
342
+ "status" in value &&
343
+ typeof value.status === "number"
344
+ );
345
+ }
346
+
347
+ async function stageValue<Value>(
348
+ stage: PromiseResult<Value>,
349
+ value: Value,
350
+ ): Promise<PromiseExtendedResult> {
351
+ const result =
352
+ typeof stage === "function" && !isEach(stage) ? await stage(value) : stage;
353
+ return isExtendedResult(result) ? result : { message: result };
354
+ }
355
+
356
+ function promise<Value>(
357
+ work: Promise<Value> | (() => Promise<Value>),
358
+ data?: PromiseData<Value>,
359
+ ): { id: ToastId | undefined; unwrap: () => Promise<Value> } {
360
+ const run = Promise.resolve(typeof work === "function" ? work() : work);
361
+ if (data === undefined) return { id: undefined, unwrap: () => run };
362
+
363
+ const {
364
+ loading,
365
+ success,
366
+ error,
367
+ description,
368
+ finally: onFinally,
369
+ ...options
370
+ } = data;
371
+ let id: ToastId | undefined;
372
+ if (loading !== undefined) {
373
+ id = create({
374
+ ...options,
375
+ promise: true,
376
+ type: "loading",
377
+ title: loading,
378
+ description:
379
+ typeof description === "function" && !isEach(description)
380
+ ? undefined
381
+ : description,
382
+ });
383
+ }
384
+
385
+ async function settle<Stage>(
386
+ type: "success" | "error",
387
+ stage: PromiseResult<Stage>,
388
+ value: Stage,
389
+ ): Promise<void> {
390
+ const { message, ...settings } = await stageValue(stage, value);
391
+ const text =
392
+ typeof description === "function" && !isEach(description)
393
+ ? await description(value)
394
+ : description;
395
+ create({
396
+ ...options,
397
+ id,
398
+ type,
399
+ description: text,
400
+ ...settings,
401
+ title: message,
402
+ });
403
+ }
404
+
405
+ // The loading toast stays only while nothing has replaced it.
406
+ let shouldDismiss = id !== undefined;
407
+ let outcome:
408
+ | { ok: true; value: Value }
409
+ | { ok: false; reason: unknown }
410
+ | undefined;
411
+ const done = run
412
+ .then(async (response) => {
413
+ outcome = { ok: true, value: response };
414
+ if (isHttpResponse(response) && !response.ok) {
415
+ shouldDismiss = false;
416
+ if (error !== undefined) {
417
+ await settle(
418
+ "error",
419
+ error,
420
+ `HTTP error! status: ${response.status}`,
421
+ );
422
+ }
423
+ } else if (response instanceof Error) {
424
+ shouldDismiss = false;
425
+ if (error !== undefined) await settle("error", error, response);
426
+ } else if (success !== undefined) {
427
+ shouldDismiss = false;
428
+ await settle("success", success, response);
429
+ }
430
+ })
431
+ .catch(async (reason: unknown) => {
432
+ outcome = { ok: false, reason };
433
+ if (error !== undefined) {
434
+ shouldDismiss = false;
435
+ await settle("error", error, reason);
436
+ }
437
+ })
438
+ .finally(() => {
439
+ if (shouldDismiss && id !== undefined) dismiss(id);
440
+ return onFinally?.();
441
+ });
442
+
443
+ return {
444
+ id,
445
+ unwrap: () =>
446
+ done.then(() => {
447
+ if (outcome?.ok === true) return outcome.value;
448
+ return Promise.reject(
449
+ outcome?.ok === false ? outcome.reason : undefined,
450
+ );
451
+ }),
452
+ };
453
+ }
454
+
455
+ function typed(type: ToastType | undefined) {
456
+ return (message: Slot, data?: ExternalToast): ToastId =>
457
+ create({ ...data, title: message, type });
458
+ }
459
+
460
+ /**
461
+ * Raise a toast. Returns its id, which `toast.dismiss` takes.
462
+ *
463
+ * Callable from anywhere — no component, no context, no handle.
464
+ */
465
+ export const toast = Object.assign(typed(undefined), {
466
+ /** A plain toast; on an existing id, resets its type. */
467
+ message: typed(undefined),
468
+ success: typed("success"),
469
+ info: typed("info"),
470
+ warning: typed("warning"),
471
+ error: typed("error"),
472
+ /** Stays until it is updated or dismissed. */
473
+ loading: typed("loading"),
474
+ /** Render your own content, unstyled; `render` gets the toast's id. */
475
+ custom(render: (id: ToastId) => Child, data?: ExternalToast): ToastId {
476
+ const id = idFor(data ?? {});
477
+ return create({ ...data, id, custom: render(id), type: undefined });
478
+ },
479
+ /**
480
+ * One toast for the whole life of an async call: loading, then its outcome.
481
+ *
482
+ * A rejection is reported, not swallowed: `unwrap()` hands it back to the
483
+ * caller's own error path.
484
+ */
485
+ promise,
486
+ /** Dismiss one toast, or every toast when no id is given. */
487
+ dismiss,
488
+ /** The toasts on screen, newest first. */
489
+ getToasts(): ToastT[] {
490
+ return records().filter((entry) => !entry.removing);
491
+ },
492
+ });
493
+
494
+ // ─── Toaster ─────────────────────────────────────────────────────────
495
+
496
+ export type Offset =
497
+ | {
498
+ top?: string | number;
499
+ right?: string | number;
500
+ bottom?: string | number;
501
+ left?: string | number;
502
+ }
503
+ | string
504
+ | number;
505
+
506
+ /** Defaults for every toast this region shows. */
507
+ export interface ToastOptions {
508
+ class?: string;
509
+ closeButton?: boolean;
510
+ descriptionClass?: string;
511
+ duration?: number;
512
+ unstyled?: boolean;
513
+ classNames?: ToastClassnames;
514
+ /** The close cross's accessible name. Default `"Close toast"`. */
515
+ closeButtonAriaLabel?: string;
516
+ }
517
+
518
+ export interface ToasterProps {
519
+ /** Shows only the toasts raised with this `toasterId`. */
520
+ id?: string;
521
+ invert?: boolean;
522
+ /**
523
+ * `"system"` follows the app's `dark` variant, which is what shadcn hands
524
+ * sonner from `next-themes`. Default `"system"`.
525
+ */
526
+ theme?: "light" | "dark" | "system";
527
+ /** Default `"bottom-right"`. */
528
+ position?: Position;
529
+ /** `KeyboardEvent` keys and codes that reach the region. Default Alt+T. */
530
+ hotkey?: string[];
531
+ richColors?: boolean;
532
+ /** Keep the stack fanned out instead of piled up. */
533
+ expand?: boolean;
534
+ /** Milliseconds on screen. Default 4000. */
535
+ duration?: number;
536
+ /** Space between fanned-out toasts. Default 14. */
537
+ gap?: number;
538
+ /** How many show at once. Default 3. */
539
+ visibleToasts?: number;
540
+ closeButton?: boolean;
541
+ toastOptions?: ToastOptions;
542
+ class?: Reactive<string>;
543
+ /** From the viewport's edges. Default `24px`. */
544
+ offset?: Offset;
545
+ /** The same, at 600px wide and under. Default `16px`. */
546
+ mobileOffset?: Offset;
547
+ dir?: "rtl" | "ltr" | "auto";
548
+ icons?: ToastIcons;
549
+ /** Replaces the region's whole accessible name. */
550
+ customAriaLabel?: string;
551
+ /** The region's name, before the hotkey. Default `"Notifications"`. */
552
+ containerAriaLabel?: string;
553
+ }
554
+
555
+ type Sides = Readonly<Record<"top" | "right" | "bottom" | "left", string>>;
556
+
557
+ function sidesOf(offset: Offset | undefined, fallback: string): Sides {
558
+ const unit = (value: string | number): string =>
559
+ typeof value === "number" ? `${value}px` : value;
560
+ if (typeof offset === "number" || typeof offset === "string") {
561
+ const all = unit(offset);
562
+ return { top: all, right: all, bottom: all, left: all };
563
+ }
564
+ return {
565
+ top: offset?.top === undefined ? fallback : unit(offset.top),
566
+ right: offset?.right === undefined ? fallback : unit(offset.right),
567
+ bottom: offset?.bottom === undefined ? fallback : unit(offset.bottom),
568
+ left: offset?.left === undefined ? fallback : unit(offset.left),
569
+ };
570
+ }
571
+
572
+ function axesOf(position: Position): {
573
+ y: "top" | "bottom";
574
+ x: "left" | "right" | "center";
575
+ } {
576
+ const [y, x] = position.split("-");
577
+ return {
578
+ y: y === "top" ? "top" : "bottom",
579
+ x: x === "left" ? "left" : x === "right" ? "right" : "center",
580
+ };
581
+ }
582
+
583
+ type ThemeMode = "light" | "dark" | "system";
584
+
585
+ /**
586
+ * Colour classes per theme, written out in full: Tailwind finds a class only
587
+ * where it appears whole in the source, so `dark:` cannot be prefixed at
588
+ * runtime. `system` defers to the app's `dark` variant.
589
+ */
590
+ interface Themed {
591
+ readonly light: string;
592
+ readonly dark: string;
593
+ readonly system: string;
594
+ }
595
+
596
+ /** sonner's rich colours, per type and theme. */
597
+ const RICH: Readonly<Record<"success" | "info" | "warning" | "error", Themed>> =
598
+ {
599
+ success: {
600
+ light:
601
+ "bg-[hsl(143,85%,96%)] border-[hsl(145,92%,87%)] text-[hsl(140,100%,27%)]",
602
+ dark: "bg-[hsl(150,100%,6%)] border-[hsl(147,100%,12%)] text-[hsl(150,86%,65%)]",
603
+ system:
604
+ "bg-[hsl(143,85%,96%)] border-[hsl(145,92%,87%)] text-[hsl(140,100%,27%)] dark:bg-[hsl(150,100%,6%)] dark:border-[hsl(147,100%,12%)] dark:text-[hsl(150,86%,65%)]",
605
+ },
606
+ info: {
607
+ light:
608
+ "bg-[hsl(208,100%,97%)] border-[hsl(221,91%,93%)] text-[hsl(210,92%,45%)]",
609
+ dark: "bg-[hsl(215,100%,6%)] border-[hsl(223,43%,17%)] text-[hsl(216,87%,65%)]",
610
+ system:
611
+ "bg-[hsl(208,100%,97%)] border-[hsl(221,91%,93%)] text-[hsl(210,92%,45%)] dark:bg-[hsl(215,100%,6%)] dark:border-[hsl(223,43%,17%)] dark:text-[hsl(216,87%,65%)]",
612
+ },
613
+ warning: {
614
+ light:
615
+ "bg-[hsl(49,100%,97%)] border-[hsl(49,91%,84%)] text-[hsl(31,92%,45%)]",
616
+ dark: "bg-[hsl(64,100%,6%)] border-[hsl(60,100%,9%)] text-[hsl(46,87%,65%)]",
617
+ system:
618
+ "bg-[hsl(49,100%,97%)] border-[hsl(49,91%,84%)] text-[hsl(31,92%,45%)] dark:bg-[hsl(64,100%,6%)] dark:border-[hsl(60,100%,9%)] dark:text-[hsl(46,87%,65%)]",
619
+ },
620
+ error: {
621
+ light:
622
+ "bg-[hsl(359,100%,97%)] border-[hsl(359,100%,94%)] text-[hsl(360,100%,45%)]",
623
+ dark: "bg-[hsl(358,76%,10%)] border-[hsl(357,89%,16%)] text-[hsl(358,100%,81%)]",
624
+ system:
625
+ "bg-[hsl(359,100%,97%)] border-[hsl(359,100%,94%)] text-[hsl(360,100%,45%)] dark:bg-[hsl(358,76%,10%)] dark:border-[hsl(357,89%,16%)] dark:text-[hsl(358,100%,81%)]",
626
+ },
627
+ };
628
+
629
+ /** shadcn's surface: the popover colours. */
630
+ const NORMAL = "bg-popover text-popover-foreground border-border";
631
+
632
+ /** sonner's `invert`: the opposite of the theme. */
633
+ const INVERT: Themed = {
634
+ light: "bg-black border-[hsl(0,0%,20%)] text-[hsl(0,0%,99%)]",
635
+ dark: "bg-white border-[hsl(0,0%,95.1%)] text-[hsl(0,0%,9%)]",
636
+ system:
637
+ "bg-black border-[hsl(0,0%,20%)] text-[hsl(0,0%,99%)] dark:bg-white dark:border-[hsl(0,0%,95.1%)] dark:text-[hsl(0,0%,9%)]",
638
+ };
639
+
640
+ const DESCRIPTION: Themed = {
641
+ light: "text-[#3f3f3f]",
642
+ dark: "text-[#e8e8e8]",
643
+ system: "text-[#3f3f3f] dark:text-[#e8e8e8]",
644
+ };
645
+
646
+ const CANCEL: Themed = {
647
+ light: "bg-black/8",
648
+ dark: "bg-white/30",
649
+ system: "bg-black/8 dark:bg-white/30",
650
+ };
651
+
652
+ const CLOSE_HOVER: Themed = {
653
+ light: "hover:bg-[hsl(0,0%,97.3%)] hover:border-[hsl(0,0%,90.9%)]",
654
+ dark: "hover:bg-[hsl(0,0%,12%)] hover:border-[hsl(0,0%,25%)]",
655
+ system:
656
+ "hover:bg-[hsl(0,0%,97.3%)] hover:border-[hsl(0,0%,90.9%)] dark:hover:bg-[hsl(0,0%,12%)] dark:hover:border-[hsl(0,0%,25%)]",
657
+ };
658
+
659
+ const TOAST_LAYOUT =
660
+ "absolute box-border outline-none touch-none [overflow-wrap:anywhere] transition-[transform,opacity,height,box-shadow] duration-400 motion-reduce:transition-none";
661
+
662
+ /** sonner's styled toast, with shadcn's colours in place of its own. */
663
+ const TOAST_STYLED =
664
+ "flex items-center gap-1.5 rounded-lg border p-4 text-[13px] shadow-[0_4px_12px_rgba(0,0,0,0.1)] focus-visible:shadow-[0_4px_12px_rgba(0,0,0,0.1),0_0_0_2px_rgba(0,0,0,0.2)] [&>*]:transition-opacity [&>*]:duration-400 data-[expanded=false]:data-[front=false]:[&>*]:opacity-0";
665
+
666
+ const BUTTON =
667
+ "ms-auto me-0 flex h-6 shrink-0 cursor-pointer items-center rounded-[4px] border-none px-2 text-xs font-medium outline-none transition-opacity focus-visible:shadow-[0_0_0_2px_rgba(0,0,0,0.4)]";
668
+
669
+ const CLOSE_BUTTON =
670
+ "absolute start-0 top-0 z-1 flex size-5 cursor-pointer items-center justify-center rounded-full border p-0 -translate-x-[35%] -translate-y-[35%] rtl:translate-x-[35%] transition-[opacity,background-color,border-color] focus-visible:shadow-[0_4px_12px_rgba(0,0,0,0.1),0_0_0_2px_rgba(0,0,0,0.2)]";
671
+
672
+ /** The icons shadcn hands to sonner. */
673
+ function defaultIcon(type: ToastType | undefined): Child {
674
+ switch (type) {
675
+ case "success":
676
+ return CircleCheckIcon({ class: "size-4" });
677
+ case "info":
678
+ return InfoIcon({ class: "size-4" });
679
+ case "warning":
680
+ return TriangleAlertIcon({ class: "size-4" });
681
+ case "error":
682
+ return OctagonXIcon({ class: "size-4" });
683
+ case "loading":
684
+ return LoaderIcon({ class: "size-4 animate-spin" });
685
+ default:
686
+ return null;
687
+ }
688
+ }
689
+
690
+ /** What one region shares with its rows. */
691
+ interface ToasterState {
692
+ readonly expanded: () => boolean;
693
+ /** Hovered, pressed, or the tab is hidden: timers hold. */
694
+ readonly paused: () => boolean;
695
+ readonly expandByDefault: boolean;
696
+ readonly gap: number;
697
+ readonly visibleToasts: number;
698
+ readonly duration: number | undefined;
699
+ readonly closeButton: boolean | undefined;
700
+ readonly richColors: boolean;
701
+ readonly invert: boolean;
702
+ readonly theme: ThemeMode;
703
+ readonly icons: ToastIcons | undefined;
704
+ readonly options: ToastOptions;
705
+ readonly narrow: () => boolean;
706
+ readonly mobile: Sides;
707
+ /** Measured heights, by row. */
708
+ readonly heights: () => ReadonlyMap<number, number>;
709
+ setHeight(serial: number, height: number | undefined): void;
710
+ announce(text: string, assertive: boolean): void;
711
+ }
712
+
713
+ interface Announcement {
714
+ readonly key: number;
715
+ readonly text: string;
716
+ }
717
+
718
+ /**
719
+ * Mount once, near the root of the app.
720
+ *
721
+ * `data-nebula-live` exempts it from the `aria-hidden` sweep a modal performs
722
+ * over its siblings: a toast raised while a dialog is open is still announced.
723
+ */
724
+ export const Toaster = component<ToasterProps>((props) => {
725
+ const position = props.position ?? "bottom-right";
726
+ const hotkey = props.hotkey ?? ["altKey", "KeyT"];
727
+ const hotkeyLabel = hotkey
728
+ .join("+")
729
+ .replace(/Key/g, "")
730
+ .replace(/Digit/g, "");
731
+ const label =
732
+ props.customAriaLabel ??
733
+ `${props.containerAriaLabel ?? "Notifications"} ${hotkeyLabel}`;
734
+ const offset = sidesOf(props.offset, VIEWPORT_OFFSET);
735
+ const mobile = sidesOf(props.mobileOffset, MOBILE_VIEWPORT_OFFSET);
736
+ const gap = props.gap ?? GAP;
737
+ const sectionId = uid("sonner");
738
+
739
+ const expanded = signal(false);
740
+ const interacting = signal(false);
741
+ const hidden = signal(false);
742
+ const narrow = signal(false);
743
+ const prefersDark = signal(false);
744
+ const heights = signal<ReadonlyMap<number, number>>(new Map());
745
+ const polite = signal<readonly Announcement[]>([]);
746
+ const assertive = signal<readonly Announcement[]>([]);
747
+ let announcements = 0;
748
+
749
+ /**
750
+ * Off until mounted, as sonner's list is state filled from an effect: the
751
+ * server's markup carries no toast, and adopting it renders none either,
752
+ * so the rows appear once the region is live.
753
+ */
754
+ const adopted = signal(false);
755
+
756
+ /** The toasts this region shows: its own `toasterId`, or none. */
757
+ const mine = (): readonly ToastRecord[] =>
758
+ (adopted() ? records() : []).filter((entry) =>
759
+ props.id === undefined
760
+ ? entry.toasterId === undefined
761
+ : entry.toasterId === props.id,
762
+ );
763
+
764
+ /** One list per corner in use, the region's own first. */
765
+ const positions = (): Position[] => [
766
+ ...new Set<Position>([
767
+ position,
768
+ ...mine().flatMap((entry) =>
769
+ entry.position === undefined ? [] : [entry.position],
770
+ ),
771
+ ]),
772
+ ];
773
+
774
+ const state: ToasterState = {
775
+ expanded,
776
+ paused: () => expanded() || interacting() || hidden(),
777
+ expandByDefault: props.expand ?? false,
778
+ gap,
779
+ visibleToasts: props.visibleToasts ?? VISIBLE_TOASTS_AMOUNT,
780
+ duration: props.toastOptions?.duration ?? props.duration,
781
+ closeButton: props.toastOptions?.closeButton ?? props.closeButton,
782
+ richColors: props.richColors ?? false,
783
+ invert: props.invert ?? false,
784
+ theme: props.theme ?? "system",
785
+ icons: props.icons,
786
+ options: props.toastOptions ?? {},
787
+ narrow,
788
+ mobile,
789
+ heights,
790
+ setHeight(serial, height) {
791
+ // Untracked: a row measures from its mount hook and from effects, and
792
+ // reading what it writes would make whichever runs it depend on it.
793
+ const current = untrack(() => heights());
794
+ if (current.get(serial) === height) return;
795
+ const next = new Map(current);
796
+ if (height === undefined) next.delete(serial);
797
+ else next.set(serial, height);
798
+ heights(next);
799
+ },
800
+ announce(text, isAssertive) {
801
+ if (text.trim() === "") return;
802
+ const region = isAssertive ? assertive : polite;
803
+ announcements += 1;
804
+ const entry: Announcement = { key: announcements, text };
805
+ region([...region(), entry]);
806
+ setTimeout(() => {
807
+ region(region().filter((candidate) => candidate !== entry));
808
+ }, ANNOUNCEMENT_LIFETIME);
809
+ },
810
+ };
811
+
812
+ onMount(() => {
813
+ adopted(true);
814
+ // A stack of one has nothing to fan out.
815
+ const stopCollapse = effect(() => {
816
+ if (mine().length <= 1) expanded(false);
817
+ });
818
+
819
+ const onKeyDown = (event: KeyboardEvent): void => {
820
+ const pressed =
821
+ hotkey.length > 0 &&
822
+ hotkey.every(
823
+ (key) => Reflect.get(event, key) === true || event.code === key,
824
+ );
825
+ const section = document.getElementById(sectionId);
826
+ if (pressed) {
827
+ expanded(true);
828
+ section?.querySelector<HTMLElement>("[data-sonner-toaster]")?.focus();
829
+ }
830
+ if (
831
+ event.code === "Escape" &&
832
+ section !== null &&
833
+ section.contains(document.activeElement)
834
+ ) {
835
+ expanded(false);
836
+ }
837
+ };
838
+ const onVisibility = (): void => {
839
+ hidden(document.hidden);
840
+ };
841
+ document.addEventListener("keydown", onKeyDown);
842
+ document.addEventListener("visibilitychange", onVisibility);
843
+ onVisibility();
844
+
845
+ const queries =
846
+ typeof window.matchMedia === "function"
847
+ ? {
848
+ narrow: window.matchMedia("(max-width: 600px)"),
849
+ dark: window.matchMedia("(prefers-color-scheme: dark)"),
850
+ }
851
+ : undefined;
852
+ const onNarrow = (): void => {
853
+ narrow(queries?.narrow.matches ?? false);
854
+ };
855
+ const onDark = (): void => {
856
+ prefersDark(queries?.dark.matches ?? false);
857
+ };
858
+ queries?.narrow.addEventListener("change", onNarrow);
859
+ queries?.dark.addEventListener("change", onDark);
860
+ onNarrow();
861
+ onDark();
862
+
863
+ return () => {
864
+ stopCollapse();
865
+ document.removeEventListener("keydown", onKeyDown);
866
+ document.removeEventListener("visibilitychange", onVisibility);
867
+ queries?.narrow.removeEventListener("change", onNarrow);
868
+ queries?.dark.removeEventListener("change", onDark);
869
+ };
870
+ });
871
+
872
+ const resolvedTheme = (): "light" | "dark" =>
873
+ state.theme === "system" ? (prefersDark() ? "dark" : "light") : state.theme;
874
+
875
+ /**
876
+ * The list's placement, bound as a `.style` property: the CSSOM is not
877
+ * subject to a Content-Security-Policy, where a `style` attribute is blocked
878
+ * by any policy without `'unsafe-inline'` — and the list then fell into the
879
+ * page flow. The server writes no property, so the list also carries `fixed`
880
+ * as a class: before hydration it is empty, and still out of the flow.
881
+ */
882
+ function listStyle(corner: Position): string {
883
+ const { x, y } = axesOf(corner);
884
+ const rules = [
885
+ "position:fixed",
886
+ "z-index:999999999",
887
+ `width:${narrow() ? "100%" : `${TOAST_WIDTH}px`}`,
888
+ ];
889
+ if (narrow()) {
890
+ rules.push(
891
+ `${y}:${mobile[y]}`,
892
+ `left:${mobile.left}`,
893
+ `right:${mobile.right}`,
894
+ );
895
+ } else {
896
+ rules.push(`${y}:${offset[y]}`);
897
+ if (x === "center") rules.push("left:50%", "transform:translateX(-50%)");
898
+ else rules.push(`${x}:${offset[x]}`);
899
+ }
900
+ return rules.join(";");
901
+ }
902
+
903
+ function renderList(
904
+ corner: ReadSignal<Position>,
905
+ index: ReadSignal<number>,
906
+ ): Child {
907
+ const toasts = (): readonly ToastRecord[] =>
908
+ mine().filter((entry) =>
909
+ entry.position === undefined
910
+ ? index() === 0
911
+ : entry.position === corner(),
912
+ );
913
+ return html`<ol
914
+ data-sonner-toaster
915
+ data-sonner-theme="${resolvedTheme}"
916
+ data-y-position="${() => axesOf(corner()).y}"
917
+ data-x-position="${() => axesOf(corner()).x}"
918
+ dir="${props.dir === "auto" ? undefined : props.dir}"
919
+ tabindex="-1"
920
+ class="${() => cn("fixed z-[999999999] m-0 box-border list-none p-0 outline-none", read(props.class))}"
921
+ .style="${() => listStyle(corner())}"
922
+ @pointerenter="${() => expanded(true)}"
923
+ @pointermove="${() => expanded(true)}"
924
+ @pointerleave="${() => {
925
+ if (!interacting()) expanded(false);
926
+ }}"
927
+ @pointerdown="${(event: PointerEvent) => {
928
+ const target = event.target;
929
+ if (
930
+ target instanceof HTMLElement &&
931
+ target.dataset.dismissible === "false"
932
+ )
933
+ return;
934
+ interacting(true);
935
+ }}"
936
+ @pointerup="${() => interacting(false)}"
937
+ >${each(
938
+ toasts,
939
+ (entry) => entry.serial,
940
+ (entry, at) =>
941
+ ToastRow({ entry, index: at, toasts, corner: corner(), state }),
942
+ )}</ol>`;
943
+ }
944
+
945
+ return html`<section
946
+ id="${sectionId}"
947
+ data-slot="sonner"
948
+ data-nebula-live
949
+ aria-label="${label}"
950
+ tabindex="-1"
951
+ >
952
+ <div role="status" aria-live="polite" aria-atomic="false" class="sr-only">${each(
953
+ polite,
954
+ (entry) => entry.key,
955
+ (entry) => html`<p>${() => entry().text}</p>`,
956
+ )}</div>
957
+ <div role="alert" aria-live="assertive" aria-atomic="false" class="sr-only">${each(
958
+ assertive,
959
+ (entry) => entry.key,
960
+ (entry) => html`<p>${() => entry().text}</p>`,
961
+ )}</div>
962
+ ${each(positions, (corner) => corner, renderList)}
963
+ </section>`;
964
+ });
965
+
966
+ interface ToastRowProps {
967
+ entry: ReadSignal<ToastRecord>;
968
+ index: ReadSignal<number>;
969
+ /** The rows of the same list, newest first. */
970
+ toasts: () => readonly ToastRecord[];
971
+ corner: Position;
972
+ state: ToasterState;
973
+ }
974
+
975
+ /**
976
+ * One toast. A component so it has a lifetime: it measures itself once it is
977
+ * in the document, owns its timer, and announces what it says.
978
+ */
979
+ const ToastRow = component<ToastRowProps>((props) => {
980
+ const { state } = props;
981
+ const rowId = uid("sonner-toast");
982
+ const mounted = signal(false);
983
+ const initialHeight = signal(0);
984
+ /** Where it stood when it was dismissed, so its exit starts from there. */
985
+ let offsetBeforeRemove = 0;
986
+
987
+ const { x, y } = axesOf(props.corner);
988
+ const lift = y === "top" ? 1 : -1;
989
+ const record = props.entry;
990
+ const isFront = (): boolean => props.index() === 0;
991
+ const isVisible = (): boolean => props.index() + 1 <= state.visibleToasts;
992
+ const isExpanded = (): boolean =>
993
+ state.expanded() || (state.expandByDefault && mounted());
994
+ const styled = (): boolean =>
995
+ !(
996
+ record().custom !== undefined ||
997
+ record().unstyled === true ||
998
+ state.options.unstyled === true
999
+ );
1000
+ const rich = (): boolean => record().richColors ?? state.richColors;
1001
+ const inverted = (): boolean => record().invert === true || state.invert;
1002
+ const dismissible = (): boolean => record().dismissible !== false;
1003
+ const duration = (): number =>
1004
+ record().duration || state.duration || TOAST_LIFETIME;
1005
+
1006
+ /** Measured heights of the rows in front of this one, sonner's `offset`. */
1007
+ const offset = (): number => {
1008
+ const measured = state.heights();
1009
+ const ordered = props.toasts().flatMap((entry) => {
1010
+ const height = measured.get(entry.serial);
1011
+ return height === undefined ? [] : [{ serial: entry.serial, height }];
1012
+ });
1013
+ const heightIndex = ordered.findIndex(
1014
+ (entry) => entry.serial === record().serial,
1015
+ );
1016
+ if (heightIndex === -1) return offsetBeforeRemove;
1017
+ let before = 0;
1018
+ for (const entry of ordered.slice(0, heightIndex)) before += entry.height;
1019
+ return heightIndex * state.gap + before;
1020
+ };
1021
+
1022
+ const frontHeight = (): number => {
1023
+ const front = props.toasts()[0];
1024
+ return front === undefined ? 0 : (state.heights().get(front.serial) ?? 0);
1025
+ };
1026
+
1027
+ function style(): string {
1028
+ const rules = [
1029
+ `${y}:0`,
1030
+ `z-index:${props.toasts().length - props.index()}`,
1031
+ ];
1032
+ if (state.narrow()) {
1033
+ rules.push(
1034
+ "left:0",
1035
+ "right:0",
1036
+ `width:calc(100% - ${state.mobile.left} * 2)`,
1037
+ );
1038
+ } else {
1039
+ if (x !== "center") rules.push(`${x}:0`);
1040
+ rules.push(`width:${TOAST_WIDTH}px`);
1041
+ }
1042
+
1043
+ let transform: string;
1044
+ let opacity = 1;
1045
+ let height: string | undefined;
1046
+ if (record().removing) {
1047
+ opacity = 0;
1048
+ if (isFront()) transform = `translateY(${lift * -100}%)`;
1049
+ else if (isExpanded())
1050
+ transform = `translateY(calc(${lift * offsetBeforeRemove}px + ${lift * -100}%))`;
1051
+ else {
1052
+ transform = "translateY(40%)";
1053
+ rules.push("transition:transform .5s,opacity .2s");
1054
+ }
1055
+ } else if (!mounted()) {
1056
+ opacity = 0;
1057
+ transform = `translateY(${lift * -100}%)`;
1058
+ } else if (isExpanded()) {
1059
+ transform = `translateY(${lift * offset()}px)`;
1060
+ height = state.expandByDefault ? "auto" : `${initialHeight()}px`;
1061
+ } else if (isFront()) {
1062
+ transform = "translateY(0)";
1063
+ } else {
1064
+ const before = props.index();
1065
+ transform = `translateY(${lift * state.gap * before}px) scale(${1 - before * 0.05})`;
1066
+ height = `${frontHeight()}px`;
1067
+ }
1068
+ if (!isVisible()) {
1069
+ opacity = 0;
1070
+ rules.push("pointer-events:none");
1071
+ }
1072
+ rules.push(`transform:${transform}`, `opacity:${opacity}`);
1073
+ if (height !== undefined) rules.push(`height:${height}`);
1074
+ return rules.join(";");
1075
+ }
1076
+
1077
+ function element(): HTMLElement | null {
1078
+ return document.getElementById(rowId);
1079
+ }
1080
+
1081
+ /** The height the content asks for, whatever the stack has set. */
1082
+ function measure(): void {
1083
+ const node = element();
1084
+ if (node === null) return;
1085
+ const original = node.style.height;
1086
+ node.style.height = "auto";
1087
+ const height = node.getBoundingClientRect().height;
1088
+ node.style.height = original;
1089
+ initialHeight(height);
1090
+ state.setHeight(record().serial, height);
1091
+ }
1092
+
1093
+ /** What a screen reader is told: the title and the description, as text. */
1094
+ function spoken(): string {
1095
+ const node = element();
1096
+ if (node === null) return "";
1097
+ const parts = [
1098
+ node.querySelector("[data-title]")?.textContent ?? "",
1099
+ node.querySelector("[data-description]")?.textContent ?? "",
1100
+ ];
1101
+ return parts
1102
+ .map((part) => part.trim())
1103
+ .filter((part) => part !== "")
1104
+ .join(". ");
1105
+ }
1106
+
1107
+ onMount(() => {
1108
+ untrack(() => {
1109
+ measure();
1110
+ // Read after the first layout, so the entrance transitions from where
1111
+ // the toast was first painted rather than appearing in place.
1112
+ mounted(true);
1113
+ });
1114
+
1115
+ let lastSpoken = "";
1116
+ let lastType: ToastType | undefined;
1117
+ const stopContent = effect(() => {
1118
+ const current = record();
1119
+ // Tracked so an update re-measures and re-announces.
1120
+ read(current.title);
1121
+ read(current.description);
1122
+ if (current.removing) return;
1123
+ queueMicrotask(() => {
1124
+ measure();
1125
+ const text = spoken();
1126
+ if (text === lastSpoken && current.type === lastType) return;
1127
+ lastSpoken = text;
1128
+ lastType = current.type;
1129
+ state.announce(text, current.type === "error");
1130
+ });
1131
+ });
1132
+
1133
+ let timer: ReturnType<typeof setTimeout> | undefined;
1134
+ let startedAt = 0;
1135
+ let remaining = duration();
1136
+ let lastDuration = remaining;
1137
+ const clear = (): void => {
1138
+ if (timer !== undefined) clearTimeout(timer);
1139
+ timer = undefined;
1140
+ };
1141
+ const stopTimer = effect(() => {
1142
+ const current = record();
1143
+ const total = duration();
1144
+ if (total !== lastDuration) {
1145
+ remaining = total;
1146
+ lastDuration = total;
1147
+ }
1148
+ if (current.removing) {
1149
+ clear();
1150
+ // Untracked: this writes the heights the offset is read from.
1151
+ untrack(() => {
1152
+ offsetBeforeRemove = offset();
1153
+ state.setHeight(current.serial, undefined);
1154
+ });
1155
+ return;
1156
+ }
1157
+ if (current.type === "loading" || total === Number.POSITIVE_INFINITY) {
1158
+ clear();
1159
+ return;
1160
+ }
1161
+ if (state.paused()) {
1162
+ if (timer !== undefined) remaining -= Date.now() - startedAt;
1163
+ clear();
1164
+ return;
1165
+ }
1166
+ clear();
1167
+ startedAt = Date.now();
1168
+ timer = setTimeout(
1169
+ () => remove(current.id, "autoClose"),
1170
+ Math.max(remaining, 0),
1171
+ );
1172
+ });
1173
+
1174
+ return () => {
1175
+ stopContent();
1176
+ stopTimer();
1177
+ clear();
1178
+ };
1179
+ });
1180
+
1181
+ onUnmount(() => {
1182
+ state.setHeight(record().serial, undefined);
1183
+ });
1184
+
1185
+ const typeKey = (): ToastType => record().type ?? "default";
1186
+
1187
+ function surfaceClasses(): string {
1188
+ const current = record();
1189
+ const type = current.type;
1190
+ const classNames = state.options.classNames;
1191
+ const colours = !styled()
1192
+ ? undefined
1193
+ : inverted()
1194
+ ? INVERT[state.theme]
1195
+ : rich() &&
1196
+ type !== undefined &&
1197
+ type !== "default" &&
1198
+ type !== "loading"
1199
+ ? RICH[type][state.theme]
1200
+ : NORMAL;
1201
+ return cn(
1202
+ TOAST_LAYOUT,
1203
+ styled() ? TOAST_STYLED : undefined,
1204
+ colours,
1205
+ state.options.class,
1206
+ current.class,
1207
+ classNames?.toast,
1208
+ current.classNames?.toast,
1209
+ classNames?.[typeKey()],
1210
+ current.classNames?.[typeKey()],
1211
+ );
1212
+ }
1213
+
1214
+ function closeClasses(): string {
1215
+ const type = record().type;
1216
+ const colours =
1217
+ rich() && type !== undefined && type !== "default" && type !== "loading"
1218
+ ? RICH[type][state.theme]
1219
+ : cn(NORMAL, CLOSE_HOVER[state.theme]);
1220
+ return cn(
1221
+ CLOSE_BUTTON,
1222
+ colours,
1223
+ state.options.classNames?.closeButton,
1224
+ record().classNames?.closeButton,
1225
+ );
1226
+ }
1227
+
1228
+ function renderClose(): Child {
1229
+ const current = record();
1230
+ const show =
1231
+ (current.closeButton ?? state.closeButton) === true &&
1232
+ current.custom === undefined &&
1233
+ current.type !== "loading";
1234
+ if (!show) return null;
1235
+ return html`<button
1236
+ type="button"
1237
+ aria-label="${state.options.closeButtonAriaLabel ?? "Close toast"}"
1238
+ data-close-button
1239
+ data-disabled="${String(current.type === "loading")}"
1240
+ class="${closeClasses}"
1241
+ @click="${() => {
1242
+ if (dismissible()) remove(record().id, "dismiss");
1243
+ }}"
1244
+ >${state.icons?.close ?? XIcon({ class: "size-3" })}</button>`;
1245
+ }
1246
+
1247
+ function renderIcon(): Child {
1248
+ const current = record();
1249
+ if (current.icon === null) return null;
1250
+ const type = current.type;
1251
+ let icon: Child;
1252
+ if (current.icon !== undefined) icon = current.icon;
1253
+ else if (
1254
+ type !== undefined &&
1255
+ state.icons !== undefined &&
1256
+ type in state.icons
1257
+ ) {
1258
+ icon = type === "default" ? null : state.icons[type];
1259
+ } else icon = defaultIcon(type);
1260
+ if (icon === null || icon === undefined || icon === false) return null;
1261
+ return html`<div
1262
+ data-icon
1263
+ class="${cn(
1264
+ "relative flex size-4 shrink-0 items-center justify-start -ms-[3px] me-1",
1265
+ state.options.classNames?.icon,
1266
+ current.classNames?.icon,
1267
+ )}"
1268
+ >${icon}</div>`;
1269
+ }
1270
+
1271
+ function renderButton(kind: "cancel" | "action"): Child {
1272
+ const current = record();
1273
+ const action = kind === "cancel" ? current.cancel : current.action;
1274
+ if (action === undefined) return null;
1275
+ const classNames = state.options.classNames;
1276
+ const classes =
1277
+ kind === "cancel"
1278
+ ? cn(
1279
+ BUTTON,
1280
+ "text-popover-foreground",
1281
+ CANCEL[state.theme],
1282
+ classNames?.cancelButton,
1283
+ current.classNames?.cancelButton,
1284
+ )
1285
+ : cn(
1286
+ BUTTON,
1287
+ "bg-popover-foreground text-popover",
1288
+ classNames?.actionButton,
1289
+ current.classNames?.actionButton,
1290
+ );
1291
+ return html`<button
1292
+ type="button"
1293
+ data-button
1294
+ data-cancel="${kind === "cancel" ? "" : undefined}"
1295
+ data-action="${kind === "action" ? "" : undefined}"
1296
+ class="${classes}"
1297
+ @click="${(event: MouseEvent) => {
1298
+ if (kind === "cancel") {
1299
+ if (!dismissible()) return;
1300
+ action.onClick(event);
1301
+ remove(record().id, "silent");
1302
+ return;
1303
+ }
1304
+ action.onClick(event);
1305
+ if (event.defaultPrevented) return;
1306
+ remove(record().id, "silent");
1307
+ }}"
1308
+ >${action.label}</button>`;
1309
+ }
1310
+
1311
+ function renderDescription(): Child {
1312
+ const current = record();
1313
+ if (current.description === undefined) return null;
1314
+ return html`<div
1315
+ data-description
1316
+ class="${cn(
1317
+ "font-normal leading-[1.4]",
1318
+ rich() ? "text-inherit" : DESCRIPTION[state.theme],
1319
+ state.options.descriptionClass,
1320
+ current.descriptionClass,
1321
+ state.options.classNames?.description,
1322
+ current.classNames?.description,
1323
+ )}"
1324
+ >${read(current.description)}</div>`;
1325
+ }
1326
+
1327
+ return html`<li
1328
+ id="${rowId}"
1329
+ tabindex="0"
1330
+ data-slot="sonner-toast"
1331
+ data-sonner-toast
1332
+ data-type="${() => record().type}"
1333
+ data-rich-colors="${() => String(rich())}"
1334
+ data-styled="${() => String(styled())}"
1335
+ data-mounted="${() => String(mounted())}"
1336
+ data-promise="${() => String(record().promise === true)}"
1337
+ data-removed="${() => String(record().removing)}"
1338
+ data-visible="${() => String(isVisible())}"
1339
+ data-y-position="${y}"
1340
+ data-x-position="${x}"
1341
+ data-index="${() => String(props.index())}"
1342
+ data-front="${() => String(isFront())}"
1343
+ data-dismissible="${() => String(dismissible())}"
1344
+ data-invert="${() => String(inverted())}"
1345
+ data-expanded="${() => String(isExpanded())}"
1346
+ data-testid="${() => record().testId}"
1347
+ class="${surfaceClasses}"
1348
+ .style="${style}"
1349
+ >${renderClose}${renderIcon}<div
1350
+ data-content
1351
+ class="${() =>
1352
+ cn(
1353
+ "flex min-w-0 flex-1 flex-col gap-0.5",
1354
+ state.options.classNames?.content,
1355
+ record().classNames?.content,
1356
+ )}"
1357
+ ><div
1358
+ data-title
1359
+ class="${() =>
1360
+ cn(
1361
+ "font-medium leading-normal",
1362
+ state.options.classNames?.title,
1363
+ record().classNames?.title,
1364
+ )}"
1365
+ >${() => record().custom ?? read(record().title)}</div>${renderDescription}</div>${() => renderButton("cancel")}${() => renderButton("action")}${() =>
1366
+ isExpanded() && !record().removing
1367
+ ? html`<span
1368
+ aria-hidden="true"
1369
+ class="absolute left-0 bottom-full w-full"
1370
+ .style="${`height:${state.gap + 1}px`}"
1371
+ ></span>`
1372
+ : null}</li>`;
1373
+ });