@zag-js/toast 1.46.0 → 1.47.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.
@@ -79,11 +79,11 @@ var groupMachine = createMachine({
79
79
  overlap: ({ prop }) => prop("store").attrs.overlap,
80
80
  placement: ({ prop }) => prop("store").attrs.placement
81
81
  },
82
- effects: ["subscribeToStore", "trackDocumentVisibility", "trackHotKeyPress"],
82
+ effects: ["subscribeToStore", "subscribeToLayout", "trackDocumentVisibility", "trackHotKeyPress"],
83
83
  watch({ track, context, action }) {
84
84
  track([() => context.hash("toasts")], () => {
85
85
  queueMicrotask(() => {
86
- action(["collapsedIfEmpty", "setDismissableBranch"]);
86
+ action(["collapsedIfEmpty", "setDismissableBranch", "resetInteractionIfEmpty"]);
87
87
  });
88
88
  });
89
89
  },
@@ -102,7 +102,7 @@ var groupMachine = createMachine({
102
102
  {
103
103
  guard: and("isOverlapping", "isPointerOut"),
104
104
  target: "overlap",
105
- actions: ["collapseToasts", "resumeToasts", "restoreFocusIfPointerOut"]
105
+ actions: ["resumeToasts", "restoreFocusIfPointerOut"]
106
106
  },
107
107
  {
108
108
  guard: "isPointerOut",
@@ -113,6 +113,9 @@ var groupMachine = createMachine({
113
113
  actions: ["clearFocusWithin"]
114
114
  }
115
115
  ],
116
+ "TOAST.DISMISS": {
117
+ actions: ["moveFocusOnDismiss"]
118
+ },
116
119
  "TOAST.REMOVE": {
117
120
  actions: ["removeToast", "removeHeight", "ignoreMouseEventsTemporarily"]
118
121
  },
@@ -127,15 +130,14 @@ var groupMachine = createMachine({
127
130
  {
128
131
  guard: "isOverlapping",
129
132
  target: "overlap",
130
- actions: ["clearPointerWithin", "resumeToasts", "collapseToasts"]
133
+ actions: ["clearPointerWithin", "resumeToasts"]
131
134
  },
132
135
  {
133
136
  actions: ["clearPointerWithin", "resumeToasts"]
134
137
  }
135
138
  ],
136
139
  "REGION.OVERLAP": {
137
- target: "overlap",
138
- actions: ["collapseToasts"]
140
+ target: "overlap"
139
141
  },
140
142
  "REGION.FOCUS": {
141
143
  actions: ["setLastFocusedEl", "pauseToasts"]
@@ -148,16 +150,18 @@ var groupMachine = createMachine({
148
150
  overlap: {
149
151
  on: {
150
152
  "REGION.STACK": {
151
- target: "stack",
152
- actions: ["expandToasts"]
153
+ target: "stack"
153
154
  },
154
155
  "REGION.POINTER_ENTER": {
155
156
  target: "stack",
156
- actions: ["setPointerWithin", "pauseToasts", "expandToasts"]
157
+ actions: ["setPointerWithin", "pauseToasts"]
158
+ },
159
+ "REGION.POINTER_LEAVE": {
160
+ actions: ["clearPointerWithin", "resumeToasts"]
157
161
  },
158
162
  "REGION.FOCUS": {
159
163
  target: "stack",
160
- actions: ["setLastFocusedEl", "pauseToasts", "expandToasts"]
164
+ actions: ["setLastFocusedEl", "pauseToasts"]
161
165
  }
162
166
  }
163
167
  }
@@ -185,6 +189,11 @@ var groupMachine = createMachine({
185
189
  });
186
190
  });
187
191
  },
192
+ subscribeToLayout({ prop, send }) {
193
+ return prop("store").subscribeLayout((stacked) => {
194
+ send({ type: stacked ? "REGION.STACK" : "REGION.OVERLAP" });
195
+ });
196
+ },
188
197
  trackHotKeyPress({ prop, send }) {
189
198
  const handleKeyDown = (event) => {
190
199
  const { hotkey } = prop("store").attrs;
@@ -219,7 +228,7 @@ var groupMachine = createMachine({
219
228
  return;
220
229
  }
221
230
  const groupEl = () => dom.getRegionEl(scope, placement);
222
- const cleanup = (0, import_dismissable.trackDismissableBranch)(groupEl, { defer: true });
231
+ const cleanup = (0, import_dismissable.trackDismissableBranch)(groupEl, { defer: true, getRootNode: scope.getRootNode });
223
232
  refs.set("dismissableCleanup", cleanup);
224
233
  },
225
234
  clearDismissableBranch({ refs }) {
@@ -240,12 +249,6 @@ var groupMachine = createMachine({
240
249
  if (idle || refs.get("isPointerWithin") || refs.get("isFocusWithin")) return;
241
250
  prop("store").resume();
242
251
  },
243
- expandToasts({ prop }) {
244
- prop("store").expand();
245
- },
246
- collapseToasts({ prop }) {
247
- prop("store").collapse();
248
- },
249
252
  removeToast({ prop, event }) {
250
253
  prop("store").remove(event.id);
251
254
  },
@@ -264,6 +267,31 @@ var groupMachine = createMachine({
264
267
  refs.set("isFocusWithin", true);
265
268
  refs.set("lastFocusedEl", event.target ?? null);
266
269
  },
270
+ moveFocusOnDismiss({ refs, scope, computed, event }) {
271
+ if (event.focusVisible) {
272
+ const toastEls = dom.getToastEls(scope, computed("placement"));
273
+ const index = toastEls.findIndex((el) => (0, import_dom_query.contains)(el, scope.getActiveElement()));
274
+ const nextEl = findOpenToast(toastEls, index + 1, 1) ?? findOpenToast(toastEls, index - 1, -1);
275
+ if (nextEl) {
276
+ nextEl.focus({ preventScroll: true });
277
+ return;
278
+ }
279
+ }
280
+ const lastFocusedEl = refs.get("lastFocusedEl");
281
+ if (event.focusVisible && lastFocusedEl) {
282
+ lastFocusedEl.focus({ preventScroll: true });
283
+ } else {
284
+ scope.getActiveElement()?.blur();
285
+ }
286
+ },
287
+ resetInteractionIfEmpty({ refs, prop, scope, computed }) {
288
+ if (computed("count") > 0) return;
289
+ refs.set("isFocusWithin", false);
290
+ refs.set("isPointerWithin", false);
291
+ refs.set("lastFocusedEl", null);
292
+ const idle = prop("store").attrs.pauseOnPageIdle && scope.getDoc().visibilityState === "hidden";
293
+ if (!idle) prop("store").resume();
294
+ },
267
295
  restoreFocusIfPointerOut({ refs }) {
268
296
  if (!refs.get("lastFocusedEl") || refs.get("isPointerWithin")) return;
269
297
  refs.get("lastFocusedEl")?.focus({ preventScroll: true });
@@ -289,8 +317,20 @@ var groupMachine = createMachine({
289
317
  refs.set("lastFocusedEl", null);
290
318
  refs.set("isFocusWithin", false);
291
319
  },
292
- ignoreMouseEventsTemporarily({ refs }) {
293
- refs.get("ignoreMouseTimer").request();
320
+ ignoreMouseEventsTemporarily({ refs, scope, computed, send }) {
321
+ refs.get("ignoreMouseTimer").request(() => {
322
+ return (0, import_dom_query.addDomEvent)(
323
+ scope.getDoc(),
324
+ "pointermove",
325
+ (event) => {
326
+ if (!refs.get("isPointerWithin")) return;
327
+ const regionEl = dom.getRegionEl(scope, computed("placement"));
328
+ if ((0, import_dom_query.contains)(regionEl, (0, import_dom_query.getEventTarget)(event))) return;
329
+ send({ type: "REGION.POINTER_LEAVE", placement: computed("placement") });
330
+ },
331
+ { once: true }
332
+ );
333
+ });
294
334
  },
295
335
  clearMouseEventTimer({ refs }) {
296
336
  refs.get("ignoreMouseTimer").cancel();
@@ -298,6 +338,12 @@ var groupMachine = createMachine({
298
338
  }
299
339
  }
300
340
  });
341
+ function findOpenToast(toastEls, from, step) {
342
+ for (let i = from; i >= 0 && i < toastEls.length; i += step) {
343
+ if (toastEls[i].dataset.state === "open") return toastEls[i];
344
+ }
345
+ return null;
346
+ }
301
347
  // Annotate the CommonJS export names for ESM import in node:
302
348
  0 && (module.exports = {
303
349
  groupMachine
@@ -1,7 +1,7 @@
1
1
  // src/toast-group.machine.ts
2
2
  import { setup } from "@zag-js/core";
3
3
  import { trackDismissableBranch } from "@zag-js/dismissable";
4
- import { addDomEvent, AnimationFrame } from "@zag-js/dom-query";
4
+ import { addDomEvent, AnimationFrame, contains, getEventTarget } from "@zag-js/dom-query";
5
5
  import { uuid } from "@zag-js/utils";
6
6
  import * as dom from "./toast.dom.mjs";
7
7
  var { guards, createMachine } = setup();
@@ -45,11 +45,11 @@ var groupMachine = createMachine({
45
45
  overlap: ({ prop }) => prop("store").attrs.overlap,
46
46
  placement: ({ prop }) => prop("store").attrs.placement
47
47
  },
48
- effects: ["subscribeToStore", "trackDocumentVisibility", "trackHotKeyPress"],
48
+ effects: ["subscribeToStore", "subscribeToLayout", "trackDocumentVisibility", "trackHotKeyPress"],
49
49
  watch({ track, context, action }) {
50
50
  track([() => context.hash("toasts")], () => {
51
51
  queueMicrotask(() => {
52
- action(["collapsedIfEmpty", "setDismissableBranch"]);
52
+ action(["collapsedIfEmpty", "setDismissableBranch", "resetInteractionIfEmpty"]);
53
53
  });
54
54
  });
55
55
  },
@@ -68,7 +68,7 @@ var groupMachine = createMachine({
68
68
  {
69
69
  guard: and("isOverlapping", "isPointerOut"),
70
70
  target: "overlap",
71
- actions: ["collapseToasts", "resumeToasts", "restoreFocusIfPointerOut"]
71
+ actions: ["resumeToasts", "restoreFocusIfPointerOut"]
72
72
  },
73
73
  {
74
74
  guard: "isPointerOut",
@@ -79,6 +79,9 @@ var groupMachine = createMachine({
79
79
  actions: ["clearFocusWithin"]
80
80
  }
81
81
  ],
82
+ "TOAST.DISMISS": {
83
+ actions: ["moveFocusOnDismiss"]
84
+ },
82
85
  "TOAST.REMOVE": {
83
86
  actions: ["removeToast", "removeHeight", "ignoreMouseEventsTemporarily"]
84
87
  },
@@ -93,15 +96,14 @@ var groupMachine = createMachine({
93
96
  {
94
97
  guard: "isOverlapping",
95
98
  target: "overlap",
96
- actions: ["clearPointerWithin", "resumeToasts", "collapseToasts"]
99
+ actions: ["clearPointerWithin", "resumeToasts"]
97
100
  },
98
101
  {
99
102
  actions: ["clearPointerWithin", "resumeToasts"]
100
103
  }
101
104
  ],
102
105
  "REGION.OVERLAP": {
103
- target: "overlap",
104
- actions: ["collapseToasts"]
106
+ target: "overlap"
105
107
  },
106
108
  "REGION.FOCUS": {
107
109
  actions: ["setLastFocusedEl", "pauseToasts"]
@@ -114,16 +116,18 @@ var groupMachine = createMachine({
114
116
  overlap: {
115
117
  on: {
116
118
  "REGION.STACK": {
117
- target: "stack",
118
- actions: ["expandToasts"]
119
+ target: "stack"
119
120
  },
120
121
  "REGION.POINTER_ENTER": {
121
122
  target: "stack",
122
- actions: ["setPointerWithin", "pauseToasts", "expandToasts"]
123
+ actions: ["setPointerWithin", "pauseToasts"]
124
+ },
125
+ "REGION.POINTER_LEAVE": {
126
+ actions: ["clearPointerWithin", "resumeToasts"]
123
127
  },
124
128
  "REGION.FOCUS": {
125
129
  target: "stack",
126
- actions: ["setLastFocusedEl", "pauseToasts", "expandToasts"]
130
+ actions: ["setLastFocusedEl", "pauseToasts"]
127
131
  }
128
132
  }
129
133
  }
@@ -151,6 +155,11 @@ var groupMachine = createMachine({
151
155
  });
152
156
  });
153
157
  },
158
+ subscribeToLayout({ prop, send }) {
159
+ return prop("store").subscribeLayout((stacked) => {
160
+ send({ type: stacked ? "REGION.STACK" : "REGION.OVERLAP" });
161
+ });
162
+ },
154
163
  trackHotKeyPress({ prop, send }) {
155
164
  const handleKeyDown = (event) => {
156
165
  const { hotkey } = prop("store").attrs;
@@ -185,7 +194,7 @@ var groupMachine = createMachine({
185
194
  return;
186
195
  }
187
196
  const groupEl = () => dom.getRegionEl(scope, placement);
188
- const cleanup = trackDismissableBranch(groupEl, { defer: true });
197
+ const cleanup = trackDismissableBranch(groupEl, { defer: true, getRootNode: scope.getRootNode });
189
198
  refs.set("dismissableCleanup", cleanup);
190
199
  },
191
200
  clearDismissableBranch({ refs }) {
@@ -206,12 +215,6 @@ var groupMachine = createMachine({
206
215
  if (idle || refs.get("isPointerWithin") || refs.get("isFocusWithin")) return;
207
216
  prop("store").resume();
208
217
  },
209
- expandToasts({ prop }) {
210
- prop("store").expand();
211
- },
212
- collapseToasts({ prop }) {
213
- prop("store").collapse();
214
- },
215
218
  removeToast({ prop, event }) {
216
219
  prop("store").remove(event.id);
217
220
  },
@@ -230,6 +233,31 @@ var groupMachine = createMachine({
230
233
  refs.set("isFocusWithin", true);
231
234
  refs.set("lastFocusedEl", event.target ?? null);
232
235
  },
236
+ moveFocusOnDismiss({ refs, scope, computed, event }) {
237
+ if (event.focusVisible) {
238
+ const toastEls = dom.getToastEls(scope, computed("placement"));
239
+ const index = toastEls.findIndex((el) => contains(el, scope.getActiveElement()));
240
+ const nextEl = findOpenToast(toastEls, index + 1, 1) ?? findOpenToast(toastEls, index - 1, -1);
241
+ if (nextEl) {
242
+ nextEl.focus({ preventScroll: true });
243
+ return;
244
+ }
245
+ }
246
+ const lastFocusedEl = refs.get("lastFocusedEl");
247
+ if (event.focusVisible && lastFocusedEl) {
248
+ lastFocusedEl.focus({ preventScroll: true });
249
+ } else {
250
+ scope.getActiveElement()?.blur();
251
+ }
252
+ },
253
+ resetInteractionIfEmpty({ refs, prop, scope, computed }) {
254
+ if (computed("count") > 0) return;
255
+ refs.set("isFocusWithin", false);
256
+ refs.set("isPointerWithin", false);
257
+ refs.set("lastFocusedEl", null);
258
+ const idle = prop("store").attrs.pauseOnPageIdle && scope.getDoc().visibilityState === "hidden";
259
+ if (!idle) prop("store").resume();
260
+ },
233
261
  restoreFocusIfPointerOut({ refs }) {
234
262
  if (!refs.get("lastFocusedEl") || refs.get("isPointerWithin")) return;
235
263
  refs.get("lastFocusedEl")?.focus({ preventScroll: true });
@@ -255,8 +283,20 @@ var groupMachine = createMachine({
255
283
  refs.set("lastFocusedEl", null);
256
284
  refs.set("isFocusWithin", false);
257
285
  },
258
- ignoreMouseEventsTemporarily({ refs }) {
259
- refs.get("ignoreMouseTimer").request();
286
+ ignoreMouseEventsTemporarily({ refs, scope, computed, send }) {
287
+ refs.get("ignoreMouseTimer").request(() => {
288
+ return addDomEvent(
289
+ scope.getDoc(),
290
+ "pointermove",
291
+ (event) => {
292
+ if (!refs.get("isPointerWithin")) return;
293
+ const regionEl = dom.getRegionEl(scope, computed("placement"));
294
+ if (contains(regionEl, getEventTarget(event))) return;
295
+ send({ type: "REGION.POINTER_LEAVE", placement: computed("placement") });
296
+ },
297
+ { once: true }
298
+ );
299
+ });
260
300
  },
261
301
  clearMouseEventTimer({ refs }) {
262
302
  refs.get("ignoreMouseTimer").cancel();
@@ -264,6 +304,12 @@ var groupMachine = createMachine({
264
304
  }
265
305
  }
266
306
  });
307
+ function findOpenToast(toastEls, from, step) {
308
+ for (let i = from; i >= 0 && i < toastEls.length; i += step) {
309
+ if (toastEls[i].dataset.state === "open") return toastEls[i];
310
+ }
311
+ return null;
312
+ }
267
313
  export {
268
314
  groupMachine
269
315
  };
@@ -51,7 +51,7 @@ function connect(service, normalize) {
51
51
  const frontmost = computed("frontmost");
52
52
  const placement = prop("parent").computed("placement");
53
53
  const type = prop("type");
54
- const stacked = prop("stacked");
54
+ const stacked = prop("parent").state.matches("stack");
55
55
  const title = prop("title");
56
56
  const description = prop("description");
57
57
  const action = prop("action");
@@ -17,7 +17,7 @@ function connect(service, normalize) {
17
17
  const frontmost = computed("frontmost");
18
18
  const placement = prop("parent").computed("placement");
19
19
  const type = prop("type");
20
- const stacked = prop("stacked");
20
+ const stacked = prop("parent").state.matches("stack");
21
21
  const title = prop("title");
22
22
  const description = prop("description");
23
23
  const action = prop("action");
@@ -5,6 +5,7 @@ import '@zag-js/dom-query';
5
5
 
6
6
  declare const getRegionId: (placement: Placement) => string;
7
7
  declare const getRegionEl: (ctx: Scope, placement: Placement) => HTMLElement | null;
8
+ declare const getToastEls: (ctx: Scope, placement: Placement) => HTMLElement[];
8
9
  declare const getRootId: (ctx: Scope) => string;
9
10
  declare const getRootEl: (ctx: Scope) => HTMLElement | null;
10
11
  declare const getTitleId: (ctx: Scope) => string;
@@ -12,5 +13,13 @@ declare const getDescriptionId: (ctx: Scope) => string;
12
13
  declare const getTitleEl: (ctx: Scope) => HTMLElement | null;
13
14
  declare const getDescriptionEl: (ctx: Scope) => HTMLElement | null;
14
15
  declare const getCloseTriggerId: (ctx: Scope) => string;
16
+ interface ObserveContentOptions {
17
+ filter?: ((el: Element) => boolean) | undefined;
18
+ /** Called when the content's size may have changed */
19
+ onChange: VoidFunction;
20
+ /** Called when the content's DOM changes */
21
+ onMutate?: VoidFunction | undefined;
22
+ }
23
+ declare function observeContent(rootEl: HTMLElement, options: ObserveContentOptions): () => void;
15
24
 
16
- export { getCloseTriggerId, getDescriptionEl, getDescriptionId, getRegionEl, getRegionId, getRootEl, getRootId, getTitleEl, getTitleId };
25
+ export { getCloseTriggerId, getDescriptionEl, getDescriptionId, getRegionEl, getRegionId, getRootEl, getRootId, getTitleEl, getTitleId, getToastEls, observeContent };
@@ -5,6 +5,7 @@ import '@zag-js/dom-query';
5
5
 
6
6
  declare const getRegionId: (placement: Placement) => string;
7
7
  declare const getRegionEl: (ctx: Scope, placement: Placement) => HTMLElement | null;
8
+ declare const getToastEls: (ctx: Scope, placement: Placement) => HTMLElement[];
8
9
  declare const getRootId: (ctx: Scope) => string;
9
10
  declare const getRootEl: (ctx: Scope) => HTMLElement | null;
10
11
  declare const getTitleId: (ctx: Scope) => string;
@@ -12,5 +13,13 @@ declare const getDescriptionId: (ctx: Scope) => string;
12
13
  declare const getTitleEl: (ctx: Scope) => HTMLElement | null;
13
14
  declare const getDescriptionEl: (ctx: Scope) => HTMLElement | null;
14
15
  declare const getCloseTriggerId: (ctx: Scope) => string;
16
+ interface ObserveContentOptions {
17
+ filter?: ((el: Element) => boolean) | undefined;
18
+ /** Called when the content's size may have changed */
19
+ onChange: VoidFunction;
20
+ /** Called when the content's DOM changes */
21
+ onMutate?: VoidFunction | undefined;
22
+ }
23
+ declare function observeContent(rootEl: HTMLElement, options: ObserveContentOptions): () => void;
15
24
 
16
- export { getCloseTriggerId, getDescriptionEl, getDescriptionId, getRegionEl, getRegionId, getRootEl, getRootId, getTitleEl, getTitleId };
25
+ export { getCloseTriggerId, getDescriptionEl, getDescriptionId, getRegionEl, getRegionId, getRootEl, getRootId, getTitleEl, getTitleId, getToastEls, observeContent };
package/dist/toast.dom.js CHANGED
@@ -28,11 +28,16 @@ __export(toast_dom_exports, {
28
28
  getRootEl: () => getRootEl,
29
29
  getRootId: () => getRootId,
30
30
  getTitleEl: () => getTitleEl,
31
- getTitleId: () => getTitleId
31
+ getTitleId: () => getTitleId,
32
+ getToastEls: () => getToastEls,
33
+ observeContent: () => observeContent
32
34
  });
33
35
  module.exports = __toCommonJS(toast_dom_exports);
36
+ var import_dom_query = require("@zag-js/dom-query");
37
+ var import_utils = require("@zag-js/utils");
34
38
  var getRegionId = (placement) => `toast-group:${placement}`;
35
39
  var getRegionEl = (ctx, placement) => ctx.getById(`toast-group:${placement}`);
40
+ var getToastEls = (ctx, placement) => (0, import_dom_query.queryAll)(getRegionEl(ctx, placement), "[data-scope=toast][data-part=root]");
36
41
  var getRootId = (ctx) => `toast:${ctx.id}`;
37
42
  var getRootEl = (ctx) => ctx.getById(getRootId(ctx));
38
43
  var getTitleId = (ctx) => `toast:${ctx.id}:title`;
@@ -40,6 +45,31 @@ var getDescriptionId = (ctx) => `toast:${ctx.id}:description`;
40
45
  var getTitleEl = (ctx) => ctx.getById(getTitleId(ctx));
41
46
  var getDescriptionEl = (ctx) => ctx.getById(getDescriptionId(ctx));
42
47
  var getCloseTriggerId = (ctx) => `toast${ctx.id}:close`;
48
+ function observeContent(rootEl, options) {
49
+ const { filter = () => true, onChange, onMutate } = options;
50
+ const win = (0, import_dom_query.getWindow)(rootEl);
51
+ const frame = import_dom_query.AnimationFrame.create();
52
+ const notify = () => frame.request(onChange);
53
+ let stopObservingChildren;
54
+ const observeChildren = () => {
55
+ stopObservingChildren?.();
56
+ const children = Array.from(rootEl.children).filter(filter);
57
+ stopObservingChildren = (0, import_utils.callAll)(...children.map((child) => import_dom_query.resizeObserverBorderBox.observe(child, notify)));
58
+ };
59
+ observeChildren();
60
+ const mutationObserver = new win.MutationObserver(() => {
61
+ frame.cancel();
62
+ onChange();
63
+ onMutate?.();
64
+ observeChildren();
65
+ });
66
+ mutationObserver.observe(rootEl, { childList: true, subtree: true, characterData: true });
67
+ return () => {
68
+ mutationObserver.disconnect();
69
+ stopObservingChildren?.();
70
+ frame.cancel();
71
+ };
72
+ }
43
73
  // Annotate the CommonJS export names for ESM import in node:
44
74
  0 && (module.exports = {
45
75
  getCloseTriggerId,
@@ -50,5 +80,7 @@ var getCloseTriggerId = (ctx) => `toast${ctx.id}:close`;
50
80
  getRootEl,
51
81
  getRootId,
52
82
  getTitleEl,
53
- getTitleId
83
+ getTitleId,
84
+ getToastEls,
85
+ observeContent
54
86
  });
@@ -1,6 +1,9 @@
1
1
  // src/toast.dom.ts
2
+ import { AnimationFrame, getWindow, queryAll, resizeObserverBorderBox } from "@zag-js/dom-query";
3
+ import { callAll } from "@zag-js/utils";
2
4
  var getRegionId = (placement) => `toast-group:${placement}`;
3
5
  var getRegionEl = (ctx, placement) => ctx.getById(`toast-group:${placement}`);
6
+ var getToastEls = (ctx, placement) => queryAll(getRegionEl(ctx, placement), "[data-scope=toast][data-part=root]");
4
7
  var getRootId = (ctx) => `toast:${ctx.id}`;
5
8
  var getRootEl = (ctx) => ctx.getById(getRootId(ctx));
6
9
  var getTitleId = (ctx) => `toast:${ctx.id}:title`;
@@ -8,6 +11,31 @@ var getDescriptionId = (ctx) => `toast:${ctx.id}:description`;
8
11
  var getTitleEl = (ctx) => ctx.getById(getTitleId(ctx));
9
12
  var getDescriptionEl = (ctx) => ctx.getById(getDescriptionId(ctx));
10
13
  var getCloseTriggerId = (ctx) => `toast${ctx.id}:close`;
14
+ function observeContent(rootEl, options) {
15
+ const { filter = () => true, onChange, onMutate } = options;
16
+ const win = getWindow(rootEl);
17
+ const frame = AnimationFrame.create();
18
+ const notify = () => frame.request(onChange);
19
+ let stopObservingChildren;
20
+ const observeChildren = () => {
21
+ stopObservingChildren?.();
22
+ const children = Array.from(rootEl.children).filter(filter);
23
+ stopObservingChildren = callAll(...children.map((child) => resizeObserverBorderBox.observe(child, notify)));
24
+ };
25
+ observeChildren();
26
+ const mutationObserver = new win.MutationObserver(() => {
27
+ frame.cancel();
28
+ onChange();
29
+ onMutate?.();
30
+ observeChildren();
31
+ });
32
+ mutationObserver.observe(rootEl, { childList: true, subtree: true, characterData: true });
33
+ return () => {
34
+ mutationObserver.disconnect();
35
+ stopObservingChildren?.();
36
+ frame.cancel();
37
+ };
38
+ }
11
39
  export {
12
40
  getCloseTriggerId,
13
41
  getDescriptionEl,
@@ -17,5 +45,7 @@ export {
17
45
  getRootEl,
18
46
  getRootId,
19
47
  getTitleEl,
20
- getTitleId
48
+ getTitleId,
49
+ getToastEls,
50
+ observeContent
21
51
  };
@@ -178,7 +178,7 @@ var machine = (0, import_core.createMachine)({
178
178
  }
179
179
  },
180
180
  dismissing: {
181
- entry: ["invokeOnDismiss"],
181
+ entry: ["notifyParentOfDismiss", "invokeOnDismiss"],
182
182
  effects: ["waitForRemoveDelay"],
183
183
  on: {
184
184
  REMOVE: {
@@ -209,14 +209,14 @@ var machine = (0, import_core.createMachine)({
209
209
  send({ type: "SHOW", src: "timer" });
210
210
  }, 0);
211
211
  },
212
- trackContent({ scope, prop, context }) {
212
+ trackContent({ scope, prop, context, state }) {
213
213
  return (0, import_dom_query.raf)(() => {
214
214
  const rootEl = dom.getRootEl(scope);
215
215
  if (!rootEl) return;
216
216
  const syncHeight = () => {
217
+ if (!state.hasTag("visible") || !rootEl.isConnected) return;
217
218
  const height = measureLayoutHeight(rootEl);
218
- const item = { id: prop("id"), height };
219
- setHeight(prop("parent"), item);
219
+ (0, import_toast.setHeight)(prop("parent"), { id: prop("id"), height });
220
220
  };
221
221
  const syncRenderedElements = () => {
222
222
  context.set("rendered", {
@@ -225,17 +225,11 @@ var machine = (0, import_core.createMachine)({
225
225
  });
226
226
  };
227
227
  syncRenderedElements();
228
- const win = scope.getWin();
229
- const observer = new win.MutationObserver(() => {
230
- syncHeight();
231
- syncRenderedElements();
228
+ return dom.observeContent(rootEl, {
229
+ filter: (el) => !el.hasAttribute("data-ghost"),
230
+ onChange: syncHeight,
231
+ onMutate: syncRenderedElements
232
232
  });
233
- observer.observe(rootEl, {
234
- childList: true,
235
- subtree: true,
236
- characterData: true
237
- });
238
- return () => observer.disconnect();
239
233
  });
240
234
  }
241
235
  },
@@ -256,7 +250,7 @@ var machine = (0, import_core.createMachine)({
256
250
  const height = measureLayoutHeight(rootEl);
257
251
  context.set("initialHeight", height);
258
252
  const item = { id: prop("id"), height };
259
- setHeight(prop("parent"), item);
253
+ (0, import_toast.setHeight)(prop("parent"), item);
260
254
  });
261
255
  },
262
256
  setCloseTimer({ refs }) {
@@ -278,6 +272,12 @@ var machine = (0, import_core.createMachine)({
278
272
  const parent = prop("parent");
279
273
  parent.send({ type: "TOAST.REMOVE", id: prop("id") });
280
274
  },
275
+ notifyParentOfDismiss({ prop, scope }) {
276
+ const activeEl = scope.getActiveElement();
277
+ if (!(0, import_dom_query.contains)(dom.getRootEl(scope), activeEl)) return;
278
+ const focusVisible = !!activeEl?.matches(":focus-visible");
279
+ prop("parent").send({ type: "TOAST.DISMISS", focusVisible });
280
+ },
281
281
  invokeOnDismiss({ prop, event }) {
282
282
  prop("parent").prop("store").dismiss(prop("id"));
283
283
  prop("onStatusChange")?.({ status: "dismissing", src: event.src });
@@ -298,17 +298,6 @@ function measureLayoutHeight(el) {
298
298
  el.style.height = prevHeight;
299
299
  return height;
300
300
  }
301
- function setHeight(parent, item) {
302
- const { id, height } = item;
303
- parent.context.set("heights", (prev) => {
304
- const alreadyExists = prev.find((i) => i.id === id);
305
- if (!alreadyExists) {
306
- return [{ id, height }, ...prev];
307
- } else {
308
- return prev.map((i) => i.id === id ? { ...i, height } : i);
309
- }
310
- });
311
- }
312
301
  // Annotate the CommonJS export names for ESM import in node:
313
302
  0 && (module.exports = {
314
303
  machine
@@ -1,9 +1,9 @@
1
1
  // src/toast.machine.ts
2
2
  import { createGuards, createMachine } from "@zag-js/core";
3
- import { raf } from "@zag-js/dom-query";
3
+ import { contains, raf } from "@zag-js/dom-query";
4
4
  import { ensureProps, setRafTimeout } from "@zag-js/utils";
5
5
  import * as dom from "./toast.dom.mjs";
6
- import { getToastDuration } from "./toast.utils.mjs";
6
+ import { getToastDuration, setHeight } from "./toast.utils.mjs";
7
7
  var { not, and } = createGuards();
8
8
  var machine = createMachine({
9
9
  props({ props }) {
@@ -144,7 +144,7 @@ var machine = createMachine({
144
144
  }
145
145
  },
146
146
  dismissing: {
147
- entry: ["invokeOnDismiss"],
147
+ entry: ["notifyParentOfDismiss", "invokeOnDismiss"],
148
148
  effects: ["waitForRemoveDelay"],
149
149
  on: {
150
150
  REMOVE: {
@@ -175,14 +175,14 @@ var machine = createMachine({
175
175
  send({ type: "SHOW", src: "timer" });
176
176
  }, 0);
177
177
  },
178
- trackContent({ scope, prop, context }) {
178
+ trackContent({ scope, prop, context, state }) {
179
179
  return raf(() => {
180
180
  const rootEl = dom.getRootEl(scope);
181
181
  if (!rootEl) return;
182
182
  const syncHeight = () => {
183
+ if (!state.hasTag("visible") || !rootEl.isConnected) return;
183
184
  const height = measureLayoutHeight(rootEl);
184
- const item = { id: prop("id"), height };
185
- setHeight(prop("parent"), item);
185
+ setHeight(prop("parent"), { id: prop("id"), height });
186
186
  };
187
187
  const syncRenderedElements = () => {
188
188
  context.set("rendered", {
@@ -191,17 +191,11 @@ var machine = createMachine({
191
191
  });
192
192
  };
193
193
  syncRenderedElements();
194
- const win = scope.getWin();
195
- const observer = new win.MutationObserver(() => {
196
- syncHeight();
197
- syncRenderedElements();
194
+ return dom.observeContent(rootEl, {
195
+ filter: (el) => !el.hasAttribute("data-ghost"),
196
+ onChange: syncHeight,
197
+ onMutate: syncRenderedElements
198
198
  });
199
- observer.observe(rootEl, {
200
- childList: true,
201
- subtree: true,
202
- characterData: true
203
- });
204
- return () => observer.disconnect();
205
199
  });
206
200
  }
207
201
  },
@@ -244,6 +238,12 @@ var machine = createMachine({
244
238
  const parent = prop("parent");
245
239
  parent.send({ type: "TOAST.REMOVE", id: prop("id") });
246
240
  },
241
+ notifyParentOfDismiss({ prop, scope }) {
242
+ const activeEl = scope.getActiveElement();
243
+ if (!contains(dom.getRootEl(scope), activeEl)) return;
244
+ const focusVisible = !!activeEl?.matches(":focus-visible");
245
+ prop("parent").send({ type: "TOAST.DISMISS", focusVisible });
246
+ },
247
247
  invokeOnDismiss({ prop, event }) {
248
248
  prop("parent").prop("store").dismiss(prop("id"));
249
249
  prop("onStatusChange")?.({ status: "dismissing", src: event.src });
@@ -264,17 +264,6 @@ function measureLayoutHeight(el) {
264
264
  el.style.height = prevHeight;
265
265
  return height;
266
266
  }
267
- function setHeight(parent, item) {
268
- const { id, height } = item;
269
- parent.context.set("heights", (prev) => {
270
- const alreadyExists = prev.find((i) => i.id === id);
271
- if (!alreadyExists) {
272
- return [{ id, height }, ...prev];
273
- } else {
274
- return prev.map((i) => i.id === id ? { ...i, height } : i);
275
- }
276
- });
277
- }
278
267
  export {
279
268
  machine
280
269
  };
@@ -65,6 +65,7 @@ function createToastStore(props = {}) {
65
65
  const closingToasts = /* @__PURE__ */ new Set();
66
66
  const promiseTokens = /* @__PURE__ */ new Map();
67
67
  let paused = false;
68
+ const layoutSubscribers = /* @__PURE__ */ new Set();
68
69
  const subscribe = (subscriber) => {
69
70
  subscribers.push(subscriber);
70
71
  let active = true;
@@ -132,7 +133,6 @@ function createToastStore(props = {}) {
132
133
  removeDelay: attrs.removeDelay,
133
134
  type: DEFAULT_TYPE,
134
135
  ...data,
135
- stacked: !attrs.overlap,
136
136
  gap: attrs.gap,
137
137
  paused
138
138
  };
@@ -273,8 +273,14 @@ function createToastStore(props = {}) {
273
273
  const isDismissed = (id) => {
274
274
  return dismissedToasts.has(id);
275
275
  };
276
- const expand = () => changeToasts({ stacked: true });
277
- const collapse = () => changeToasts({ stacked: false });
276
+ const subscribeLayout = (subscriber) => {
277
+ layoutSubscribers.add(subscriber);
278
+ return () => {
279
+ layoutSubscribers.delete(subscriber);
280
+ };
281
+ };
282
+ const expand = () => layoutSubscribers.forEach((subscriber) => subscriber(true));
283
+ const collapse = () => layoutSubscribers.forEach((subscriber) => subscriber(false));
278
284
  return {
279
285
  attrs,
280
286
  subscribe,
@@ -295,7 +301,8 @@ function createToastStore(props = {}) {
295
301
  isVisible,
296
302
  isDismissed,
297
303
  expand,
298
- collapse
304
+ collapse,
305
+ subscribeLayout
299
306
  };
300
307
  }
301
308
  var isHttpResponse = (data) => {
@@ -41,6 +41,7 @@ function createToastStore(props = {}) {
41
41
  const closingToasts = /* @__PURE__ */ new Set();
42
42
  const promiseTokens = /* @__PURE__ */ new Map();
43
43
  let paused = false;
44
+ const layoutSubscribers = /* @__PURE__ */ new Set();
44
45
  const subscribe = (subscriber) => {
45
46
  subscribers.push(subscriber);
46
47
  let active = true;
@@ -108,7 +109,6 @@ function createToastStore(props = {}) {
108
109
  removeDelay: attrs.removeDelay,
109
110
  type: DEFAULT_TYPE,
110
111
  ...data,
111
- stacked: !attrs.overlap,
112
112
  gap: attrs.gap,
113
113
  paused
114
114
  };
@@ -249,8 +249,14 @@ function createToastStore(props = {}) {
249
249
  const isDismissed = (id) => {
250
250
  return dismissedToasts.has(id);
251
251
  };
252
- const expand = () => changeToasts({ stacked: true });
253
- const collapse = () => changeToasts({ stacked: false });
252
+ const subscribeLayout = (subscriber) => {
253
+ layoutSubscribers.add(subscriber);
254
+ return () => {
255
+ layoutSubscribers.delete(subscriber);
256
+ };
257
+ };
258
+ const expand = () => layoutSubscribers.forEach((subscriber) => subscriber(true));
259
+ const collapse = () => layoutSubscribers.forEach((subscriber) => subscriber(false));
254
260
  return {
255
261
  attrs,
256
262
  subscribe,
@@ -271,7 +277,8 @@ function createToastStore(props = {}) {
271
277
  isVisible,
272
278
  isDismissed,
273
279
  expand,
274
- collapse
280
+ collapse,
281
+ subscribeLayout
275
282
  };
276
283
  }
277
284
  var isHttpResponse = (data) => {
@@ -1,6 +1,6 @@
1
1
  import { Service } from '@zag-js/core';
2
2
  import { Style } from '@zag-js/types';
3
- import { Type, ToastSchema, ToastGroupService, Placement } from './toast.types.mjs';
3
+ import { Type, ToastSchema, ToastGroupService, Placement, ToastGroupSchema, ToastHeight } from './toast.types.mjs';
4
4
  import '@zag-js/dom-query';
5
5
 
6
6
  declare const defaultTimeouts: Record<Type, number>;
@@ -9,5 +9,6 @@ declare function getGroupPlacementStyle(service: ToastGroupService, placement: P
9
9
  declare function getPlacementStyle(service: Service<ToastSchema>, visible: boolean): Style;
10
10
  declare function getGhostBeforeStyle(service: Service<ToastSchema>, visible: boolean): Style;
11
11
  declare function getGhostAfterStyle(): Style;
12
+ declare function setHeight(parent: Service<ToastGroupSchema>, item: ToastHeight): void;
12
13
 
13
- export { defaultTimeouts, getGhostAfterStyle, getGhostBeforeStyle, getGroupPlacementStyle, getPlacementStyle, getToastDuration };
14
+ export { defaultTimeouts, getGhostAfterStyle, getGhostBeforeStyle, getGroupPlacementStyle, getPlacementStyle, getToastDuration, setHeight };
@@ -1,6 +1,6 @@
1
1
  import { Service } from '@zag-js/core';
2
2
  import { Style } from '@zag-js/types';
3
- import { Type, ToastSchema, ToastGroupService, Placement } from './toast.types.js';
3
+ import { Type, ToastSchema, ToastGroupService, Placement, ToastGroupSchema, ToastHeight } from './toast.types.js';
4
4
  import '@zag-js/dom-query';
5
5
 
6
6
  declare const defaultTimeouts: Record<Type, number>;
@@ -9,5 +9,6 @@ declare function getGroupPlacementStyle(service: ToastGroupService, placement: P
9
9
  declare function getPlacementStyle(service: Service<ToastSchema>, visible: boolean): Style;
10
10
  declare function getGhostBeforeStyle(service: Service<ToastSchema>, visible: boolean): Style;
11
11
  declare function getGhostAfterStyle(): Style;
12
+ declare function setHeight(parent: Service<ToastGroupSchema>, item: ToastHeight): void;
12
13
 
13
- export { defaultTimeouts, getGhostAfterStyle, getGhostBeforeStyle, getGroupPlacementStyle, getPlacementStyle, getToastDuration };
14
+ export { defaultTimeouts, getGhostAfterStyle, getGhostBeforeStyle, getGroupPlacementStyle, getPlacementStyle, getToastDuration, setHeight };
@@ -25,7 +25,8 @@ __export(toast_utils_exports, {
25
25
  getGhostBeforeStyle: () => getGhostBeforeStyle,
26
26
  getGroupPlacementStyle: () => getGroupPlacementStyle,
27
27
  getPlacementStyle: () => getPlacementStyle,
28
- getToastDuration: () => getToastDuration
28
+ getToastDuration: () => getToastDuration,
29
+ setHeight: () => setHeight
29
30
  });
30
31
  module.exports = __toCommonJS(toast_utils_exports);
31
32
  var import_dom_query = require("@zag-js/dom-query");
@@ -96,8 +97,8 @@ function getPlacementStyle(service, visible) {
96
97
  const height = computed("height");
97
98
  const frontmost = computed("frontmost");
98
99
  const sibling = !frontmost;
99
- const overlap = !prop("stacked");
100
- const stacked = prop("stacked");
100
+ const stacked = prop("parent").state.matches("stack");
101
+ const overlap = !stacked;
101
102
  const type = prop("type");
102
103
  const duration = type === "loading" ? Number.MAX_SAFE_INTEGER : remainingTime;
103
104
  const offset = computed("heightIndex") * gap + computed("heightBefore");
@@ -199,6 +200,25 @@ function getGhostAfterStyle() {
199
200
  width: "100%"
200
201
  };
201
202
  }
203
+ function setHeight(parent, item) {
204
+ const { id, height } = item;
205
+ parent.context.set("heights", (prev) => {
206
+ const existing = prev.find((i) => i.id === id);
207
+ if (existing) {
208
+ if (existing.height === height) return prev;
209
+ return prev.map((i) => i.id === id ? { ...i, height } : i);
210
+ }
211
+ const toasts = parent.context.get("toasts");
212
+ const rank = (id2) => toasts.findIndex((t) => t.id === id2);
213
+ const index = rank(id);
214
+ let insertAt = prev.findIndex((i) => {
215
+ const r = rank(i.id);
216
+ return r === -1 || r > index;
217
+ });
218
+ if (insertAt === -1) insertAt = prev.length;
219
+ return [...prev.slice(0, insertAt), { id, height }, ...prev.slice(insertAt)];
220
+ });
221
+ }
202
222
  // Annotate the CommonJS export names for ESM import in node:
203
223
  0 && (module.exports = {
204
224
  defaultTimeouts,
@@ -206,5 +226,6 @@ function getGhostAfterStyle() {
206
226
  getGhostBeforeStyle,
207
227
  getGroupPlacementStyle,
208
228
  getPlacementStyle,
209
- getToastDuration
229
+ getToastDuration,
230
+ setHeight
210
231
  });
@@ -67,8 +67,8 @@ function getPlacementStyle(service, visible) {
67
67
  const height = computed("height");
68
68
  const frontmost = computed("frontmost");
69
69
  const sibling = !frontmost;
70
- const overlap = !prop("stacked");
71
- const stacked = prop("stacked");
70
+ const stacked = prop("parent").state.matches("stack");
71
+ const overlap = !stacked;
72
72
  const type = prop("type");
73
73
  const duration = type === "loading" ? Number.MAX_SAFE_INTEGER : remainingTime;
74
74
  const offset = computed("heightIndex") * gap + computed("heightBefore");
@@ -170,11 +170,31 @@ function getGhostAfterStyle() {
170
170
  width: "100%"
171
171
  };
172
172
  }
173
+ function setHeight(parent, item) {
174
+ const { id, height } = item;
175
+ parent.context.set("heights", (prev) => {
176
+ const existing = prev.find((i) => i.id === id);
177
+ if (existing) {
178
+ if (existing.height === height) return prev;
179
+ return prev.map((i) => i.id === id ? { ...i, height } : i);
180
+ }
181
+ const toasts = parent.context.get("toasts");
182
+ const rank = (id2) => toasts.findIndex((t) => t.id === id2);
183
+ const index = rank(id);
184
+ let insertAt = prev.findIndex((i) => {
185
+ const r = rank(i.id);
186
+ return r === -1 || r > index;
187
+ });
188
+ if (insertAt === -1) insertAt = prev.length;
189
+ return [...prev.slice(0, insertAt), { id, height }, ...prev.slice(insertAt)];
190
+ });
191
+ }
173
192
  export {
174
193
  defaultTimeouts,
175
194
  getGhostAfterStyle,
176
195
  getGhostBeforeStyle,
177
196
  getGroupPlacementStyle,
178
197
  getPlacementStyle,
179
- getToastDuration
198
+ getToastDuration,
199
+ setHeight
180
200
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zag-js/toast",
3
- "version": "1.46.0",
3
+ "version": "1.47.0",
4
4
  "description": "Core logic for the toast widget implemented as a state machine",
5
5
  "keywords": [
6
6
  "js",
@@ -29,12 +29,12 @@
29
29
  "url": "https://github.com/chakra-ui/zag/issues"
30
30
  },
31
31
  "dependencies": {
32
- "@zag-js/anatomy": "1.46.0",
33
- "@zag-js/core": "1.46.0",
34
- "@zag-js/dom-query": "1.46.0",
35
- "@zag-js/dismissable": "1.46.0",
36
- "@zag-js/utils": "1.46.0",
37
- "@zag-js/types": "1.46.0"
32
+ "@zag-js/anatomy": "1.47.0",
33
+ "@zag-js/core": "1.47.0",
34
+ "@zag-js/dom-query": "1.47.0",
35
+ "@zag-js/dismissable": "1.47.0",
36
+ "@zag-js/utils": "1.47.0",
37
+ "@zag-js/types": "1.47.0"
38
38
  },
39
39
  "devDependencies": {
40
40
  "clean-package": "2.2.0"