@zag-js/toast 0.2.5 → 0.2.7

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