@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,916 @@
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
+ import { component, each, effect, html, isEach, isTemplateResult, onMount, onUnmount, signal, uid, untrack, } from "@c9up/aurora";
54
+ import { cn } from "../lib/cn.js";
55
+ import { CircleCheckIcon, InfoIcon, LoaderIcon, OctagonXIcon, TriangleAlertIcon, XIcon, } from "../lib/icons.js";
56
+ import { read } from "../lib/props.js";
57
+ // ─── State ───────────────────────────────────────────────────────────
58
+ /** sonner's defaults, as its source declares them. */
59
+ const VISIBLE_TOASTS_AMOUNT = 3;
60
+ const VIEWPORT_OFFSET = "24px";
61
+ const MOBILE_VIEWPORT_OFFSET = "16px";
62
+ const TOAST_LIFETIME = 4000;
63
+ const TOAST_WIDTH = 356;
64
+ const GAP = 14;
65
+ const TIME_BEFORE_UNMOUNT = 200;
66
+ /** How long an announcement stays in its live region once read. */
67
+ const ANNOUNCEMENT_LIFETIME = 7000;
68
+ /** Newest first, as sonner stacks them. */
69
+ const records = signal([]);
70
+ let counter = 1;
71
+ let serials = 0;
72
+ function idFor(data) {
73
+ if (typeof data.id === "number")
74
+ return data.id;
75
+ if (typeof data.id === "string" && data.id.length > 0)
76
+ return data.id;
77
+ const id = counter;
78
+ counter += 1;
79
+ return id;
80
+ }
81
+ /**
82
+ * No document: this is the server, rendering a page for one request in a
83
+ * process that renders everyone's. A toast kept here would reach the next
84
+ * user's markup and never leave, its timer belonging to a mounted row.
85
+ */
86
+ function onServer() {
87
+ return typeof document === "undefined";
88
+ }
89
+ function create(data) {
90
+ const id = idFor(data);
91
+ // The page code that raised it runs again in the browser, where it is kept.
92
+ if (onServer())
93
+ return id;
94
+ const list = records();
95
+ const existing = list.find((entry) => entry.id === id && !entry.removing);
96
+ if (existing !== undefined) {
97
+ records(list.map((entry) => entry === existing ? { ...entry, ...data, id } : entry));
98
+ return id;
99
+ }
100
+ // One still leaving under the same id is gone: this is a new toast, not
101
+ // a merge, or its old `action` would leak into the new one.
102
+ serials += 1;
103
+ const fresh = { ...data, id, serial: serials, removing: false };
104
+ records([fresh, ...list.filter((entry) => entry.id !== id)]);
105
+ return id;
106
+ }
107
+ /**
108
+ * Run an application callback without letting it take the caller down: they
109
+ * run from a timer, a click and `dismiss()` alike, and one that throws would
110
+ * leave the list half-updated.
111
+ */
112
+ function notify(callback, toast) {
113
+ if (callback === undefined)
114
+ return;
115
+ try {
116
+ callback(toast);
117
+ }
118
+ catch (error) {
119
+ console.error("[nebula] a toast callback threw", error);
120
+ }
121
+ }
122
+ /**
123
+ * Start a toast's exit, and drop it once the exit has played.
124
+ *
125
+ * The drop is scheduled here, not by the region, so a toast dismissed while
126
+ * no `Toaster` is mounted still leaves.
127
+ */
128
+ function remove(id, reason) {
129
+ const target = records().find((entry) => entry.id === id && !entry.removing);
130
+ if (target === undefined)
131
+ return;
132
+ records(records().map((entry) => entry === target ? { ...entry, removing: true } : entry));
133
+ if (reason === "dismiss")
134
+ notify(target.onDismiss, target);
135
+ if (reason === "autoClose")
136
+ notify(target.onAutoClose, target);
137
+ setTimeout(() => {
138
+ records(records().filter((entry) => entry.serial !== target.serial));
139
+ }, TIME_BEFORE_UNMOUNT);
140
+ }
141
+ function dismiss(id) {
142
+ if (id === undefined) {
143
+ for (const entry of records()) {
144
+ if (!entry.removing)
145
+ remove(entry.id, "dismiss");
146
+ }
147
+ return id;
148
+ }
149
+ remove(id, "dismiss");
150
+ return id;
151
+ }
152
+ function isNodeLike(value) {
153
+ return typeof Node !== "undefined" && value instanceof Node;
154
+ }
155
+ /** A stage that carries options, rather than a message to show. */
156
+ function isExtendedResult(value) {
157
+ return (typeof value === "object" &&
158
+ value !== null &&
159
+ !Array.isArray(value) &&
160
+ !isTemplateResult(value) &&
161
+ !isNodeLike(value) &&
162
+ "message" in value);
163
+ }
164
+ function isHttpResponse(value) {
165
+ return (typeof value === "object" &&
166
+ value !== null &&
167
+ "ok" in value &&
168
+ typeof value.ok === "boolean" &&
169
+ "status" in value &&
170
+ typeof value.status === "number");
171
+ }
172
+ async function stageValue(stage, value) {
173
+ const result = typeof stage === "function" && !isEach(stage) ? await stage(value) : stage;
174
+ return isExtendedResult(result) ? result : { message: result };
175
+ }
176
+ function promise(work, data) {
177
+ const run = Promise.resolve(typeof work === "function" ? work() : work);
178
+ if (data === undefined)
179
+ return { id: undefined, unwrap: () => run };
180
+ const { loading, success, error, description, finally: onFinally, ...options } = data;
181
+ let id;
182
+ if (loading !== undefined) {
183
+ id = create({
184
+ ...options,
185
+ promise: true,
186
+ type: "loading",
187
+ title: loading,
188
+ description: typeof description === "function" && !isEach(description)
189
+ ? undefined
190
+ : description,
191
+ });
192
+ }
193
+ async function settle(type, stage, value) {
194
+ const { message, ...settings } = await stageValue(stage, value);
195
+ const text = typeof description === "function" && !isEach(description)
196
+ ? await description(value)
197
+ : description;
198
+ create({
199
+ ...options,
200
+ id,
201
+ type,
202
+ description: text,
203
+ ...settings,
204
+ title: message,
205
+ });
206
+ }
207
+ // The loading toast stays only while nothing has replaced it.
208
+ let shouldDismiss = id !== undefined;
209
+ let outcome;
210
+ const done = run
211
+ .then(async (response) => {
212
+ outcome = { ok: true, value: response };
213
+ if (isHttpResponse(response) && !response.ok) {
214
+ shouldDismiss = false;
215
+ if (error !== undefined) {
216
+ await settle("error", error, `HTTP error! status: ${response.status}`);
217
+ }
218
+ }
219
+ else if (response instanceof Error) {
220
+ shouldDismiss = false;
221
+ if (error !== undefined)
222
+ await settle("error", error, response);
223
+ }
224
+ else if (success !== undefined) {
225
+ shouldDismiss = false;
226
+ await settle("success", success, response);
227
+ }
228
+ })
229
+ .catch(async (reason) => {
230
+ outcome = { ok: false, reason };
231
+ if (error !== undefined) {
232
+ shouldDismiss = false;
233
+ await settle("error", error, reason);
234
+ }
235
+ })
236
+ .finally(() => {
237
+ if (shouldDismiss && id !== undefined)
238
+ dismiss(id);
239
+ return onFinally?.();
240
+ });
241
+ return {
242
+ id,
243
+ unwrap: () => done.then(() => {
244
+ if (outcome?.ok === true)
245
+ return outcome.value;
246
+ return Promise.reject(outcome?.ok === false ? outcome.reason : undefined);
247
+ }),
248
+ };
249
+ }
250
+ function typed(type) {
251
+ return (message, data) => create({ ...data, title: message, type });
252
+ }
253
+ /**
254
+ * Raise a toast. Returns its id, which `toast.dismiss` takes.
255
+ *
256
+ * Callable from anywhere — no component, no context, no handle.
257
+ */
258
+ export const toast = Object.assign(typed(undefined), {
259
+ /** A plain toast; on an existing id, resets its type. */
260
+ message: typed(undefined),
261
+ success: typed("success"),
262
+ info: typed("info"),
263
+ warning: typed("warning"),
264
+ error: typed("error"),
265
+ /** Stays until it is updated or dismissed. */
266
+ loading: typed("loading"),
267
+ /** Render your own content, unstyled; `render` gets the toast's id. */
268
+ custom(render, data) {
269
+ const id = idFor(data ?? {});
270
+ return create({ ...data, id, custom: render(id), type: undefined });
271
+ },
272
+ /**
273
+ * One toast for the whole life of an async call: loading, then its outcome.
274
+ *
275
+ * A rejection is reported, not swallowed: `unwrap()` hands it back to the
276
+ * caller's own error path.
277
+ */
278
+ promise,
279
+ /** Dismiss one toast, or every toast when no id is given. */
280
+ dismiss,
281
+ /** The toasts on screen, newest first. */
282
+ getToasts() {
283
+ return records().filter((entry) => !entry.removing);
284
+ },
285
+ });
286
+ function sidesOf(offset, fallback) {
287
+ const unit = (value) => typeof value === "number" ? `${value}px` : value;
288
+ if (typeof offset === "number" || typeof offset === "string") {
289
+ const all = unit(offset);
290
+ return { top: all, right: all, bottom: all, left: all };
291
+ }
292
+ return {
293
+ top: offset?.top === undefined ? fallback : unit(offset.top),
294
+ right: offset?.right === undefined ? fallback : unit(offset.right),
295
+ bottom: offset?.bottom === undefined ? fallback : unit(offset.bottom),
296
+ left: offset?.left === undefined ? fallback : unit(offset.left),
297
+ };
298
+ }
299
+ function axesOf(position) {
300
+ const [y, x] = position.split("-");
301
+ return {
302
+ y: y === "top" ? "top" : "bottom",
303
+ x: x === "left" ? "left" : x === "right" ? "right" : "center",
304
+ };
305
+ }
306
+ /** sonner's rich colours, per type and theme. */
307
+ const RICH = {
308
+ success: {
309
+ light: "bg-[hsl(143,85%,96%)] border-[hsl(145,92%,87%)] text-[hsl(140,100%,27%)]",
310
+ dark: "bg-[hsl(150,100%,6%)] border-[hsl(147,100%,12%)] text-[hsl(150,86%,65%)]",
311
+ system: "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%)]",
312
+ },
313
+ info: {
314
+ light: "bg-[hsl(208,100%,97%)] border-[hsl(221,91%,93%)] text-[hsl(210,92%,45%)]",
315
+ dark: "bg-[hsl(215,100%,6%)] border-[hsl(223,43%,17%)] text-[hsl(216,87%,65%)]",
316
+ system: "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%)]",
317
+ },
318
+ warning: {
319
+ light: "bg-[hsl(49,100%,97%)] border-[hsl(49,91%,84%)] text-[hsl(31,92%,45%)]",
320
+ dark: "bg-[hsl(64,100%,6%)] border-[hsl(60,100%,9%)] text-[hsl(46,87%,65%)]",
321
+ system: "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%)]",
322
+ },
323
+ error: {
324
+ light: "bg-[hsl(359,100%,97%)] border-[hsl(359,100%,94%)] text-[hsl(360,100%,45%)]",
325
+ dark: "bg-[hsl(358,76%,10%)] border-[hsl(357,89%,16%)] text-[hsl(358,100%,81%)]",
326
+ system: "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%)]",
327
+ },
328
+ };
329
+ /** shadcn's surface: the popover colours. */
330
+ const NORMAL = "bg-popover text-popover-foreground border-border";
331
+ /** sonner's `invert`: the opposite of the theme. */
332
+ const INVERT = {
333
+ light: "bg-black border-[hsl(0,0%,20%)] text-[hsl(0,0%,99%)]",
334
+ dark: "bg-white border-[hsl(0,0%,95.1%)] text-[hsl(0,0%,9%)]",
335
+ system: "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%)]",
336
+ };
337
+ const DESCRIPTION = {
338
+ light: "text-[#3f3f3f]",
339
+ dark: "text-[#e8e8e8]",
340
+ system: "text-[#3f3f3f] dark:text-[#e8e8e8]",
341
+ };
342
+ const CANCEL = {
343
+ light: "bg-black/8",
344
+ dark: "bg-white/30",
345
+ system: "bg-black/8 dark:bg-white/30",
346
+ };
347
+ const CLOSE_HOVER = {
348
+ light: "hover:bg-[hsl(0,0%,97.3%)] hover:border-[hsl(0,0%,90.9%)]",
349
+ dark: "hover:bg-[hsl(0,0%,12%)] hover:border-[hsl(0,0%,25%)]",
350
+ system: "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%)]",
351
+ };
352
+ const TOAST_LAYOUT = "absolute box-border outline-none touch-none [overflow-wrap:anywhere] transition-[transform,opacity,height,box-shadow] duration-400 motion-reduce:transition-none";
353
+ /** sonner's styled toast, with shadcn's colours in place of its own. */
354
+ const TOAST_STYLED = "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";
355
+ const BUTTON = "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)]";
356
+ const CLOSE_BUTTON = "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)]";
357
+ /** The icons shadcn hands to sonner. */
358
+ function defaultIcon(type) {
359
+ switch (type) {
360
+ case "success":
361
+ return CircleCheckIcon({ class: "size-4" });
362
+ case "info":
363
+ return InfoIcon({ class: "size-4" });
364
+ case "warning":
365
+ return TriangleAlertIcon({ class: "size-4" });
366
+ case "error":
367
+ return OctagonXIcon({ class: "size-4" });
368
+ case "loading":
369
+ return LoaderIcon({ class: "size-4 animate-spin" });
370
+ default:
371
+ return null;
372
+ }
373
+ }
374
+ /**
375
+ * Mount once, near the root of the app.
376
+ *
377
+ * `data-nebula-live` exempts it from the `aria-hidden` sweep a modal performs
378
+ * over its siblings: a toast raised while a dialog is open is still announced.
379
+ */
380
+ export const Toaster = component((props) => {
381
+ const position = props.position ?? "bottom-right";
382
+ const hotkey = props.hotkey ?? ["altKey", "KeyT"];
383
+ const hotkeyLabel = hotkey
384
+ .join("+")
385
+ .replace(/Key/g, "")
386
+ .replace(/Digit/g, "");
387
+ const label = props.customAriaLabel ??
388
+ `${props.containerAriaLabel ?? "Notifications"} ${hotkeyLabel}`;
389
+ const offset = sidesOf(props.offset, VIEWPORT_OFFSET);
390
+ const mobile = sidesOf(props.mobileOffset, MOBILE_VIEWPORT_OFFSET);
391
+ const gap = props.gap ?? GAP;
392
+ const sectionId = uid("sonner");
393
+ const expanded = signal(false);
394
+ const interacting = signal(false);
395
+ const hidden = signal(false);
396
+ const narrow = signal(false);
397
+ const prefersDark = signal(false);
398
+ const heights = signal(new Map());
399
+ const polite = signal([]);
400
+ const assertive = signal([]);
401
+ let announcements = 0;
402
+ /**
403
+ * Off until mounted, as sonner's list is state filled from an effect: the
404
+ * server's markup carries no toast, and adopting it renders none either,
405
+ * so the rows appear once the region is live.
406
+ */
407
+ const adopted = signal(false);
408
+ /** The toasts this region shows: its own `toasterId`, or none. */
409
+ const mine = () => (adopted() ? records() : []).filter((entry) => props.id === undefined
410
+ ? entry.toasterId === undefined
411
+ : entry.toasterId === props.id);
412
+ /** One list per corner in use, the region's own first. */
413
+ const positions = () => [
414
+ ...new Set([
415
+ position,
416
+ ...mine().flatMap((entry) => entry.position === undefined ? [] : [entry.position]),
417
+ ]),
418
+ ];
419
+ const state = {
420
+ expanded,
421
+ paused: () => expanded() || interacting() || hidden(),
422
+ expandByDefault: props.expand ?? false,
423
+ gap,
424
+ visibleToasts: props.visibleToasts ?? VISIBLE_TOASTS_AMOUNT,
425
+ duration: props.toastOptions?.duration ?? props.duration,
426
+ closeButton: props.toastOptions?.closeButton ?? props.closeButton,
427
+ richColors: props.richColors ?? false,
428
+ invert: props.invert ?? false,
429
+ theme: props.theme ?? "system",
430
+ icons: props.icons,
431
+ options: props.toastOptions ?? {},
432
+ narrow,
433
+ mobile,
434
+ heights,
435
+ setHeight(serial, height) {
436
+ // Untracked: a row measures from its mount hook and from effects, and
437
+ // reading what it writes would make whichever runs it depend on it.
438
+ const current = untrack(() => heights());
439
+ if (current.get(serial) === height)
440
+ return;
441
+ const next = new Map(current);
442
+ if (height === undefined)
443
+ next.delete(serial);
444
+ else
445
+ next.set(serial, height);
446
+ heights(next);
447
+ },
448
+ announce(text, isAssertive) {
449
+ if (text.trim() === "")
450
+ return;
451
+ const region = isAssertive ? assertive : polite;
452
+ announcements += 1;
453
+ const entry = { key: announcements, text };
454
+ region([...region(), entry]);
455
+ setTimeout(() => {
456
+ region(region().filter((candidate) => candidate !== entry));
457
+ }, ANNOUNCEMENT_LIFETIME);
458
+ },
459
+ };
460
+ onMount(() => {
461
+ adopted(true);
462
+ // A stack of one has nothing to fan out.
463
+ const stopCollapse = effect(() => {
464
+ if (mine().length <= 1)
465
+ expanded(false);
466
+ });
467
+ const onKeyDown = (event) => {
468
+ const pressed = hotkey.length > 0 &&
469
+ hotkey.every((key) => Reflect.get(event, key) === true || event.code === key);
470
+ const section = document.getElementById(sectionId);
471
+ if (pressed) {
472
+ expanded(true);
473
+ section?.querySelector("[data-sonner-toaster]")?.focus();
474
+ }
475
+ if (event.code === "Escape" &&
476
+ section !== null &&
477
+ section.contains(document.activeElement)) {
478
+ expanded(false);
479
+ }
480
+ };
481
+ const onVisibility = () => {
482
+ hidden(document.hidden);
483
+ };
484
+ document.addEventListener("keydown", onKeyDown);
485
+ document.addEventListener("visibilitychange", onVisibility);
486
+ onVisibility();
487
+ const queries = typeof window.matchMedia === "function"
488
+ ? {
489
+ narrow: window.matchMedia("(max-width: 600px)"),
490
+ dark: window.matchMedia("(prefers-color-scheme: dark)"),
491
+ }
492
+ : undefined;
493
+ const onNarrow = () => {
494
+ narrow(queries?.narrow.matches ?? false);
495
+ };
496
+ const onDark = () => {
497
+ prefersDark(queries?.dark.matches ?? false);
498
+ };
499
+ queries?.narrow.addEventListener("change", onNarrow);
500
+ queries?.dark.addEventListener("change", onDark);
501
+ onNarrow();
502
+ onDark();
503
+ return () => {
504
+ stopCollapse();
505
+ document.removeEventListener("keydown", onKeyDown);
506
+ document.removeEventListener("visibilitychange", onVisibility);
507
+ queries?.narrow.removeEventListener("change", onNarrow);
508
+ queries?.dark.removeEventListener("change", onDark);
509
+ };
510
+ });
511
+ const resolvedTheme = () => state.theme === "system" ? (prefersDark() ? "dark" : "light") : state.theme;
512
+ /**
513
+ * The list's placement, bound as a `.style` property: the CSSOM is not
514
+ * subject to a Content-Security-Policy, where a `style` attribute is blocked
515
+ * by any policy without `'unsafe-inline'` — and the list then fell into the
516
+ * page flow. The server writes no property, so the list also carries `fixed`
517
+ * as a class: before hydration it is empty, and still out of the flow.
518
+ */
519
+ function listStyle(corner) {
520
+ const { x, y } = axesOf(corner);
521
+ const rules = [
522
+ "position:fixed",
523
+ "z-index:999999999",
524
+ `width:${narrow() ? "100%" : `${TOAST_WIDTH}px`}`,
525
+ ];
526
+ if (narrow()) {
527
+ rules.push(`${y}:${mobile[y]}`, `left:${mobile.left}`, `right:${mobile.right}`);
528
+ }
529
+ else {
530
+ rules.push(`${y}:${offset[y]}`);
531
+ if (x === "center")
532
+ rules.push("left:50%", "transform:translateX(-50%)");
533
+ else
534
+ rules.push(`${x}:${offset[x]}`);
535
+ }
536
+ return rules.join(";");
537
+ }
538
+ function renderList(corner, index) {
539
+ const toasts = () => mine().filter((entry) => entry.position === undefined
540
+ ? index() === 0
541
+ : entry.position === corner());
542
+ return html `<ol
543
+ data-sonner-toaster
544
+ data-sonner-theme="${resolvedTheme}"
545
+ data-y-position="${() => axesOf(corner()).y}"
546
+ data-x-position="${() => axesOf(corner()).x}"
547
+ dir="${props.dir === "auto" ? undefined : props.dir}"
548
+ tabindex="-1"
549
+ class="${() => cn("fixed z-[999999999] m-0 box-border list-none p-0 outline-none", read(props.class))}"
550
+ .style="${() => listStyle(corner())}"
551
+ @pointerenter="${() => expanded(true)}"
552
+ @pointermove="${() => expanded(true)}"
553
+ @pointerleave="${() => {
554
+ if (!interacting())
555
+ expanded(false);
556
+ }}"
557
+ @pointerdown="${(event) => {
558
+ const target = event.target;
559
+ if (target instanceof HTMLElement &&
560
+ target.dataset.dismissible === "false")
561
+ return;
562
+ interacting(true);
563
+ }}"
564
+ @pointerup="${() => interacting(false)}"
565
+ >${each(toasts, (entry) => entry.serial, (entry, at) => ToastRow({ entry, index: at, toasts, corner: corner(), state }))}</ol>`;
566
+ }
567
+ return html `<section
568
+ id="${sectionId}"
569
+ data-slot="sonner"
570
+ data-nebula-live
571
+ aria-label="${label}"
572
+ tabindex="-1"
573
+ >
574
+ <div role="status" aria-live="polite" aria-atomic="false" class="sr-only">${each(polite, (entry) => entry.key, (entry) => html `<p>${() => entry().text}</p>`)}</div>
575
+ <div role="alert" aria-live="assertive" aria-atomic="false" class="sr-only">${each(assertive, (entry) => entry.key, (entry) => html `<p>${() => entry().text}</p>`)}</div>
576
+ ${each(positions, (corner) => corner, renderList)}
577
+ </section>`;
578
+ });
579
+ /**
580
+ * One toast. A component so it has a lifetime: it measures itself once it is
581
+ * in the document, owns its timer, and announces what it says.
582
+ */
583
+ const ToastRow = component((props) => {
584
+ const { state } = props;
585
+ const rowId = uid("sonner-toast");
586
+ const mounted = signal(false);
587
+ const initialHeight = signal(0);
588
+ /** Where it stood when it was dismissed, so its exit starts from there. */
589
+ let offsetBeforeRemove = 0;
590
+ const { x, y } = axesOf(props.corner);
591
+ const lift = y === "top" ? 1 : -1;
592
+ const record = props.entry;
593
+ const isFront = () => props.index() === 0;
594
+ const isVisible = () => props.index() + 1 <= state.visibleToasts;
595
+ const isExpanded = () => state.expanded() || (state.expandByDefault && mounted());
596
+ const styled = () => !(record().custom !== undefined ||
597
+ record().unstyled === true ||
598
+ state.options.unstyled === true);
599
+ const rich = () => record().richColors ?? state.richColors;
600
+ const inverted = () => record().invert === true || state.invert;
601
+ const dismissible = () => record().dismissible !== false;
602
+ const duration = () => record().duration || state.duration || TOAST_LIFETIME;
603
+ /** Measured heights of the rows in front of this one, sonner's `offset`. */
604
+ const offset = () => {
605
+ const measured = state.heights();
606
+ const ordered = props.toasts().flatMap((entry) => {
607
+ const height = measured.get(entry.serial);
608
+ return height === undefined ? [] : [{ serial: entry.serial, height }];
609
+ });
610
+ const heightIndex = ordered.findIndex((entry) => entry.serial === record().serial);
611
+ if (heightIndex === -1)
612
+ return offsetBeforeRemove;
613
+ let before = 0;
614
+ for (const entry of ordered.slice(0, heightIndex))
615
+ before += entry.height;
616
+ return heightIndex * state.gap + before;
617
+ };
618
+ const frontHeight = () => {
619
+ const front = props.toasts()[0];
620
+ return front === undefined ? 0 : (state.heights().get(front.serial) ?? 0);
621
+ };
622
+ function style() {
623
+ const rules = [
624
+ `${y}:0`,
625
+ `z-index:${props.toasts().length - props.index()}`,
626
+ ];
627
+ if (state.narrow()) {
628
+ rules.push("left:0", "right:0", `width:calc(100% - ${state.mobile.left} * 2)`);
629
+ }
630
+ else {
631
+ if (x !== "center")
632
+ rules.push(`${x}:0`);
633
+ rules.push(`width:${TOAST_WIDTH}px`);
634
+ }
635
+ let transform;
636
+ let opacity = 1;
637
+ let height;
638
+ if (record().removing) {
639
+ opacity = 0;
640
+ if (isFront())
641
+ transform = `translateY(${lift * -100}%)`;
642
+ else if (isExpanded())
643
+ transform = `translateY(calc(${lift * offsetBeforeRemove}px + ${lift * -100}%))`;
644
+ else {
645
+ transform = "translateY(40%)";
646
+ rules.push("transition:transform .5s,opacity .2s");
647
+ }
648
+ }
649
+ else if (!mounted()) {
650
+ opacity = 0;
651
+ transform = `translateY(${lift * -100}%)`;
652
+ }
653
+ else if (isExpanded()) {
654
+ transform = `translateY(${lift * offset()}px)`;
655
+ height = state.expandByDefault ? "auto" : `${initialHeight()}px`;
656
+ }
657
+ else if (isFront()) {
658
+ transform = "translateY(0)";
659
+ }
660
+ else {
661
+ const before = props.index();
662
+ transform = `translateY(${lift * state.gap * before}px) scale(${1 - before * 0.05})`;
663
+ height = `${frontHeight()}px`;
664
+ }
665
+ if (!isVisible()) {
666
+ opacity = 0;
667
+ rules.push("pointer-events:none");
668
+ }
669
+ rules.push(`transform:${transform}`, `opacity:${opacity}`);
670
+ if (height !== undefined)
671
+ rules.push(`height:${height}`);
672
+ return rules.join(";");
673
+ }
674
+ function element() {
675
+ return document.getElementById(rowId);
676
+ }
677
+ /** The height the content asks for, whatever the stack has set. */
678
+ function measure() {
679
+ const node = element();
680
+ if (node === null)
681
+ return;
682
+ const original = node.style.height;
683
+ node.style.height = "auto";
684
+ const height = node.getBoundingClientRect().height;
685
+ node.style.height = original;
686
+ initialHeight(height);
687
+ state.setHeight(record().serial, height);
688
+ }
689
+ /** What a screen reader is told: the title and the description, as text. */
690
+ function spoken() {
691
+ const node = element();
692
+ if (node === null)
693
+ return "";
694
+ const parts = [
695
+ node.querySelector("[data-title]")?.textContent ?? "",
696
+ node.querySelector("[data-description]")?.textContent ?? "",
697
+ ];
698
+ return parts
699
+ .map((part) => part.trim())
700
+ .filter((part) => part !== "")
701
+ .join(". ");
702
+ }
703
+ onMount(() => {
704
+ untrack(() => {
705
+ measure();
706
+ // Read after the first layout, so the entrance transitions from where
707
+ // the toast was first painted rather than appearing in place.
708
+ mounted(true);
709
+ });
710
+ let lastSpoken = "";
711
+ let lastType;
712
+ const stopContent = effect(() => {
713
+ const current = record();
714
+ // Tracked so an update re-measures and re-announces.
715
+ read(current.title);
716
+ read(current.description);
717
+ if (current.removing)
718
+ return;
719
+ queueMicrotask(() => {
720
+ measure();
721
+ const text = spoken();
722
+ if (text === lastSpoken && current.type === lastType)
723
+ return;
724
+ lastSpoken = text;
725
+ lastType = current.type;
726
+ state.announce(text, current.type === "error");
727
+ });
728
+ });
729
+ let timer;
730
+ let startedAt = 0;
731
+ let remaining = duration();
732
+ let lastDuration = remaining;
733
+ const clear = () => {
734
+ if (timer !== undefined)
735
+ clearTimeout(timer);
736
+ timer = undefined;
737
+ };
738
+ const stopTimer = effect(() => {
739
+ const current = record();
740
+ const total = duration();
741
+ if (total !== lastDuration) {
742
+ remaining = total;
743
+ lastDuration = total;
744
+ }
745
+ if (current.removing) {
746
+ clear();
747
+ // Untracked: this writes the heights the offset is read from.
748
+ untrack(() => {
749
+ offsetBeforeRemove = offset();
750
+ state.setHeight(current.serial, undefined);
751
+ });
752
+ return;
753
+ }
754
+ if (current.type === "loading" || total === Number.POSITIVE_INFINITY) {
755
+ clear();
756
+ return;
757
+ }
758
+ if (state.paused()) {
759
+ if (timer !== undefined)
760
+ remaining -= Date.now() - startedAt;
761
+ clear();
762
+ return;
763
+ }
764
+ clear();
765
+ startedAt = Date.now();
766
+ timer = setTimeout(() => remove(current.id, "autoClose"), Math.max(remaining, 0));
767
+ });
768
+ return () => {
769
+ stopContent();
770
+ stopTimer();
771
+ clear();
772
+ };
773
+ });
774
+ onUnmount(() => {
775
+ state.setHeight(record().serial, undefined);
776
+ });
777
+ const typeKey = () => record().type ?? "default";
778
+ function surfaceClasses() {
779
+ const current = record();
780
+ const type = current.type;
781
+ const classNames = state.options.classNames;
782
+ const colours = !styled()
783
+ ? undefined
784
+ : inverted()
785
+ ? INVERT[state.theme]
786
+ : rich() &&
787
+ type !== undefined &&
788
+ type !== "default" &&
789
+ type !== "loading"
790
+ ? RICH[type][state.theme]
791
+ : NORMAL;
792
+ return cn(TOAST_LAYOUT, styled() ? TOAST_STYLED : undefined, colours, state.options.class, current.class, classNames?.toast, current.classNames?.toast, classNames?.[typeKey()], current.classNames?.[typeKey()]);
793
+ }
794
+ function closeClasses() {
795
+ const type = record().type;
796
+ const colours = rich() && type !== undefined && type !== "default" && type !== "loading"
797
+ ? RICH[type][state.theme]
798
+ : cn(NORMAL, CLOSE_HOVER[state.theme]);
799
+ return cn(CLOSE_BUTTON, colours, state.options.classNames?.closeButton, record().classNames?.closeButton);
800
+ }
801
+ function renderClose() {
802
+ const current = record();
803
+ const show = (current.closeButton ?? state.closeButton) === true &&
804
+ current.custom === undefined &&
805
+ current.type !== "loading";
806
+ if (!show)
807
+ return null;
808
+ return html `<button
809
+ type="button"
810
+ aria-label="${state.options.closeButtonAriaLabel ?? "Close toast"}"
811
+ data-close-button
812
+ data-disabled="${String(current.type === "loading")}"
813
+ class="${closeClasses}"
814
+ @click="${() => {
815
+ if (dismissible())
816
+ remove(record().id, "dismiss");
817
+ }}"
818
+ >${state.icons?.close ?? XIcon({ class: "size-3" })}</button>`;
819
+ }
820
+ function renderIcon() {
821
+ const current = record();
822
+ if (current.icon === null)
823
+ return null;
824
+ const type = current.type;
825
+ let icon;
826
+ if (current.icon !== undefined)
827
+ icon = current.icon;
828
+ else if (type !== undefined &&
829
+ state.icons !== undefined &&
830
+ type in state.icons) {
831
+ icon = type === "default" ? null : state.icons[type];
832
+ }
833
+ else
834
+ icon = defaultIcon(type);
835
+ if (icon === null || icon === undefined || icon === false)
836
+ return null;
837
+ return html `<div
838
+ data-icon
839
+ class="${cn("relative flex size-4 shrink-0 items-center justify-start -ms-[3px] me-1", state.options.classNames?.icon, current.classNames?.icon)}"
840
+ >${icon}</div>`;
841
+ }
842
+ function renderButton(kind) {
843
+ const current = record();
844
+ const action = kind === "cancel" ? current.cancel : current.action;
845
+ if (action === undefined)
846
+ return null;
847
+ const classNames = state.options.classNames;
848
+ const classes = kind === "cancel"
849
+ ? cn(BUTTON, "text-popover-foreground", CANCEL[state.theme], classNames?.cancelButton, current.classNames?.cancelButton)
850
+ : cn(BUTTON, "bg-popover-foreground text-popover", classNames?.actionButton, current.classNames?.actionButton);
851
+ return html `<button
852
+ type="button"
853
+ data-button
854
+ data-cancel="${kind === "cancel" ? "" : undefined}"
855
+ data-action="${kind === "action" ? "" : undefined}"
856
+ class="${classes}"
857
+ @click="${(event) => {
858
+ if (kind === "cancel") {
859
+ if (!dismissible())
860
+ return;
861
+ action.onClick(event);
862
+ remove(record().id, "silent");
863
+ return;
864
+ }
865
+ action.onClick(event);
866
+ if (event.defaultPrevented)
867
+ return;
868
+ remove(record().id, "silent");
869
+ }}"
870
+ >${action.label}</button>`;
871
+ }
872
+ function renderDescription() {
873
+ const current = record();
874
+ if (current.description === undefined)
875
+ return null;
876
+ return html `<div
877
+ data-description
878
+ class="${cn("font-normal leading-[1.4]", rich() ? "text-inherit" : DESCRIPTION[state.theme], state.options.descriptionClass, current.descriptionClass, state.options.classNames?.description, current.classNames?.description)}"
879
+ >${read(current.description)}</div>`;
880
+ }
881
+ return html `<li
882
+ id="${rowId}"
883
+ tabindex="0"
884
+ data-slot="sonner-toast"
885
+ data-sonner-toast
886
+ data-type="${() => record().type}"
887
+ data-rich-colors="${() => String(rich())}"
888
+ data-styled="${() => String(styled())}"
889
+ data-mounted="${() => String(mounted())}"
890
+ data-promise="${() => String(record().promise === true)}"
891
+ data-removed="${() => String(record().removing)}"
892
+ data-visible="${() => String(isVisible())}"
893
+ data-y-position="${y}"
894
+ data-x-position="${x}"
895
+ data-index="${() => String(props.index())}"
896
+ data-front="${() => String(isFront())}"
897
+ data-dismissible="${() => String(dismissible())}"
898
+ data-invert="${() => String(inverted())}"
899
+ data-expanded="${() => String(isExpanded())}"
900
+ data-testid="${() => record().testId}"
901
+ class="${surfaceClasses}"
902
+ .style="${style}"
903
+ >${renderClose}${renderIcon}<div
904
+ data-content
905
+ class="${() => cn("flex min-w-0 flex-1 flex-col gap-0.5", state.options.classNames?.content, record().classNames?.content)}"
906
+ ><div
907
+ data-title
908
+ class="${() => cn("font-medium leading-normal", state.options.classNames?.title, record().classNames?.title)}"
909
+ >${() => record().custom ?? read(record().title)}</div>${renderDescription}</div>${() => renderButton("cancel")}${() => renderButton("action")}${() => isExpanded() && !record().removing
910
+ ? html `<span
911
+ aria-hidden="true"
912
+ class="absolute left-0 bottom-full w-full"
913
+ .style="${`height:${state.gap + 1}px`}"
914
+ ></span>`
915
+ : null}</li>`;
916
+ });