@zag-js/toast 0.50.0 → 0.51.1

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.
package/dist/index.js CHANGED
@@ -1,956 +1,2 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var src_exports = {};
22
- __export(src_exports, {
23
- anatomy: () => anatomy,
24
- connect: () => connect,
25
- createMachine: () => createToastMachine,
26
- group: () => group
27
- });
28
- module.exports = __toCommonJS(src_exports);
29
-
30
- // src/toast-group.connect.ts
31
- var import_core = require("@zag-js/core");
32
- var import_dom_query3 = require("@zag-js/dom-query");
33
- var import_utils = require("@zag-js/utils");
34
-
35
- // src/toast.anatomy.ts
36
- var import_anatomy = require("@zag-js/anatomy");
37
- var anatomy = (0, import_anatomy.createAnatomy)("toast").parts(
38
- "group",
39
- "root",
40
- "title",
41
- "description",
42
- "actionTrigger",
43
- "closeTrigger"
44
- );
45
- var parts = anatomy.build();
46
-
47
- // src/toast.dom.ts
48
- var import_dom_query = require("@zag-js/dom-query");
49
- var dom = (0, import_dom_query.createScope)({
50
- getRegionId: (placement) => `toast-group:${placement}`,
51
- getRegionEl: (ctx, placement) => dom.getById(ctx, `toast-group:${placement}`),
52
- getRootId: (ctx) => `toast:${ctx.id}`,
53
- getRootEl: (ctx) => dom.getById(ctx, dom.getRootId(ctx)),
54
- getTitleId: (ctx) => `toast:${ctx.id}:title`,
55
- getDescriptionId: (ctx) => `toast:${ctx.id}:description`,
56
- getCloseTriggerId: (ctx) => `toast${ctx.id}:close`
57
- });
58
-
59
- // src/toast.utils.ts
60
- var import_dom_query2 = require("@zag-js/dom-query");
61
- function getToastsByPlacement(toasts, placement) {
62
- return toasts.filter((toast) => toast.state.context.placement === placement);
63
- }
64
- var defaultTimeouts = {
65
- info: 5e3,
66
- error: 5e3,
67
- success: 2e3,
68
- loading: Infinity,
69
- DEFAULT: 5e3
70
- };
71
- function getToastDuration(duration, type) {
72
- return duration ?? defaultTimeouts[type] ?? defaultTimeouts.DEFAULT;
73
- }
74
- function getGroupPlacementStyle(ctx, placement) {
75
- const offset = ctx.offsets;
76
- const computedOffset = typeof offset === "string" ? { left: offset, right: offset, bottom: offset, top: offset } : offset;
77
- const rtl = ctx.dir === "rtl";
78
- const computedPlacement = placement.replace("-start", rtl ? "-right" : "-left").replace("-end", rtl ? "-left" : "-right");
79
- const isRighty = computedPlacement.includes("right");
80
- const isLefty = computedPlacement.includes("left");
81
- const styles = {
82
- position: "fixed",
83
- pointerEvents: ctx.count > 0 ? void 0 : "none",
84
- display: "flex",
85
- flexDirection: "column",
86
- "--gap": `${ctx.gap}px`,
87
- "--first-height": `${ctx.heights[0]?.height || 0}px`,
88
- zIndex: import_dom_query2.MAX_Z_INDEX
89
- };
90
- let alignItems = "center";
91
- if (isRighty)
92
- alignItems = "flex-end";
93
- if (isLefty)
94
- alignItems = "flex-start";
95
- styles.alignItems = alignItems;
96
- if (computedPlacement.includes("top")) {
97
- const offset2 = computedOffset.top;
98
- styles.top = `max(env(safe-area-inset-top, 0px), ${offset2})`;
99
- }
100
- if (computedPlacement.includes("bottom")) {
101
- const offset2 = computedOffset.bottom;
102
- styles.bottom = `max(env(safe-area-inset-bottom, 0px), ${offset2})`;
103
- }
104
- if (!computedPlacement.includes("left")) {
105
- const offset2 = computedOffset.right;
106
- styles.insetInlineEnd = `calc(env(safe-area-inset-right, 0px) + ${offset2})`;
107
- }
108
- if (!computedPlacement.includes("right")) {
109
- const offset2 = computedOffset.left;
110
- styles.insetInlineStart = `calc(env(safe-area-inset-left, 0px) + ${offset2})`;
111
- }
112
- return styles;
113
- }
114
- function getPlacementStyle(ctx, visible) {
115
- const [side] = ctx.placement.split("-");
116
- const sibling = !ctx.frontmost;
117
- const overlap = !ctx.stacked;
118
- const styles = {
119
- position: "absolute",
120
- pointerEvents: "auto",
121
- "--opacity": "0",
122
- "--remove-delay": `${ctx.removeDelay}ms`,
123
- "--duration": `${ctx.type === "loading" ? Number.MAX_SAFE_INTEGER : ctx.duration}ms`,
124
- "--initial-height": `${ctx.height}px`,
125
- "--offset": `${ctx.offset}px`,
126
- "--index": ctx.index,
127
- "--z-index": ctx.zIndex,
128
- "--lift-amount": "calc(var(--lift) * var(--gap))",
129
- "--y": "100%",
130
- "--x": "0"
131
- };
132
- const assign = (overrides) => Object.assign(styles, overrides);
133
- if (side === "top") {
134
- assign({
135
- top: "0",
136
- "--sign": "-1",
137
- "--y": "-100%",
138
- "--lift": "1"
139
- });
140
- } else if (side === "bottom") {
141
- assign({
142
- bottom: "0",
143
- "--sign": "1",
144
- "--y": "100%",
145
- "--lift": "-1"
146
- });
147
- }
148
- if (ctx.mounted) {
149
- assign({
150
- "--y": "0",
151
- "--opacity": "1"
152
- });
153
- if (ctx.stacked) {
154
- assign({
155
- "--y": "calc(var(--lift) * var(--offset))",
156
- "--height": "var(--initial-height)"
157
- });
158
- }
159
- }
160
- if (!visible) {
161
- assign({
162
- "--opacity": "0",
163
- pointerEvents: "none"
164
- });
165
- }
166
- if (sibling && overlap) {
167
- assign({
168
- "--base-scale": "var(--index) * 0.05 + 1",
169
- "--y": "calc(var(--lift-amount) * var(--index))",
170
- "--scale": "calc(-1 * var(--base-scale))",
171
- "--height": "var(--first-height)"
172
- });
173
- if (!visible) {
174
- assign({
175
- "--y": "calc(var(--sign) * 40%)"
176
- });
177
- }
178
- }
179
- if (sibling && ctx.stacked && !visible) {
180
- assign({
181
- "--y": "calc(var(--lift) * var(--offset) + var(--lift) * -100%)"
182
- });
183
- }
184
- if (ctx.frontmost && !visible) {
185
- assign({
186
- "--y": "calc(var(--lift) * -100%)"
187
- });
188
- }
189
- return styles;
190
- }
191
- function getGhostBeforeStyle(ctx, visible) {
192
- const styles = {
193
- position: "absolute",
194
- inset: "0",
195
- scale: "1 2",
196
- pointerEvents: visible ? "none" : "auto"
197
- };
198
- const assign = (overrides) => Object.assign(styles, overrides);
199
- if (ctx.frontmost && !visible) {
200
- assign({
201
- height: "calc(var(--initial-height) + 80%)"
202
- });
203
- }
204
- return styles;
205
- }
206
- function getGhostAfterStyle(_ctx, _visible) {
207
- return {
208
- position: "absolute",
209
- left: "0",
210
- height: "calc(var(--gap) + 2px)",
211
- bottom: "100%",
212
- width: "100%"
213
- };
214
- }
215
-
216
- // src/toast-group.connect.ts
217
- function groupConnect(serviceOrState, send, normalize) {
218
- function getState() {
219
- const result = (0, import_core.isMachine)(serviceOrState) ? serviceOrState.getState() : serviceOrState;
220
- return result;
221
- }
222
- function getToastsByPlacementImpl(placement) {
223
- return getToastsByPlacement(getState().context.toasts, placement);
224
- }
225
- function isVisible(id) {
226
- const toasts = getState().context.toasts;
227
- if (!toasts.length)
228
- return false;
229
- return !!toasts.find((toast) => toast.id == id);
230
- }
231
- function create(options) {
232
- const uid = `toast:${(0, import_utils.uuid)()}`;
233
- const id = options.id ? options.id : uid;
234
- if (isVisible(id))
235
- return id;
236
- send({ type: "ADD_TOAST", toast: { ...options, id } });
237
- return id;
238
- }
239
- function update(id, options) {
240
- if (!isVisible(id))
241
- return id;
242
- send({ type: "UPDATE_TOAST", id, toast: options });
243
- return id;
244
- }
245
- function upsert(options) {
246
- const { id } = options;
247
- const visible = id ? isVisible(id) : false;
248
- if (visible && id != null) {
249
- return update(id, options);
250
- } else {
251
- return create(options);
252
- }
253
- }
254
- function dismiss(id) {
255
- if (id == null) {
256
- send("DISMISS_ALL");
257
- } else if (isVisible(id)) {
258
- send({ type: "DISMISS_TOAST", id });
259
- }
260
- }
261
- return {
262
- getCount() {
263
- return getState().context.count;
264
- },
265
- getPlacements() {
266
- const toasts = getState().context.toasts;
267
- const placements = toasts.map((toast) => toast.state.context.placement);
268
- return Array.from(new Set(placements));
269
- },
270
- getToastsByPlacement: getToastsByPlacementImpl,
271
- isVisible,
272
- create,
273
- update,
274
- upsert,
275
- dismiss,
276
- remove(id) {
277
- if (id == null) {
278
- send("REMOVE_ALL");
279
- } else if (isVisible(id)) {
280
- send({ type: "REMOVE_TOAST", id });
281
- }
282
- },
283
- dismissByPlacement(placement) {
284
- const toasts = getToastsByPlacementImpl(placement);
285
- toasts.forEach((toast) => dismiss(toast.id));
286
- },
287
- loading(options) {
288
- return upsert({ ...options, type: "loading" });
289
- },
290
- success(options) {
291
- return upsert({ ...options, type: "success" });
292
- },
293
- error(options) {
294
- return upsert({ ...options, type: "error" });
295
- },
296
- promise(promise, options, shared = {}) {
297
- const id = upsert({ ...shared, ...options.loading, type: "loading" });
298
- (0, import_utils.runIfFn)(promise).then((response) => {
299
- const successOptions = (0, import_utils.runIfFn)(options.success, response);
300
- upsert({ ...shared, ...successOptions, id, type: "success" });
301
- }).catch((error) => {
302
- const errorOptions = (0, import_utils.runIfFn)(options.error, error);
303
- upsert({ ...shared, ...errorOptions, id, type: "error" });
304
- }).finally(() => {
305
- options.finally?.();
306
- });
307
- return id;
308
- },
309
- pause(id) {
310
- if (id == null) {
311
- send("PAUSE_ALL");
312
- } else if (isVisible(id)) {
313
- send({ type: "PAUSE_TOAST", id });
314
- }
315
- },
316
- resume(id) {
317
- if (id == null) {
318
- send("RESUME_ALL");
319
- } else if (isVisible(id)) {
320
- send({ type: "RESUME_TOAST", id });
321
- }
322
- },
323
- getGroupProps(options) {
324
- const { placement, label = "Notifications" } = options;
325
- const state = getState();
326
- const hotkeyLabel = state.context.hotkey.join("+").replace(/Key/g, "").replace(/Digit/g, "");
327
- const [side, align = "center"] = placement.split("-");
328
- return normalize.element({
329
- ...parts.group.attrs,
330
- dir: state.context.dir,
331
- tabIndex: -1,
332
- "aria-label": `${placement} ${label} ${hotkeyLabel}`,
333
- id: dom.getRegionId(placement),
334
- "data-placement": placement,
335
- "data-side": side,
336
- "data-align": align,
337
- "aria-live": "polite",
338
- role: "region",
339
- style: getGroupPlacementStyle(state.context, placement),
340
- onMouseMove() {
341
- send({ type: "REGION.POINTER_ENTER", placement });
342
- },
343
- onMouseLeave() {
344
- send({ type: "REGION.POINTER_LEAVE", placement });
345
- },
346
- onFocus(event) {
347
- send({ type: "REGION.FOCUS", target: event.relatedTarget });
348
- },
349
- onBlur(event) {
350
- if (state.context.isFocusWithin && !(0, import_dom_query3.contains)(event.currentTarget, event.relatedTarget)) {
351
- send({ type: "REGION.BLUR" });
352
- }
353
- }
354
- });
355
- },
356
- subscribe(fn) {
357
- const state = getState();
358
- return (0, import_core.subscribe)(state.context.toasts, () => {
359
- const toasts = getToastsByPlacementImpl(state.context.placement);
360
- const contexts = toasts.map((toast) => toast.getState().context);
361
- fn(contexts);
362
- });
363
- }
364
- };
365
- }
366
-
367
- // src/toast-group.machine.ts
368
- var import_core3 = require("@zag-js/core");
369
- var import_dismissable = require("@zag-js/dismissable");
370
- var import_dom_event = require("@zag-js/dom-event");
371
- var import_utils3 = require("@zag-js/utils");
372
-
373
- // src/toast.machine.ts
374
- var import_core2 = require("@zag-js/core");
375
- var import_dom_query4 = require("@zag-js/dom-query");
376
- var import_utils2 = require("@zag-js/utils");
377
- var { not, and, or } = import_core2.guards;
378
- function createToastMachine(options) {
379
- const { type = "info", duration, id = "1", placement = "bottom", removeDelay = 200, ...restProps } = options;
380
- const ctx = (0, import_utils2.compact)(restProps);
381
- const computedDuration = getToastDuration(duration, type);
382
- return (0, import_core2.createMachine)(
383
- {
384
- id,
385
- context: {
386
- id,
387
- type,
388
- remaining: computedDuration,
389
- duration: computedDuration,
390
- removeDelay,
391
- createdAt: Date.now(),
392
- placement,
393
- ...ctx,
394
- height: 0,
395
- offset: 0,
396
- frontmost: false,
397
- mounted: false,
398
- index: -1,
399
- zIndex: 0
400
- },
401
- initial: type === "loading" ? "visible:persist" : "visible",
402
- on: {
403
- UPDATE: [
404
- {
405
- guard: and("hasTypeChanged", "isChangingToLoading"),
406
- target: "visible:persist",
407
- actions: ["setContext"]
408
- },
409
- {
410
- guard: or("hasDurationChanged", "hasTypeChanged"),
411
- target: "visible:updating",
412
- actions: ["setContext"]
413
- },
414
- {
415
- actions: ["setContext"]
416
- }
417
- ],
418
- MEASURE: {
419
- actions: ["measureHeight"]
420
- }
421
- },
422
- entry: ["invokeOnVisible"],
423
- activities: ["trackHeight"],
424
- states: {
425
- "visible:updating": {
426
- tags: ["visible", "updating"],
427
- after: {
428
- 0: "visible"
429
- }
430
- },
431
- "visible:persist": {
432
- tags: ["visible", "paused"],
433
- on: {
434
- RESUME: {
435
- guard: not("isLoadingType"),
436
- target: "visible",
437
- actions: ["setCreatedAt"]
438
- },
439
- DISMISS: "dismissing"
440
- }
441
- },
442
- visible: {
443
- tags: ["visible"],
444
- after: {
445
- VISIBLE_DURATION: "dismissing"
446
- },
447
- on: {
448
- DISMISS: "dismissing",
449
- PAUSE: {
450
- target: "visible:persist",
451
- actions: "setRemainingDuration"
452
- }
453
- }
454
- },
455
- dismissing: {
456
- entry: "invokeOnDismiss",
457
- after: {
458
- REMOVE_DELAY: {
459
- target: "unmounted",
460
- actions: "notifyParentToRemove"
461
- }
462
- }
463
- },
464
- unmounted: {
465
- entry: "invokeOnUnmount",
466
- type: "final"
467
- }
468
- }
469
- },
470
- {
471
- activities: {
472
- trackHeight(ctx2, _evt, { self }) {
473
- let cleanup;
474
- (0, import_dom_query4.raf)(() => {
475
- const rootEl = dom.getRootEl(ctx2);
476
- if (!rootEl)
477
- return;
478
- ctx2.mounted = true;
479
- const ghosts = (0, import_dom_query4.queryAll)(rootEl, "[data-ghost]");
480
- (0, import_utils2.warn)(
481
- ghosts.length !== 2,
482
- "[toast] No ghost element found in toast. Render the `ghostBefore` and `ghostAfter` elements"
483
- );
484
- const syncHeight = () => {
485
- const originalHeight = rootEl.style.height;
486
- rootEl.style.height = "auto";
487
- const newHeight = rootEl.getBoundingClientRect().height;
488
- rootEl.style.height = originalHeight;
489
- ctx2.height = newHeight;
490
- self.sendParent({ type: "UPDATE_HEIGHT", id: self.id, height: newHeight, placement: ctx2.placement });
491
- };
492
- syncHeight();
493
- const win = dom.getWin(ctx2);
494
- const observer = new win.MutationObserver(syncHeight);
495
- observer.observe(rootEl, { childList: true, subtree: true, characterData: true });
496
- cleanup = () => observer.disconnect();
497
- });
498
- return () => cleanup?.();
499
- }
500
- },
501
- guards: {
502
- isChangingToLoading: (_, evt) => evt.toast?.type === "loading",
503
- isLoadingType: (ctx2) => ctx2.type === "loading",
504
- hasTypeChanged: (ctx2, evt) => evt.toast?.type != null && evt.toast.type !== ctx2.type,
505
- hasDurationChanged: (ctx2, evt) => evt.toast?.duration != null && evt.toast.duration !== ctx2.duration
506
- },
507
- delays: {
508
- VISIBLE_DURATION: (ctx2) => ctx2.remaining,
509
- REMOVE_DELAY: (ctx2) => ctx2.removeDelay
510
- },
511
- actions: {
512
- measureHeight(ctx2, _evt, { self }) {
513
- (0, import_dom_query4.raf)(() => {
514
- const rootEl = dom.getRootEl(ctx2);
515
- if (!rootEl)
516
- return;
517
- ctx2.mounted = true;
518
- const originalHeight = rootEl.style.height;
519
- rootEl.style.height = "auto";
520
- const newHeight = rootEl.getBoundingClientRect().height;
521
- rootEl.style.height = originalHeight;
522
- ctx2.height = newHeight;
523
- self.sendParent({ type: "UPDATE_HEIGHT", id: self.id, height: newHeight, placement: ctx2.placement });
524
- });
525
- },
526
- setRemainingDuration(ctx2) {
527
- ctx2.remaining -= Date.now() - ctx2.createdAt;
528
- },
529
- setCreatedAt(ctx2) {
530
- ctx2.createdAt = Date.now();
531
- },
532
- notifyParentToRemove(_ctx, _evt, { self }) {
533
- self.sendParent({ type: "REMOVE_TOAST", id: self.id });
534
- },
535
- invokeOnDismiss(ctx2) {
536
- ctx2.onStatusChange?.({ status: "dismissing" });
537
- },
538
- invokeOnUnmount(ctx2) {
539
- ctx2.onStatusChange?.({ status: "unmounted" });
540
- },
541
- invokeOnVisible(ctx2) {
542
- ctx2.onStatusChange?.({ status: "visible" });
543
- },
544
- setContext(ctx2, evt) {
545
- const duration2 = evt.toast?.duration;
546
- const type2 = evt.toast?.type ?? ctx2.type;
547
- const computedDuration2 = getToastDuration(duration2, type2);
548
- Object.assign(ctx2, {
549
- ...evt.toast,
550
- duration: computedDuration2,
551
- remaining: computedDuration2
552
- });
553
- }
554
- }
555
- }
556
- );
557
- }
558
-
559
- // src/toast-group.machine.ts
560
- function groupMachine(userContext) {
561
- const ctx = (0, import_utils3.compact)(userContext);
562
- return (0, import_core3.createMachine)(
563
- {
564
- id: "toaster",
565
- initial: ctx.overlap ? "overlap" : "stack",
566
- context: {
567
- dir: "ltr",
568
- max: Number.MAX_SAFE_INTEGER,
569
- gap: 16,
570
- pauseOnPageIdle: false,
571
- hotkey: ["altKey", "KeyT"],
572
- offsets: "1rem",
573
- placement: "bottom",
574
- removeDelay: 200,
575
- ...ctx,
576
- toasts: [],
577
- lastFocusedEl: null,
578
- isFocusWithin: false,
579
- heights: []
580
- },
581
- computed: {
582
- count: (ctx2) => ctx2.toasts.length
583
- },
584
- activities: ["trackDocumentVisibility", "trackHotKeyPress"],
585
- watch: {
586
- toasts: ["collapsedIfEmpty", "setDismissableBranch"]
587
- },
588
- exit: ["removeToasts", "clearDismissableBranch", "clearLastFocusedEl"],
589
- on: {
590
- PAUSE_TOAST: {
591
- actions: ["pauseToast"]
592
- },
593
- PAUSE_ALL: {
594
- actions: ["pauseToasts"]
595
- },
596
- RESUME_TOAST: {
597
- actions: ["resumeToast"]
598
- },
599
- RESUME_ALL: {
600
- actions: ["resumeToasts"]
601
- },
602
- ADD_TOAST: {
603
- guard: "isWithinRange",
604
- actions: ["createToast", "syncToastIndex"]
605
- },
606
- UPDATE_TOAST: {
607
- actions: ["updateToast"]
608
- },
609
- DISMISS_TOAST: {
610
- actions: ["dismissToast"]
611
- },
612
- DISMISS_ALL: {
613
- actions: ["dismissToasts"]
614
- },
615
- REMOVE_TOAST: {
616
- actions: ["removeToast", "syncToastIndex", "syncToastOffset"]
617
- },
618
- REMOVE_ALL: {
619
- actions: ["removeToasts"]
620
- },
621
- UPDATE_HEIGHT: {
622
- actions: ["syncHeights", "syncToastOffset"]
623
- },
624
- "DOC.HOTKEY": {
625
- actions: ["focusRegionEl"]
626
- },
627
- "REGION.BLUR": [
628
- {
629
- guard: "isOverlapping",
630
- target: "overlap",
631
- actions: ["resumeToasts", "restoreLastFocusedEl"]
632
- },
633
- {
634
- actions: ["resumeToasts", "restoreLastFocusedEl"]
635
- }
636
- ]
637
- },
638
- states: {
639
- stack: {
640
- entry: ["expandToasts"],
641
- on: {
642
- "REGION.POINTER_LEAVE": [
643
- {
644
- guard: "isOverlapping",
645
- target: "overlap",
646
- actions: ["resumeToasts"]
647
- },
648
- {
649
- actions: ["resumeToasts"]
650
- }
651
- ],
652
- "REGION.OVERLAP": {
653
- target: "overlap"
654
- },
655
- "REGION.FOCUS": {
656
- actions: ["setLastFocusedEl", "pauseToasts"]
657
- },
658
- "REGION.POINTER_ENTER": {
659
- actions: ["pauseToasts"]
660
- }
661
- }
662
- },
663
- overlap: {
664
- entry: ["collapseToasts"],
665
- on: {
666
- "REGION.STACK": {
667
- target: "stack"
668
- },
669
- "REGION.POINTER_ENTER": {
670
- target: "stack",
671
- actions: ["pauseToasts"]
672
- },
673
- "REGION.FOCUS": {
674
- target: "stack",
675
- actions: ["setLastFocusedEl", "pauseToasts"]
676
- }
677
- }
678
- }
679
- }
680
- },
681
- {
682
- guards: {
683
- isWithinRange: (ctx2) => ctx2.toasts.length < ctx2.max,
684
- isOverlapping: (ctx2) => !!ctx2.overlap
685
- },
686
- activities: {
687
- trackHotKeyPress(ctx2, _evt, { send }) {
688
- const handleKeyDown = (event) => {
689
- const isHotkeyPressed = ctx2.hotkey.every((key) => event[key] || event.code === key);
690
- if (!isHotkeyPressed)
691
- return;
692
- send({ type: "DOC.HOTKEY" });
693
- };
694
- return (0, import_dom_event.addDomEvent)(document, "keydown", handleKeyDown, { capture: true });
695
- },
696
- trackDocumentVisibility(ctx2, _evt, { send }) {
697
- if (!ctx2.pauseOnPageIdle)
698
- return;
699
- const doc = dom.getDoc(ctx2);
700
- return (0, import_dom_event.addDomEvent)(doc, "visibilitychange", () => {
701
- send(doc.visibilityState === "hidden" ? "PAUSE_ALL" : "RESUME_ALL");
702
- });
703
- }
704
- },
705
- actions: {
706
- setDismissableBranch(ctx2) {
707
- const currentToasts = getToastsByPlacement(ctx2.toasts, ctx2.placement);
708
- const hasToasts = currentToasts.length > 0;
709
- if (!hasToasts) {
710
- ctx2._cleanup?.();
711
- return;
712
- }
713
- if (hasToasts && ctx2._cleanup) {
714
- return;
715
- }
716
- const groupEl = () => dom.getRegionEl(ctx2, ctx2.placement);
717
- ctx2._cleanup = (0, import_dismissable.trackDismissableBranch)(groupEl, { defer: true });
718
- },
719
- clearDismissableBranch(ctx2) {
720
- ctx2._cleanup?.();
721
- },
722
- focusRegionEl(ctx2) {
723
- queueMicrotask(() => {
724
- dom.getRegionEl(ctx2, ctx2.placement)?.focus();
725
- });
726
- },
727
- expandToasts(ctx2) {
728
- each(ctx2, (toast) => {
729
- toast.state.context.stacked = true;
730
- });
731
- },
732
- collapseToasts(ctx2) {
733
- each(ctx2, (toast) => {
734
- toast.state.context.stacked = false;
735
- });
736
- },
737
- collapsedIfEmpty(ctx2, _evt, { send }) {
738
- if (!ctx2.overlap || ctx2.toasts.length > 1)
739
- return;
740
- send("REGION.OVERLAP");
741
- },
742
- pauseToast(_ctx, evt, { self }) {
743
- self.sendChild("PAUSE", evt.id);
744
- },
745
- pauseToasts(ctx2) {
746
- ctx2.toasts.forEach((toast) => toast.send("PAUSE"));
747
- },
748
- resumeToast(_ctx, evt, { self }) {
749
- self.sendChild("RESUME", evt.id);
750
- },
751
- resumeToasts(ctx2) {
752
- ctx2.toasts.forEach((toast) => toast.send("RESUME"));
753
- },
754
- measureToasts(ctx2) {
755
- ctx2.toasts.forEach((toast) => toast.send("MEASURE"));
756
- },
757
- createToast(ctx2, evt, { self, getState }) {
758
- const options = {
759
- placement: ctx2.placement,
760
- duration: ctx2.duration,
761
- removeDelay: ctx2.removeDelay,
762
- ...evt.toast,
763
- dir: ctx2.dir,
764
- getRootNode: ctx2.getRootNode,
765
- stacked: getState().matches("stack")
766
- };
767
- const toast = createToastMachine(options);
768
- const actor = self.spawn(toast);
769
- ctx2.toasts = [actor, ...ctx2.toasts];
770
- },
771
- updateToast(_ctx, evt, { self }) {
772
- self.sendChild({ type: "UPDATE", toast: evt.toast }, evt.id);
773
- },
774
- dismissToast(_ctx, evt, { self }) {
775
- self.sendChild("DISMISS", evt.id);
776
- },
777
- dismissToasts(ctx2) {
778
- ctx2.toasts.forEach((toast) => toast.send("DISMISS"));
779
- },
780
- removeToast(ctx2, evt, { self }) {
781
- self.stopChild(evt.id);
782
- ctx2.toasts = ctx2.toasts.filter((toast) => toast.id !== evt.id);
783
- ctx2.heights = ctx2.heights.filter((height) => height.id !== evt.id);
784
- },
785
- removeToasts(ctx2, _evt, { self }) {
786
- ctx2.toasts.forEach((toast) => self.stopChild(toast.id));
787
- ctx2.toasts = [];
788
- ctx2.heights = [];
789
- },
790
- syncHeights(ctx2, evt) {
791
- const existing = ctx2.heights.find((height) => height.id === evt.id);
792
- if (existing) {
793
- existing.height = evt.height;
794
- existing.placement = evt.placement;
795
- } else {
796
- const newHeight = { id: evt.id, height: evt.height, placement: evt.placement };
797
- ctx2.heights = [newHeight, ...ctx2.heights];
798
- }
799
- },
800
- syncToastIndex(ctx2) {
801
- each(ctx2, (toast, index, toasts) => {
802
- toast.state.context.index = index;
803
- toast.state.context.frontmost = index === 0;
804
- toast.state.context.zIndex = toasts.length - index;
805
- });
806
- },
807
- syncToastOffset(ctx2, evt) {
808
- const placement = evt.placement ?? ctx2.placement;
809
- each({ ...ctx2, placement }, (toast) => {
810
- const heightIndex = Math.max(
811
- ctx2.heights.findIndex((height) => height.id === toast.id),
812
- 0
813
- );
814
- const toastsHeightBefore = ctx2.heights.reduce((prev, curr, reducerIndex) => {
815
- if (reducerIndex >= heightIndex)
816
- return prev;
817
- return prev + curr.height;
818
- }, 0);
819
- toast.state.context.offset = heightIndex * ctx2.gap + toastsHeightBefore;
820
- });
821
- },
822
- setLastFocusedEl(ctx2, evt) {
823
- if (ctx2.isFocusWithin || !evt.target)
824
- return;
825
- ctx2.isFocusWithin = true;
826
- ctx2.lastFocusedEl = (0, import_core3.ref)(evt.target);
827
- },
828
- restoreLastFocusedEl(ctx2) {
829
- ctx2.isFocusWithin = false;
830
- if (!ctx2.lastFocusedEl)
831
- return;
832
- ctx2.lastFocusedEl.focus({ preventScroll: true });
833
- ctx2.lastFocusedEl = null;
834
- },
835
- clearLastFocusedEl(ctx2) {
836
- if (!ctx2.lastFocusedEl)
837
- return;
838
- ctx2.lastFocusedEl.focus({ preventScroll: true });
839
- ctx2.lastFocusedEl = null;
840
- ctx2.isFocusWithin = false;
841
- }
842
- }
843
- }
844
- );
845
- }
846
- function each(ctx, fn) {
847
- const currentToasts = getToastsByPlacement(ctx.toasts, ctx.placement);
848
- currentToasts.forEach(fn);
849
- }
850
-
851
- // src/toast.connect.ts
852
- var import_dom_query5 = require("@zag-js/dom-query");
853
- function connect(state, send, normalize) {
854
- const visible = state.hasTag("visible");
855
- const paused = state.hasTag("paused");
856
- const placement = state.context.placement;
857
- const type = state.context.type;
858
- const [side, align = "center"] = placement.split("-");
859
- return {
860
- type,
861
- title: state.context.title,
862
- description: state.context.description,
863
- placement,
864
- visible,
865
- paused,
866
- pause() {
867
- send("PAUSE");
868
- },
869
- resume() {
870
- send("RESUME");
871
- },
872
- dismiss() {
873
- send("DISMISS");
874
- },
875
- rootProps: normalize.element({
876
- ...parts.root.attrs,
877
- dir: state.context.dir,
878
- id: dom.getRootId(state.context),
879
- "data-state": visible ? "open" : "closed",
880
- "data-type": type,
881
- "data-placement": placement,
882
- "data-align": align,
883
- "data-side": side,
884
- "data-mounted": (0, import_dom_query5.dataAttr)(state.context.mounted),
885
- "data-paused": (0, import_dom_query5.dataAttr)(paused),
886
- "data-first": (0, import_dom_query5.dataAttr)(state.context.frontmost),
887
- "data-sibling": (0, import_dom_query5.dataAttr)(!state.context.frontmost),
888
- "data-stack": (0, import_dom_query5.dataAttr)(state.context.stacked),
889
- "data-overlap": (0, import_dom_query5.dataAttr)(!state.context.stacked),
890
- role: "status",
891
- "aria-atomic": "true",
892
- tabIndex: 0,
893
- style: getPlacementStyle(state.context, visible),
894
- onKeyDown(event) {
895
- if (event.defaultPrevented)
896
- return;
897
- if (event.key == "Escape") {
898
- send("DISMISS");
899
- event.preventDefault();
900
- }
901
- }
902
- }),
903
- /* Leave a ghost div to avoid setting hover to false when transitioning out */
904
- ghostBeforeProps: normalize.element({
905
- "data-ghost": "before",
906
- style: getGhostBeforeStyle(state.context, visible)
907
- }),
908
- /* Needed to avoid setting hover to false when in between toasts */
909
- ghostAfterProps: normalize.element({
910
- "data-ghost": "after",
911
- style: getGhostAfterStyle(state.context, visible)
912
- }),
913
- titleProps: normalize.element({
914
- ...parts.title.attrs,
915
- id: dom.getTitleId(state.context)
916
- }),
917
- descriptionProps: normalize.element({
918
- ...parts.description.attrs,
919
- id: dom.getDescriptionId(state.context)
920
- }),
921
- actionTriggerProps: normalize.button({
922
- ...parts.actionTrigger.attrs,
923
- type: "button",
924
- onClick(event) {
925
- if (event.defaultPrevented)
926
- return;
927
- send("DISMISS");
928
- }
929
- }),
930
- closeTriggerProps: normalize.button({
931
- id: dom.getCloseTriggerId(state.context),
932
- ...parts.closeTrigger.attrs,
933
- type: "button",
934
- "aria-label": "Dismiss notification",
935
- onClick(event) {
936
- if (event.defaultPrevented)
937
- return;
938
- send("DISMISS");
939
- }
940
- })
941
- };
942
- }
943
-
944
- // src/index.ts
945
- var group = {
946
- connect: groupConnect,
947
- machine: groupMachine
948
- };
949
- // Annotate the CommonJS export names for ESM import in node:
950
- 0 && (module.exports = {
951
- anatomy,
952
- connect,
953
- createMachine,
954
- group
955
- });
1
+ "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var src_exports={};__export(src_exports,{anatomy:()=>anatomy,connect:()=>connect,createMachine:()=>createToastMachine,group:()=>group});module.exports=__toCommonJS(src_exports);var import_core=require("@zag-js/core");var import_dom_query3=require("@zag-js/dom-query");var import_utils=require("@zag-js/utils");var import_anatomy=require("@zag-js/anatomy");var anatomy=(0,import_anatomy.createAnatomy)("toast").parts("group","root","title","description","actionTrigger","closeTrigger");var parts=anatomy.build();var import_dom_query=require("@zag-js/dom-query");var dom=(0,import_dom_query.createScope)({getRegionId:placement=>`toast-group:${placement}`,getRegionEl:(ctx,placement)=>dom.getById(ctx,`toast-group:${placement}`),getRootId:ctx=>`toast:${ctx.id}`,getRootEl:ctx=>dom.getById(ctx,dom.getRootId(ctx)),getTitleId:ctx=>`toast:${ctx.id}:title`,getDescriptionId:ctx=>`toast:${ctx.id}:description`,getCloseTriggerId:ctx=>`toast${ctx.id}:close`});var import_dom_query2=require("@zag-js/dom-query");function getToastsByPlacement(toasts,placement){return toasts.filter(toast=>toast.state.context.placement===placement)}var defaultTimeouts={info:5e3,error:5e3,success:2e3,loading:Infinity,DEFAULT:5e3};function getToastDuration(duration,type){return duration??defaultTimeouts[type]??defaultTimeouts.DEFAULT}function getGroupPlacementStyle(ctx,placement){const offset=ctx.offsets;const computedOffset=typeof offset==="string"?{left:offset,right:offset,bottom:offset,top:offset}:offset;const rtl=ctx.dir==="rtl";const computedPlacement=placement.replace("-start",rtl?"-right":"-left").replace("-end",rtl?"-left":"-right");const isRighty=computedPlacement.includes("right");const isLefty=computedPlacement.includes("left");const styles={position:"fixed",pointerEvents:ctx.count>0?void 0:"none",display:"flex",flexDirection:"column","--gap":`${ctx.gap}px`,"--first-height":`${ctx.heights[0]?.height||0}px`,zIndex:import_dom_query2.MAX_Z_INDEX};let alignItems="center";if(isRighty)alignItems="flex-end";if(isLefty)alignItems="flex-start";styles.alignItems=alignItems;if(computedPlacement.includes("top")){const offset2=computedOffset.top;styles.top=`max(env(safe-area-inset-top, 0px), ${offset2})`}if(computedPlacement.includes("bottom")){const offset2=computedOffset.bottom;styles.bottom=`max(env(safe-area-inset-bottom, 0px), ${offset2})`}if(!computedPlacement.includes("left")){const offset2=computedOffset.right;styles.insetInlineEnd=`calc(env(safe-area-inset-right, 0px) + ${offset2})`}if(!computedPlacement.includes("right")){const offset2=computedOffset.left;styles.insetInlineStart=`calc(env(safe-area-inset-left, 0px) + ${offset2})`}return styles}function getPlacementStyle(ctx,visible){const[side]=ctx.placement.split("-");const sibling=!ctx.frontmost;const overlap=!ctx.stacked;const styles={position:"absolute",pointerEvents:"auto","--opacity":"0","--remove-delay":`${ctx.removeDelay}ms`,"--duration":`${ctx.type==="loading"?Number.MAX_SAFE_INTEGER:ctx.duration}ms`,"--initial-height":`${ctx.height}px`,"--offset":`${ctx.offset}px`,"--index":ctx.index,"--z-index":ctx.zIndex,"--lift-amount":"calc(var(--lift) * var(--gap))","--y":"100%","--x":"0"};const assign=overrides=>Object.assign(styles,overrides);if(side==="top"){assign({top:"0","--sign":"-1","--y":"-100%","--lift":"1"})}else if(side==="bottom"){assign({bottom:"0","--sign":"1","--y":"100%","--lift":"-1"})}if(ctx.mounted){assign({"--y":"0","--opacity":"1"});if(ctx.stacked){assign({"--y":"calc(var(--lift) * var(--offset))","--height":"var(--initial-height)"})}}if(!visible){assign({"--opacity":"0",pointerEvents:"none"})}if(sibling&&overlap){assign({"--base-scale":"var(--index) * 0.05 + 1","--y":"calc(var(--lift-amount) * var(--index))","--scale":"calc(-1 * var(--base-scale))","--height":"var(--first-height)"});if(!visible){assign({"--y":"calc(var(--sign) * 40%)"})}}if(sibling&&ctx.stacked&&!visible){assign({"--y":"calc(var(--lift) * var(--offset) + var(--lift) * -100%)"})}if(ctx.frontmost&&!visible){assign({"--y":"calc(var(--lift) * -100%)"})}return styles}function getGhostBeforeStyle(ctx,visible){const styles={position:"absolute",inset:"0",scale:"1 2",pointerEvents:visible?"none":"auto"};const assign=overrides=>Object.assign(styles,overrides);if(ctx.frontmost&&!visible){assign({height:"calc(var(--initial-height) + 80%)"})}return styles}function getGhostAfterStyle(_ctx,_visible){return{position:"absolute",left:"0",height:"calc(var(--gap) + 2px)",bottom:"100%",width:"100%"}}function groupConnect(serviceOrState,send,normalize){function getState(){const result=(0,import_core.isMachine)(serviceOrState)?serviceOrState.getState():serviceOrState;return result}function getToastsByPlacementImpl(placement){return getToastsByPlacement(getState().context.toasts,placement)}function isVisible(id){const toasts=getState().context.toasts;if(!toasts.length)return false;return!!toasts.find(toast=>toast.id==id)}function create(options){const uid=`toast:${(0,import_utils.uuid)()}`;const id=options.id?options.id:uid;if(isVisible(id))return id;send({type:"ADD_TOAST",toast:{...options,id}});return id}function update(id,options){if(!isVisible(id))return id;send({type:"UPDATE_TOAST",id,toast:options});return id}function upsert(options){const{id}=options;const visible=id?isVisible(id):false;if(visible&&id!=null){return update(id,options)}else{return create(options)}}function dismiss(id){if(id==null){send("DISMISS_ALL")}else if(isVisible(id)){send({type:"DISMISS_TOAST",id})}}return{getCount(){return getState().context.count},getPlacements(){const toasts=getState().context.toasts;const placements=toasts.map(toast=>toast.state.context.placement);return Array.from(new Set(placements))},getToastsByPlacement:getToastsByPlacementImpl,isVisible,create,update,upsert,dismiss,remove(id){if(id==null){send("REMOVE_ALL")}else if(isVisible(id)){send({type:"REMOVE_TOAST",id})}},dismissByPlacement(placement){const toasts=getToastsByPlacementImpl(placement);toasts.forEach(toast=>dismiss(toast.id))},loading(options){return upsert({...options,type:"loading"})},success(options){return upsert({...options,type:"success"})},error(options){return upsert({...options,type:"error"})},promise(promise,options,shared={}){const id=upsert({...shared,...options.loading,type:"loading"});(0,import_utils.runIfFn)(promise).then(response=>{const successOptions=(0,import_utils.runIfFn)(options.success,response);upsert({...shared,...successOptions,id,type:"success"})}).catch(error=>{const errorOptions=(0,import_utils.runIfFn)(options.error,error);upsert({...shared,...errorOptions,id,type:"error"})}).finally(()=>{options.finally?.()});return id},pause(id){if(id==null){send("PAUSE_ALL")}else if(isVisible(id)){send({type:"PAUSE_TOAST",id})}},resume(id){if(id==null){send("RESUME_ALL")}else if(isVisible(id)){send({type:"RESUME_TOAST",id})}},getGroupProps(options){const{placement,label="Notifications"}=options;const state=getState();const hotkeyLabel=state.context.hotkey.join("+").replace(/Key/g,"").replace(/Digit/g,"");const[side,align="center"]=placement.split("-");return normalize.element({...parts.group.attrs,dir:state.context.dir,tabIndex:-1,"aria-label":`${placement} ${label} ${hotkeyLabel}`,id:dom.getRegionId(placement),"data-placement":placement,"data-side":side,"data-align":align,"aria-live":"polite",role:"region",style:getGroupPlacementStyle(state.context,placement),onMouseMove(){send({type:"REGION.POINTER_ENTER",placement})},onMouseLeave(){send({type:"REGION.POINTER_LEAVE",placement})},onFocus(event){send({type:"REGION.FOCUS",target:event.relatedTarget})},onBlur(event){if(state.context.isFocusWithin&&!(0,import_dom_query3.contains)(event.currentTarget,event.relatedTarget)){send({type:"REGION.BLUR"})}}})},subscribe(fn){const state=getState();return(0,import_core.subscribe)(state.context.toasts,()=>{const toasts=getToastsByPlacementImpl(state.context.placement);const contexts=toasts.map(toast=>toast.getState().context);fn(contexts)})}}}var import_core3=require("@zag-js/core");var import_dismissable=require("@zag-js/dismissable");var import_dom_event=require("@zag-js/dom-event");var import_utils3=require("@zag-js/utils");var import_core2=require("@zag-js/core");var import_dom_query4=require("@zag-js/dom-query");var import_utils2=require("@zag-js/utils");var{not,and,or}=import_core2.guards;function createToastMachine(options){const{type="info",duration,id="1",placement="bottom",removeDelay=200,...restProps}=options;const ctx=(0,import_utils2.compact)(restProps);const computedDuration=getToastDuration(duration,type);return(0,import_core2.createMachine)({id,context:{id,type,remaining:computedDuration,duration:computedDuration,removeDelay,createdAt:Date.now(),placement,...ctx,height:0,offset:0,frontmost:false,mounted:false,index:-1,zIndex:0},initial:type==="loading"?"visible:persist":"visible",on:{UPDATE:[{guard:and("hasTypeChanged","isChangingToLoading"),target:"visible:persist",actions:["setContext"]},{guard:or("hasDurationChanged","hasTypeChanged"),target:"visible:updating",actions:["setContext"]},{actions:["setContext"]}],MEASURE:{actions:["measureHeight"]}},entry:["invokeOnVisible"],activities:["trackHeight"],states:{"visible:updating":{tags:["visible","updating"],after:{0:"visible"}},"visible:persist":{tags:["visible","paused"],on:{RESUME:{guard:not("isLoadingType"),target:"visible",actions:["setCreatedAt"]},DISMISS:"dismissing"}},visible:{tags:["visible"],after:{VISIBLE_DURATION:"dismissing"},on:{DISMISS:"dismissing",PAUSE:{target:"visible:persist",actions:"setRemainingDuration"}}},dismissing:{entry:"invokeOnDismiss",after:{REMOVE_DELAY:{target:"unmounted",actions:"notifyParentToRemove"}}},unmounted:{entry:"invokeOnUnmount",type:"final"}}},{activities:{trackHeight(ctx2,_evt,{self}){let cleanup;(0,import_dom_query4.raf)(()=>{const rootEl=dom.getRootEl(ctx2);if(!rootEl)return;ctx2.mounted=true;const ghosts=(0,import_dom_query4.queryAll)(rootEl,"[data-ghost]");(0,import_utils2.warn)(ghosts.length!==2,"[toast] No ghost element found in toast. Render the `ghostBefore` and `ghostAfter` elements");const syncHeight=()=>{const originalHeight=rootEl.style.height;rootEl.style.height="auto";const newHeight=rootEl.getBoundingClientRect().height;rootEl.style.height=originalHeight;ctx2.height=newHeight;self.sendParent({type:"UPDATE_HEIGHT",id:self.id,height:newHeight,placement:ctx2.placement})};syncHeight();const win=dom.getWin(ctx2);const observer=new win.MutationObserver(syncHeight);observer.observe(rootEl,{childList:true,subtree:true,characterData:true});cleanup=()=>observer.disconnect()});return()=>cleanup?.()}},guards:{isChangingToLoading:(_,evt)=>evt.toast?.type==="loading",isLoadingType:ctx2=>ctx2.type==="loading",hasTypeChanged:(ctx2,evt)=>evt.toast?.type!=null&&evt.toast.type!==ctx2.type,hasDurationChanged:(ctx2,evt)=>evt.toast?.duration!=null&&evt.toast.duration!==ctx2.duration},delays:{VISIBLE_DURATION:ctx2=>ctx2.remaining,REMOVE_DELAY:ctx2=>ctx2.removeDelay},actions:{measureHeight(ctx2,_evt,{self}){(0,import_dom_query4.raf)(()=>{const rootEl=dom.getRootEl(ctx2);if(!rootEl)return;ctx2.mounted=true;const originalHeight=rootEl.style.height;rootEl.style.height="auto";const newHeight=rootEl.getBoundingClientRect().height;rootEl.style.height=originalHeight;ctx2.height=newHeight;self.sendParent({type:"UPDATE_HEIGHT",id:self.id,height:newHeight,placement:ctx2.placement})})},setRemainingDuration(ctx2){ctx2.remaining-=Date.now()-ctx2.createdAt},setCreatedAt(ctx2){ctx2.createdAt=Date.now()},notifyParentToRemove(_ctx,_evt,{self}){self.sendParent({type:"REMOVE_TOAST",id:self.id})},invokeOnDismiss(ctx2){ctx2.onStatusChange?.({status:"dismissing"})},invokeOnUnmount(ctx2){ctx2.onStatusChange?.({status:"unmounted"})},invokeOnVisible(ctx2){ctx2.onStatusChange?.({status:"visible"})},setContext(ctx2,evt){const duration2=evt.toast?.duration;const type2=evt.toast?.type??ctx2.type;const computedDuration2=getToastDuration(duration2,type2);Object.assign(ctx2,{...evt.toast,duration:computedDuration2,remaining:computedDuration2})}}})}function groupMachine(userContext){const ctx=(0,import_utils3.compact)(userContext);return(0,import_core3.createMachine)({id:"toaster",initial:ctx.overlap?"overlap":"stack",context:{dir:"ltr",max:Number.MAX_SAFE_INTEGER,gap:16,pauseOnPageIdle:false,hotkey:["altKey","KeyT"],offsets:"1rem",placement:"bottom",removeDelay:200,...ctx,toasts:[],lastFocusedEl:null,isFocusWithin:false,heights:[]},computed:{count:ctx2=>ctx2.toasts.length},activities:["trackDocumentVisibility","trackHotKeyPress"],watch:{toasts:["collapsedIfEmpty","setDismissableBranch"]},exit:["removeToasts","clearDismissableBranch","clearLastFocusedEl"],on:{PAUSE_TOAST:{actions:["pauseToast"]},PAUSE_ALL:{actions:["pauseToasts"]},RESUME_TOAST:{actions:["resumeToast"]},RESUME_ALL:{actions:["resumeToasts"]},ADD_TOAST:{guard:"isWithinRange",actions:["createToast","syncToastIndex"]},UPDATE_TOAST:{actions:["updateToast"]},DISMISS_TOAST:{actions:["dismissToast"]},DISMISS_ALL:{actions:["dismissToasts"]},REMOVE_TOAST:{actions:["removeToast","syncToastIndex","syncToastOffset"]},REMOVE_ALL:{actions:["removeToasts"]},UPDATE_HEIGHT:{actions:["syncHeights","syncToastOffset"]},"DOC.HOTKEY":{actions:["focusRegionEl"]},"REGION.BLUR":[{guard:"isOverlapping",target:"overlap",actions:["resumeToasts","restoreLastFocusedEl"]},{actions:["resumeToasts","restoreLastFocusedEl"]}]},states:{stack:{entry:["expandToasts"],on:{"REGION.POINTER_LEAVE":[{guard:"isOverlapping",target:"overlap",actions:["resumeToasts"]},{actions:["resumeToasts"]}],"REGION.OVERLAP":{target:"overlap"},"REGION.FOCUS":{actions:["setLastFocusedEl","pauseToasts"]},"REGION.POINTER_ENTER":{actions:["pauseToasts"]}}},overlap:{entry:["collapseToasts"],on:{"REGION.STACK":{target:"stack"},"REGION.POINTER_ENTER":{target:"stack",actions:["pauseToasts"]},"REGION.FOCUS":{target:"stack",actions:["setLastFocusedEl","pauseToasts"]}}}}},{guards:{isWithinRange:ctx2=>ctx2.toasts.length<ctx2.max,isOverlapping:ctx2=>!!ctx2.overlap},activities:{trackHotKeyPress(ctx2,_evt,{send}){const handleKeyDown=event=>{const isHotkeyPressed=ctx2.hotkey.every(key=>event[key]||event.code===key);if(!isHotkeyPressed)return;send({type:"DOC.HOTKEY"})};return(0,import_dom_event.addDomEvent)(document,"keydown",handleKeyDown,{capture:true})},trackDocumentVisibility(ctx2,_evt,{send}){if(!ctx2.pauseOnPageIdle)return;const doc=dom.getDoc(ctx2);return(0,import_dom_event.addDomEvent)(doc,"visibilitychange",()=>{send(doc.visibilityState==="hidden"?"PAUSE_ALL":"RESUME_ALL")})}},actions:{setDismissableBranch(ctx2){const currentToasts=getToastsByPlacement(ctx2.toasts,ctx2.placement);const hasToasts=currentToasts.length>0;if(!hasToasts){ctx2._cleanup?.();return}if(hasToasts&&ctx2._cleanup){return}const groupEl=()=>dom.getRegionEl(ctx2,ctx2.placement);ctx2._cleanup=(0,import_dismissable.trackDismissableBranch)(groupEl,{defer:true})},clearDismissableBranch(ctx2){ctx2._cleanup?.()},focusRegionEl(ctx2){queueMicrotask(()=>{dom.getRegionEl(ctx2,ctx2.placement)?.focus()})},expandToasts(ctx2){each(ctx2,toast=>{toast.state.context.stacked=true})},collapseToasts(ctx2){each(ctx2,toast=>{toast.state.context.stacked=false})},collapsedIfEmpty(ctx2,_evt,{send}){if(!ctx2.overlap||ctx2.toasts.length>1)return;send("REGION.OVERLAP")},pauseToast(_ctx,evt,{self}){self.sendChild("PAUSE",evt.id)},pauseToasts(ctx2){ctx2.toasts.forEach(toast=>toast.send("PAUSE"))},resumeToast(_ctx,evt,{self}){self.sendChild("RESUME",evt.id)},resumeToasts(ctx2){ctx2.toasts.forEach(toast=>toast.send("RESUME"))},measureToasts(ctx2){ctx2.toasts.forEach(toast=>toast.send("MEASURE"))},createToast(ctx2,evt,{self,getState}){const options={placement:ctx2.placement,duration:ctx2.duration,removeDelay:ctx2.removeDelay,...evt.toast,dir:ctx2.dir,getRootNode:ctx2.getRootNode,stacked:getState().matches("stack")};const toast=createToastMachine(options);const actor=self.spawn(toast);ctx2.toasts=[actor,...ctx2.toasts]},updateToast(_ctx,evt,{self}){self.sendChild({type:"UPDATE",toast:evt.toast},evt.id)},dismissToast(_ctx,evt,{self}){self.sendChild("DISMISS",evt.id)},dismissToasts(ctx2){ctx2.toasts.forEach(toast=>toast.send("DISMISS"))},removeToast(ctx2,evt,{self}){self.stopChild(evt.id);ctx2.toasts=ctx2.toasts.filter(toast=>toast.id!==evt.id);ctx2.heights=ctx2.heights.filter(height=>height.id!==evt.id)},removeToasts(ctx2,_evt,{self}){ctx2.toasts.forEach(toast=>self.stopChild(toast.id));ctx2.toasts=[];ctx2.heights=[]},syncHeights(ctx2,evt){const existing=ctx2.heights.find(height=>height.id===evt.id);if(existing){existing.height=evt.height;existing.placement=evt.placement}else{const newHeight={id:evt.id,height:evt.height,placement:evt.placement};ctx2.heights=[newHeight,...ctx2.heights]}},syncToastIndex(ctx2){each(ctx2,(toast,index,toasts)=>{toast.state.context.index=index;toast.state.context.frontmost=index===0;toast.state.context.zIndex=toasts.length-index})},syncToastOffset(ctx2,evt){const placement=evt.placement??ctx2.placement;each({...ctx2,placement},toast=>{const heightIndex=Math.max(ctx2.heights.findIndex(height=>height.id===toast.id),0);const toastsHeightBefore=ctx2.heights.reduce((prev,curr,reducerIndex)=>{if(reducerIndex>=heightIndex)return prev;return prev+curr.height},0);toast.state.context.offset=heightIndex*ctx2.gap+toastsHeightBefore})},setLastFocusedEl(ctx2,evt){if(ctx2.isFocusWithin||!evt.target)return;ctx2.isFocusWithin=true;ctx2.lastFocusedEl=(0,import_core3.ref)(evt.target)},restoreLastFocusedEl(ctx2){ctx2.isFocusWithin=false;if(!ctx2.lastFocusedEl)return;ctx2.lastFocusedEl.focus({preventScroll:true});ctx2.lastFocusedEl=null},clearLastFocusedEl(ctx2){if(!ctx2.lastFocusedEl)return;ctx2.lastFocusedEl.focus({preventScroll:true});ctx2.lastFocusedEl=null;ctx2.isFocusWithin=false}}})}function each(ctx,fn){const currentToasts=getToastsByPlacement(ctx.toasts,ctx.placement);currentToasts.forEach(fn)}var import_dom_query5=require("@zag-js/dom-query");function connect(state,send,normalize){const visible=state.hasTag("visible");const paused=state.hasTag("paused");const placement=state.context.placement;const type=state.context.type;const[side,align="center"]=placement.split("-");return{type,title:state.context.title,description:state.context.description,placement,visible,paused,pause(){send("PAUSE")},resume(){send("RESUME")},dismiss(){send("DISMISS")},rootProps:normalize.element({...parts.root.attrs,dir:state.context.dir,id:dom.getRootId(state.context),"data-state":visible?"open":"closed","data-type":type,"data-placement":placement,"data-align":align,"data-side":side,"data-mounted":(0,import_dom_query5.dataAttr)(state.context.mounted),"data-paused":(0,import_dom_query5.dataAttr)(paused),"data-first":(0,import_dom_query5.dataAttr)(state.context.frontmost),"data-sibling":(0,import_dom_query5.dataAttr)(!state.context.frontmost),"data-stack":(0,import_dom_query5.dataAttr)(state.context.stacked),"data-overlap":(0,import_dom_query5.dataAttr)(!state.context.stacked),role:"status","aria-atomic":"true",tabIndex:0,style:getPlacementStyle(state.context,visible),onKeyDown(event){if(event.defaultPrevented)return;if(event.key=="Escape"){send("DISMISS");event.preventDefault()}}}),ghostBeforeProps:normalize.element({"data-ghost":"before",style:getGhostBeforeStyle(state.context,visible)}),ghostAfterProps:normalize.element({"data-ghost":"after",style:getGhostAfterStyle(state.context,visible)}),titleProps:normalize.element({...parts.title.attrs,id:dom.getTitleId(state.context)}),descriptionProps:normalize.element({...parts.description.attrs,id:dom.getDescriptionId(state.context)}),actionTriggerProps:normalize.button({...parts.actionTrigger.attrs,type:"button",onClick(event){if(event.defaultPrevented)return;send("DISMISS")}}),closeTriggerProps:normalize.button({id:dom.getCloseTriggerId(state.context),...parts.closeTrigger.attrs,type:"button","aria-label":"Dismiss notification",onClick(event){if(event.defaultPrevented)return;send("DISMISS")}})}}var group={connect:groupConnect,machine:groupMachine};0&&(module.exports={anatomy,connect,createMachine,group});
956
2
  //# sourceMappingURL=index.js.map