@zag-js/toast 0.10.5 → 0.11.0

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.mjs CHANGED
@@ -1,12 +1,625 @@
1
- import { isDom } from '@zag-js/dom-query';
2
- import { warn } from '@zag-js/utils';
3
- import { groupConnect, toaster } from './toast-group.connect.mjs';
4
- import { groupMachine } from './toast-group.machine.mjs';
5
- export { createToastMachine as createMachine } from './toast.machine.mjs';
6
- export { anatomy } from './toast.anatomy.mjs';
7
- export { connect } from './toast.connect.mjs';
8
-
9
- const group = {
1
+ // src/index.ts
2
+ import { isDom } from "@zag-js/dom-query";
3
+ import { warn } from "@zag-js/utils";
4
+
5
+ // src/toast-group.connect.ts
6
+ import { subscribe } from "@zag-js/core";
7
+ import { runIfFn, uuid } from "@zag-js/utils";
8
+
9
+ // src/toast.anatomy.ts
10
+ import { createAnatomy } from "@zag-js/anatomy";
11
+ var anatomy = createAnatomy("toast").parts("group", "root", "title", "description", "closeTrigger");
12
+ var parts = anatomy.build();
13
+
14
+ // src/toast.dom.ts
15
+ import { createScope } from "@zag-js/dom-query";
16
+ var dom = createScope({
17
+ getGroupId: (placement) => `toast-group:${placement}`,
18
+ getRootId: (ctx) => `toast:${ctx.id}`,
19
+ getTitleId: (ctx) => `toast:${ctx.id}:title`,
20
+ getDescriptionId: (ctx) => `toast:${ctx.id}:description`,
21
+ getCloseTriggerId: (ctx) => `toast${ctx.id}:close`,
22
+ getPortalId: (ctx) => `toast-portal:${ctx.id}`
23
+ });
24
+
25
+ // src/toast.utils.ts
26
+ function getToastsByPlacement(toasts) {
27
+ const result = {};
28
+ for (const toast of toasts) {
29
+ const placement = toast.state.context.placement;
30
+ result[placement] || (result[placement] = []);
31
+ result[placement].push(toast);
32
+ }
33
+ return result;
34
+ }
35
+ var defaultTimeouts = {
36
+ info: 5e3,
37
+ error: 5e3,
38
+ success: 2e3,
39
+ loading: Infinity,
40
+ custom: 5e3
41
+ };
42
+ function getToastDuration(duration, type) {
43
+ return duration ?? defaultTimeouts[type];
44
+ }
45
+ function getGroupPlacementStyle(ctx, placement) {
46
+ const offset = ctx.offsets;
47
+ const computedOffset = typeof offset === "string" ? { left: offset, right: offset, bottom: offset, top: offset } : offset;
48
+ const rtl = ctx.dir === "rtl";
49
+ const computedPlacement = placement.replace("-start", rtl ? "-right" : "-left").replace("-end", rtl ? "-left" : "-right");
50
+ const isRighty = computedPlacement.includes("right");
51
+ const isLefty = computedPlacement.includes("left");
52
+ const styles = {
53
+ position: "fixed",
54
+ pointerEvents: ctx.count > 0 ? void 0 : "none",
55
+ display: "flex",
56
+ flexDirection: "column",
57
+ "--toast-gutter": ctx.gutter,
58
+ zIndex: ctx.zIndex
59
+ };
60
+ let alignItems = "center";
61
+ if (isRighty)
62
+ alignItems = "flex-end";
63
+ if (isLefty)
64
+ alignItems = "flex-start";
65
+ styles.alignItems = alignItems;
66
+ if (computedPlacement.includes("top")) {
67
+ const offset2 = computedOffset.top;
68
+ styles.top = `calc(env(safe-area-inset-top, 0px) + ${offset2})`;
69
+ }
70
+ if (computedPlacement.includes("bottom")) {
71
+ const offset2 = computedOffset.bottom;
72
+ styles.bottom = `calc(env(safe-area-inset-bottom, 0px) + ${offset2})`;
73
+ }
74
+ if (!computedPlacement.includes("left")) {
75
+ const offset2 = computedOffset.right;
76
+ styles.right = `calc(env(safe-area-inset-right, 0px) + ${offset2})`;
77
+ }
78
+ if (!computedPlacement.includes("right")) {
79
+ const offset2 = computedOffset.left;
80
+ styles.left = `calc(env(safe-area-inset-left, 0px) + ${offset2})`;
81
+ }
82
+ return styles;
83
+ }
84
+
85
+ // src/toast-group.connect.ts
86
+ var toaster = {};
87
+ function groupConnect(state, send, normalize) {
88
+ const group2 = {
89
+ /**
90
+ * The total number of toasts
91
+ */
92
+ count: state.context.count,
93
+ /**
94
+ * The active toasts
95
+ */
96
+ toasts: state.context.toasts,
97
+ /**
98
+ * The active toasts by placement
99
+ */
100
+ toastsByPlacement: getToastsByPlacement(state.context.toasts),
101
+ /**
102
+ * Returns whether the toast id is visible
103
+ */
104
+ isVisible(id) {
105
+ if (!state.context.toasts.length)
106
+ return false;
107
+ return !!state.context.toasts.find((toast) => toast.id == id);
108
+ },
109
+ /**
110
+ * Function to create a toast.
111
+ */
112
+ create(options) {
113
+ const uid = `toast:${uuid()}`;
114
+ const id = options.id ? options.id : uid;
115
+ if (group2.isVisible(id))
116
+ return;
117
+ send({ type: "ADD_TOAST", toast: { ...options, id } });
118
+ return id;
119
+ },
120
+ /**
121
+ * Function to create or update a toast.
122
+ */
123
+ upsert(options) {
124
+ const { id } = options;
125
+ const isVisible = id ? group2.isVisible(id) : false;
126
+ if (isVisible && id != null) {
127
+ return group2.update(id, options);
128
+ } else {
129
+ return group2.create(options);
130
+ }
131
+ },
132
+ /**
133
+ * Function to dismiss a toast by id.
134
+ * If no id is provided, all toasts will be dismissed.
135
+ */
136
+ dismiss(id) {
137
+ if (id == null) {
138
+ send("DISMISS_ALL");
139
+ } else if (group2.isVisible(id)) {
140
+ send({ type: "DISMISS_TOAST", id });
141
+ }
142
+ },
143
+ /**
144
+ * Function to remove a toast by id.
145
+ * If no id is provided, all toasts will be removed.
146
+ */
147
+ remove(id) {
148
+ if (id == null) {
149
+ send("REMOVE_ALL");
150
+ } else if (group2.isVisible(id)) {
151
+ send({ type: "REMOVE_TOAST", id });
152
+ }
153
+ },
154
+ /**
155
+ * Function to dismiss all toasts by placement.
156
+ */
157
+ dismissByPlacement(placement) {
158
+ const toasts = group2.toastsByPlacement[placement];
159
+ if (toasts) {
160
+ toasts.forEach((toast) => group2.dismiss(toast.id));
161
+ }
162
+ },
163
+ /**
164
+ * Function to update a toast's options by id.
165
+ */
166
+ update(id, options) {
167
+ if (!group2.isVisible(id))
168
+ return;
169
+ send({ type: "UPDATE_TOAST", id, toast: options });
170
+ return id;
171
+ },
172
+ /**
173
+ * Function to create a loading toast.
174
+ */
175
+ loading(options) {
176
+ options.type = "loading";
177
+ return group2.upsert(options);
178
+ },
179
+ /**
180
+ * Function to create a success toast.
181
+ */
182
+ success(options) {
183
+ options.type = "success";
184
+ return group2.upsert(options);
185
+ },
186
+ /**
187
+ * Function to create an error toast.
188
+ */
189
+ error(options) {
190
+ options.type = "error";
191
+ return group2.upsert(options);
192
+ },
193
+ /**
194
+ * Function to create a toast from a promise.
195
+ * - When the promise resolves, the toast will be updated with the success options.
196
+ * - When the promise rejects, the toast will be updated with the error options.
197
+ */
198
+ promise(promise, options, shared = {}) {
199
+ const id = group2.loading({ ...shared, ...options.loading });
200
+ promise.then((response) => {
201
+ const successOptions = runIfFn(options.success, response);
202
+ group2.success({ ...shared, ...successOptions, id });
203
+ }).catch((error) => {
204
+ const errorOptions = runIfFn(options.error, error);
205
+ group2.error({ ...shared, ...errorOptions, id });
206
+ });
207
+ return promise;
208
+ },
209
+ /**
210
+ * Function to pause a toast by id.
211
+ */
212
+ pause(id) {
213
+ if (id == null) {
214
+ send("PAUSE_ALL");
215
+ } else if (group2.isVisible(id)) {
216
+ send({ type: "PAUSE_TOAST", id });
217
+ }
218
+ },
219
+ /**
220
+ * Function to resume a toast by id.
221
+ */
222
+ resume(id) {
223
+ if (id == null) {
224
+ send("RESUME_ALL");
225
+ } else if (group2.isVisible(id)) {
226
+ send({ type: "RESUME_TOAST", id });
227
+ }
228
+ },
229
+ getGroupProps(options) {
230
+ const { placement, label = "Notifications" } = options;
231
+ return normalize.element({
232
+ ...parts.group.attrs,
233
+ tabIndex: -1,
234
+ "aria-label": label,
235
+ id: dom.getGroupId(placement),
236
+ "data-placement": placement,
237
+ "aria-live": "polite",
238
+ role: "region",
239
+ style: getGroupPlacementStyle(state.context, placement)
240
+ });
241
+ },
242
+ subscribe(fn) {
243
+ return subscribe(state.context.toasts, () => fn(state.context.toasts));
244
+ }
245
+ };
246
+ Object.assign(toaster, group2);
247
+ return group2;
248
+ }
249
+
250
+ // src/toast-group.machine.ts
251
+ import { createMachine as createMachine2 } from "@zag-js/core";
252
+ import { MAX_Z_INDEX } from "@zag-js/dom-query";
253
+ import { compact as compact2 } from "@zag-js/utils";
254
+
255
+ // src/toast.machine.ts
256
+ import { createMachine, guards } from "@zag-js/core";
257
+ import { addDomEvent } from "@zag-js/dom-event";
258
+ import { compact } from "@zag-js/utils";
259
+ var { not, and, or } = guards;
260
+ function createToastMachine(options = {}) {
261
+ const { type = "info", duration, id = "toast", placement = "bottom", removeDelay = 0, ...restProps } = options;
262
+ const ctx = compact(restProps);
263
+ const computedDuration = getToastDuration(duration, type);
264
+ return createMachine(
265
+ {
266
+ id,
267
+ entry: "invokeOnOpen",
268
+ initial: type === "loading" ? "persist" : "active",
269
+ context: {
270
+ id,
271
+ type,
272
+ remaining: computedDuration,
273
+ duration: computedDuration,
274
+ removeDelay,
275
+ createdAt: Date.now(),
276
+ placement,
277
+ ...ctx
278
+ },
279
+ on: {
280
+ UPDATE: [
281
+ {
282
+ guard: and("hasTypeChanged", "isChangingToLoading"),
283
+ target: "persist",
284
+ actions: ["setContext", "invokeOnUpdate"]
285
+ },
286
+ {
287
+ guard: or("hasDurationChanged", "hasTypeChanged"),
288
+ target: "active:temp",
289
+ actions: ["setContext", "invokeOnUpdate"]
290
+ },
291
+ {
292
+ actions: ["setContext", "invokeOnUpdate"]
293
+ }
294
+ ]
295
+ },
296
+ states: {
297
+ "active:temp": {
298
+ tags: ["visible", "updating"],
299
+ after: {
300
+ 0: "active"
301
+ }
302
+ },
303
+ persist: {
304
+ tags: ["visible", "paused"],
305
+ activities: "trackDocumentVisibility",
306
+ on: {
307
+ RESUME: {
308
+ guard: not("isLoadingType"),
309
+ target: "active",
310
+ actions: ["setCreatedAt"]
311
+ },
312
+ DISMISS: "dismissing"
313
+ }
314
+ },
315
+ active: {
316
+ tags: ["visible"],
317
+ activities: "trackDocumentVisibility",
318
+ after: {
319
+ VISIBLE_DURATION: "dismissing"
320
+ },
321
+ on: {
322
+ DISMISS: "dismissing",
323
+ PAUSE: {
324
+ target: "persist",
325
+ actions: "setRemainingDuration"
326
+ }
327
+ }
328
+ },
329
+ dismissing: {
330
+ entry: "invokeOnClosing",
331
+ after: {
332
+ REMOVE_DELAY: {
333
+ target: "inactive",
334
+ actions: "notifyParentToRemove"
335
+ }
336
+ }
337
+ },
338
+ inactive: {
339
+ entry: "invokeOnClose",
340
+ type: "final"
341
+ }
342
+ }
343
+ },
344
+ {
345
+ activities: {
346
+ trackDocumentVisibility(ctx2, _evt, { send }) {
347
+ if (!ctx2.pauseOnPageIdle)
348
+ return;
349
+ const doc = dom.getDoc(ctx2);
350
+ return addDomEvent(doc, "visibilitychange", () => {
351
+ send(doc.visibilityState === "hidden" ? "PAUSE" : "RESUME");
352
+ });
353
+ }
354
+ },
355
+ guards: {
356
+ isChangingToLoading: (_, evt) => evt.toast?.type === "loading",
357
+ isLoadingType: (ctx2) => ctx2.type === "loading",
358
+ hasTypeChanged: (ctx2, evt) => evt.toast?.type !== ctx2.type,
359
+ hasDurationChanged: (ctx2, evt) => evt.toast?.duration !== ctx2.duration
360
+ },
361
+ delays: {
362
+ VISIBLE_DURATION: (ctx2) => ctx2.remaining,
363
+ REMOVE_DELAY: (ctx2) => ctx2.removeDelay
364
+ },
365
+ actions: {
366
+ setRemainingDuration(ctx2) {
367
+ ctx2.remaining -= Date.now() - ctx2.createdAt;
368
+ },
369
+ setCreatedAt(ctx2) {
370
+ ctx2.createdAt = Date.now();
371
+ },
372
+ notifyParentToRemove(_ctx, _evt, { self }) {
373
+ self.sendParent({ type: "REMOVE_TOAST", id: self.id });
374
+ },
375
+ invokeOnClosing(ctx2) {
376
+ ctx2.onClosing?.();
377
+ },
378
+ invokeOnClose(ctx2) {
379
+ ctx2.onClose?.();
380
+ },
381
+ invokeOnOpen(ctx2) {
382
+ ctx2.onOpen?.();
383
+ },
384
+ invokeOnUpdate(ctx2) {
385
+ ctx2.onUpdate?.();
386
+ },
387
+ setContext(ctx2, evt) {
388
+ const { duration: duration2, type: type2 } = evt.toast;
389
+ const time = getToastDuration(duration2, type2);
390
+ Object.assign(ctx2, { ...evt.toast, duration: time, remaining: time });
391
+ }
392
+ }
393
+ }
394
+ );
395
+ }
396
+
397
+ // src/toast-group.machine.ts
398
+ function groupMachine(userContext) {
399
+ const ctx = compact2(userContext);
400
+ return createMachine2({
401
+ id: "toaster",
402
+ initial: "active",
403
+ context: {
404
+ dir: "ltr",
405
+ max: Number.MAX_SAFE_INTEGER,
406
+ toasts: [],
407
+ gutter: "1rem",
408
+ zIndex: MAX_Z_INDEX,
409
+ pauseOnPageIdle: false,
410
+ pauseOnInteraction: true,
411
+ offsets: { left: "0px", right: "0px", top: "0px", bottom: "0px" },
412
+ ...ctx
413
+ },
414
+ computed: {
415
+ count: (ctx2) => ctx2.toasts.length
416
+ },
417
+ on: {
418
+ SETUP: {},
419
+ PAUSE_TOAST: {
420
+ actions: (_ctx, evt, { self }) => {
421
+ self.sendChild("PAUSE", evt.id);
422
+ }
423
+ },
424
+ PAUSE_ALL: {
425
+ actions: (ctx2) => {
426
+ ctx2.toasts.forEach((toast) => toast.send("PAUSE"));
427
+ }
428
+ },
429
+ RESUME_TOAST: {
430
+ actions: (_ctx, evt, { self }) => {
431
+ self.sendChild("RESUME", evt.id);
432
+ }
433
+ },
434
+ RESUME_ALL: {
435
+ actions: (ctx2) => {
436
+ ctx2.toasts.forEach((toast) => toast.send("RESUME"));
437
+ }
438
+ },
439
+ ADD_TOAST: {
440
+ guard: (ctx2) => ctx2.toasts.length < ctx2.max,
441
+ actions: (ctx2, evt, { self }) => {
442
+ const options = {
443
+ ...evt.toast,
444
+ pauseOnPageIdle: ctx2.pauseOnPageIdle,
445
+ pauseOnInteraction: ctx2.pauseOnInteraction,
446
+ dir: ctx2.dir,
447
+ getRootNode: ctx2.getRootNode
448
+ };
449
+ const toast = createToastMachine(options);
450
+ const actor = self.spawn(toast);
451
+ ctx2.toasts.push(actor);
452
+ }
453
+ },
454
+ UPDATE_TOAST: {
455
+ actions: (_ctx, evt, { self }) => {
456
+ self.sendChild({ type: "UPDATE", toast: evt.toast }, evt.id);
457
+ }
458
+ },
459
+ DISMISS_TOAST: {
460
+ actions: (_ctx, evt, { self }) => {
461
+ self.sendChild("DISMISS", evt.id);
462
+ }
463
+ },
464
+ DISMISS_ALL: {
465
+ actions: (ctx2) => {
466
+ ctx2.toasts.forEach((toast) => toast.send("DISMISS"));
467
+ }
468
+ },
469
+ REMOVE_TOAST: {
470
+ actions: (ctx2, evt, { self }) => {
471
+ self.stopChild(evt.id);
472
+ const index = ctx2.toasts.findIndex((toast) => toast.id === evt.id);
473
+ ctx2.toasts.splice(index, 1);
474
+ }
475
+ },
476
+ REMOVE_ALL: {
477
+ actions: (ctx2, _evt, { self }) => {
478
+ ctx2.toasts.forEach((toast) => self.stopChild(toast.id));
479
+ while (ctx2.toasts.length)
480
+ ctx2.toasts.pop();
481
+ }
482
+ }
483
+ }
484
+ });
485
+ }
486
+
487
+ // src/toast.connect.ts
488
+ import { dataAttr } from "@zag-js/dom-query";
489
+ function connect(state, send, normalize) {
490
+ const isVisible = state.hasTag("visible");
491
+ const isPaused = state.hasTag("paused");
492
+ const pauseOnInteraction = state.context.pauseOnInteraction;
493
+ const placement = state.context.placement;
494
+ return {
495
+ /**
496
+ * The type of the toast.
497
+ */
498
+ type: state.context.type,
499
+ /**
500
+ * The title of the toast.
501
+ */
502
+ title: state.context.title,
503
+ /**
504
+ * The description of the toast.
505
+ */
506
+ description: state.context.description,
507
+ /**
508
+ * The current placement of the toast.
509
+ */
510
+ placement,
511
+ /**
512
+ * Whether the toast is visible.
513
+ */
514
+ isVisible,
515
+ /**
516
+ * Whether the toast is paused.
517
+ */
518
+ isPaused,
519
+ /**
520
+ * Whether the toast is in RTL mode.
521
+ */
522
+ isRtl: state.context.dir === "rtl",
523
+ /**
524
+ * Function to pause the toast (keeping it visible).
525
+ */
526
+ pause() {
527
+ send("PAUSE");
528
+ },
529
+ /**
530
+ * Function to resume the toast dismissing.
531
+ */
532
+ resume() {
533
+ send("RESUME");
534
+ },
535
+ /**
536
+ * Function to instantly dismiss the toast.
537
+ */
538
+ dismiss() {
539
+ send("DISMISS");
540
+ },
541
+ /**
542
+ * Function render the toast in the DOM (based on the defined `render` property)
543
+ */
544
+ render() {
545
+ return state.context.render?.({
546
+ id: state.context.id,
547
+ type: state.context.type,
548
+ duration: state.context.duration,
549
+ title: state.context.title,
550
+ placement: state.context.placement,
551
+ description: state.context.description,
552
+ dismiss() {
553
+ send("DISMISS");
554
+ }
555
+ });
556
+ },
557
+ rootProps: normalize.element({
558
+ ...parts.root.attrs,
559
+ dir: state.context.dir,
560
+ id: dom.getRootId(state.context),
561
+ "data-open": dataAttr(isVisible),
562
+ "data-type": state.context.type,
563
+ "data-placement": placement,
564
+ role: "status",
565
+ "aria-atomic": "true",
566
+ tabIndex: 0,
567
+ style: {
568
+ position: "relative",
569
+ pointerEvents: "auto",
570
+ margin: "calc(var(--toast-gutter) / 2)",
571
+ "--remove-delay": `${state.context.removeDelay}ms`,
572
+ "--duration": `${state.context.duration}ms`
573
+ },
574
+ onKeyDown(event) {
575
+ if (event.key == "Escape") {
576
+ send("DISMISS");
577
+ event.preventDefault();
578
+ }
579
+ },
580
+ onFocus() {
581
+ if (pauseOnInteraction) {
582
+ send("PAUSE");
583
+ }
584
+ },
585
+ onBlur() {
586
+ if (pauseOnInteraction) {
587
+ send("RESUME");
588
+ }
589
+ },
590
+ onPointerEnter() {
591
+ if (pauseOnInteraction) {
592
+ send("PAUSE");
593
+ }
594
+ },
595
+ onPointerLeave() {
596
+ if (pauseOnInteraction) {
597
+ send("RESUME");
598
+ }
599
+ }
600
+ }),
601
+ titleProps: normalize.element({
602
+ ...parts.title.attrs,
603
+ id: dom.getTitleId(state.context)
604
+ }),
605
+ descriptionProps: normalize.element({
606
+ ...parts.description.attrs,
607
+ id: dom.getDescriptionId(state.context)
608
+ }),
609
+ closeTriggerProps: normalize.button({
610
+ id: dom.getCloseTriggerId(state.context),
611
+ ...parts.closeTrigger.attrs,
612
+ type: "button",
613
+ "aria-label": "Dismiss notification",
614
+ onClick() {
615
+ send("DISMISS");
616
+ }
617
+ })
618
+ };
619
+ }
620
+
621
+ // src/index.ts
622
+ var group = {
10
623
  connect: groupConnect,
11
624
  machine: groupMachine
12
625
  };
@@ -17,5 +630,11 @@ function api() {
17
630
  return toaster;
18
631
  }
19
632
  }
20
-
21
- export { api, group };
633
+ export {
634
+ anatomy,
635
+ api,
636
+ connect,
637
+ createToastMachine as createMachine,
638
+ group
639
+ };
640
+ //# sourceMappingURL=index.mjs.map