undo-toast 0.0.0-stage → 0.4.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.
@@ -0,0 +1,355 @@
1
+ // src/spec.ts
2
+ var CONTEXT_FIELDS = {
3
+ reversal: {
4
+ values: ["deferred", "compensating", "manual", "none"],
5
+ default: "compensating",
6
+ describe: "How the action can be taken back. 'deferred': nothing is committed until the undo window ends (Gmail's undo send, zodal's undoable mutation). 'compensating': it is already done, and one Undo applies the inverse of the whole operation, in place (re-insert, restore; for a bulk action, one undo step for the whole selection). 'manual': recoverable, but only by hand, item by item, somewhere else (finding 30 songs in a playlist to remove them, restoring 12 items one by one from a trash without a one-step restore); recoverable is not reversible. 'none': it cannot be taken back (a payment, an email already delivered, Delete permanently, Empty Trash)."
7
+ },
8
+ cost: {
9
+ values: ["low", "high"],
10
+ default: "low",
11
+ describe: "What a mistake costs the user. 'high': their work is lost (a document, hours of edits), many items at once, or something hard to recreate (a key, a playlist they built). 'low': it is easy to redo by hand."
12
+ },
13
+ frequency: {
14
+ values: ["rare", "occasional", "frequent"],
15
+ default: "occasional",
16
+ describe: "How often the user does this. 'frequent' (toggle, check, reorder, many times a session) makes a toast noise."
17
+ },
18
+ resultStaysInView: {
19
+ values: [true, false],
20
+ default: false,
21
+ describe: "True when the changed thing stays on screen showing its new state (a checked box, a renamed title), so the change is its own feedback. False when the item leaves the view, moves away, or the action was done by a shortcut."
22
+ },
23
+ failsOften: {
24
+ values: [true, false],
25
+ default: false,
26
+ describe: "True when the action often fails or its result is computed by the server: show it pending, not done, and report failure with Retry."
27
+ },
28
+ count: {
29
+ values: "number",
30
+ default: 1,
31
+ describe: "How many items the action touched. Above 1 the message names the count and the cost leans high."
32
+ },
33
+ hasUndoStack: {
34
+ values: [true, false],
35
+ default: false,
36
+ describe: "True when the app keeps its own undo history (acture-undo, Ctrl/Cmd+Z). Then the toast is a shortcut, the app owns Ctrl/Cmd+Z, and the action stays undoable after the toast leaves."
37
+ },
38
+ takesAway: {
39
+ values: [true, false],
40
+ default: true,
41
+ describe: "True when the action takes something from the user (deletes, removes, overwrites): losing its undo toast can lose their work. False when it only adds (to a playlist, a tag): if the undo is lost, nothing is gone, so no trash or undo history is called for."
42
+ },
43
+ hasTrash: {
44
+ values: [true, false],
45
+ default: false,
46
+ describe: "True when deleted things go to a trash or 'recently removed' that outlives the toast."
47
+ },
48
+ keepNotices: {
49
+ values: [true, false],
50
+ default: false,
51
+ describe: "The user's own setting 'keep notices until I close them' (WCAG 2.2.1, Timing Adjustable). True makes a compensating toast stay until closed."
52
+ },
53
+ message: {
54
+ values: "string",
55
+ default: void 0,
56
+ describe: "The toast text, if known: longer text stays longer (reading time)."
57
+ },
58
+ verb: {
59
+ values: "string",
60
+ default: void 0,
61
+ describe: "The action's verb phrase, for the confirmation button when the advice is to confirm: 'Move {count} {item|items} to Trash', 'Add {count} {song|songs} to playlist'. `{count}` is the count and `{one|other}` picks the singular at 1; without `{count}`, a count above 1 is appended as ' (12)'."
62
+ }
63
+ };
64
+ var PRESETS = {
65
+ "remove-item": {
66
+ describe: "Remove one item from a list or collection (a segment, a row, a card); undo puts it back.",
67
+ context: { reversal: "compensating", cost: "low" }
68
+ },
69
+ "delete-work": {
70
+ describe: "Delete something the user built (a document, a playlist, a project).",
71
+ context: { reversal: "compensating", cost: "high" }
72
+ },
73
+ "bulk-delete": {
74
+ describe: "Delete several items at once (pass count).",
75
+ context: { reversal: "compensating", cost: "high", count: 2 }
76
+ },
77
+ "move-to-trash": {
78
+ describe: "Move one item to the Trash (soft delete); undo restores it, and so does the Trash after the toast leaves.",
79
+ context: { reversal: "compensating", cost: "low", hasTrash: true, verb: "Move to Trash" }
80
+ },
81
+ "bulk-move-to-trash": {
82
+ describe: "Move a selection to the Trash (pass count). A timed toast when one Undo restores the whole selection; pass reversal: 'manual' when the Trash can only restore item by item, and it asks first.",
83
+ context: { reversal: "compensating", cost: "high", count: 2, hasTrash: true, verb: "Move {count} {item|items} to Trash" }
84
+ },
85
+ "add-to-collection": {
86
+ describe: "Add items to a playlist, folder or collection that is not in view (pass count for a selection). One Undo takes the addition back; pass reversal: 'manual' when the only way back is editing the collection by hand, and a bulk add asks first.",
87
+ context: { reversal: "compensating", cost: "low", takesAway: false, verb: "Add to collection" }
88
+ },
89
+ "delete-permanently": {
90
+ describe: "Delete from the Trash for good (pass count). Cannot be taken back: always confirms.",
91
+ context: { reversal: "none", cost: "high", verb: "Delete {count} {item|items} permanently" }
92
+ },
93
+ "empty-trash": {
94
+ describe: "Empty the Trash (pass count). Cannot be taken back: always confirms.",
95
+ context: { reversal: "none", cost: "high", verb: "Empty Trash" }
96
+ },
97
+ archive: {
98
+ describe: "Archive, hide, or move out of the current view.",
99
+ context: { reversal: "compensating", cost: "low" }
100
+ },
101
+ "clear-history": {
102
+ describe: "Clear a list of past entries (recent searches, input history).",
103
+ context: { reversal: "compensating", cost: "low" }
104
+ },
105
+ "forget-secret": {
106
+ describe: "Forget a stored key or credential; it is held, not erased, until the window ends.",
107
+ context: { reversal: "deferred", cost: "high" }
108
+ },
109
+ send: {
110
+ describe: "Send, publish or share; held back until the window ends (undo send).",
111
+ context: { reversal: "deferred", cost: "high" }
112
+ },
113
+ toggle: {
114
+ describe: "Toggle, check, star, reorder: frequent, cheap, and its result stays in view.",
115
+ context: { reversal: "compensating", cost: "low", frequency: "frequent", resultStaysInView: true }
116
+ },
117
+ pay: {
118
+ describe: "Pay, or any action with an external effect that cannot be called back.",
119
+ context: { reversal: "none", cost: "high" }
120
+ }
121
+ };
122
+ function resolveContext(context = {}) {
123
+ const out = {};
124
+ for (const key of Object.keys(context)) {
125
+ if (!(key in CONTEXT_FIELDS)) {
126
+ throw new Error(`undo-toast: unknown context field "${key}"; the fields are ${Object.keys(CONTEXT_FIELDS).join(", ")}.`);
127
+ }
128
+ }
129
+ for (const [key, spec] of Object.entries(CONTEXT_FIELDS)) {
130
+ const value = context[key];
131
+ if (value === void 0) {
132
+ if (spec.default !== void 0) out[key] = spec.default;
133
+ continue;
134
+ }
135
+ if (spec.values === "number") {
136
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
137
+ throw new Error(`undo-toast: "${key}" must be a non-negative number, got ${String(value)}.`);
138
+ }
139
+ } else if (spec.values === "string") {
140
+ if (typeof value !== "string") throw new Error(`undo-toast: "${key}" must be a string, got ${typeof value}.`);
141
+ } else if (!spec.values.includes(value)) {
142
+ throw new Error(`undo-toast: "${key}" must be one of ${spec.values.map((v) => JSON.stringify(v)).join(", ")}, got ${JSON.stringify(value)}.`);
143
+ }
144
+ out[key] = value;
145
+ }
146
+ return out;
147
+ }
148
+ function presetContext(name, extra = {}) {
149
+ const preset = PRESETS[name];
150
+ if (!preset) throw new Error(`undo-toast: unknown preset "${name}"; the presets are ${Object.keys(PRESETS).join(", ")}.`);
151
+ return { ...preset.context, ...extra };
152
+ }
153
+ function contextJsonSchema() {
154
+ const properties = {};
155
+ for (const [key, spec] of Object.entries(CONTEXT_FIELDS)) {
156
+ const type = spec.values === "number" ? { type: "number", minimum: 0 } : spec.values === "string" ? { type: "string" } : spec.values.every((v) => typeof v === "boolean") ? { type: "boolean" } : { type: "string", enum: [...spec.values] };
157
+ properties[key] = { ...type, description: spec.describe, ...spec.default === void 0 ? {} : { default: spec.default } };
158
+ }
159
+ return { $schema: "https://json-schema.org/draft/2020-12/schema", title: "ActionContext", type: "object", properties, additionalProperties: false };
160
+ }
161
+
162
+ // src/advise.ts
163
+ var TIMING = {
164
+ /** A timed toast with an action stays at least this long (Polaris' minimum for toasts with an action). */
165
+ actionMs: 1e4,
166
+ /** The window of a deferred action before it is sent (Gmail's choices: 5, 10, 20, 30 s). Let the user set it. */
167
+ deferredMs: 1e4,
168
+ /** Costly actions, when timed, stay at least this long. */
169
+ highCostMs: 15e3,
170
+ /** Words a message may have before reading time adds to the duration. */
171
+ baseWords: 10,
172
+ /** Added per extra word (an estimate: no primary source gives a formula). */
173
+ msPerExtraWord: 250,
174
+ /** Reading time never takes a timed toast past this. */
175
+ maxMs: 2e4,
176
+ /** After a pause, at least this much time is left. */
177
+ resumeMinMs: 4e3,
178
+ /** An irreversible action over more items than this asks the user to type to confirm. An estimate: no design system gives a number, so make it a setting. */
179
+ confirmTypeAbove: 10
180
+ };
181
+ var words = (s) => s ? s.trim().split(/\s+/).filter(Boolean).length : 0;
182
+ var isCostly = (c) => c.cost === "high" || c.count > 1;
183
+ var hasFallback = (c) => c.hasUndoStack || c.hasTrash;
184
+ var R = "docs/research/undo-toast-standard.md";
185
+ var V = "docs/research/bulk-confirm.md";
186
+ function confirmLabel(c) {
187
+ if (!c.verb) return null;
188
+ const text = c.verb.replace(/\{([^{}|]*)\|([^{}|]*)\}/g, (_m, one, other) => c.count === 1 ? one : other);
189
+ if (text.includes("{count}")) return text.replaceAll("{count}", String(c.count));
190
+ return c.count > 1 ? `${text} (${c.count})` : text;
191
+ }
192
+ var confirm = () => ({ surface: "confirm", durationMs: null });
193
+ var RULES = [
194
+ {
195
+ id: "irreversible",
196
+ when: (c) => c.reversal === "none",
197
+ then: (_a, c, t) => ({ ...confirm(), typeToConfirm: c.count > t.confirmTypeAbove }),
198
+ why: 'Nothing can take it back, so an Undo button would lie: ask first, on a button that names the verb and the count ("Pay \u20AC12", "Delete 37 tracks permanently", not "OK"), with type-to-confirm above `timing.confirmTypeAbove` items; then show it pending.',
199
+ source: `${R} \xA76; ${V}`,
200
+ final: true
201
+ },
202
+ {
203
+ id: "bulk-confirm",
204
+ when: (c) => c.reversal === "manual" && c.count > 1,
205
+ then: () => confirm(),
206
+ why: `A bulk action that no single Undo takes back (recoverable only by hand, item by item: from the playlist, from a trash without a one-step restore) asks first, with the count in the verb ("Move 12 items to Trash"), then shows it pending. Recoverable is not reversible. A plain confirmation, not a typed one: the items can still be recovered. To earn an undo toast instead, run the whole selection as one undo step (one history entry, one restore) and say reversal: 'compensating'.`,
207
+ source: V,
208
+ final: true
209
+ },
210
+ {
211
+ id: "manual",
212
+ when: (c) => c.reversal === "manual",
213
+ then: (_a, c) => c.cost === "low" && c.resultStaysInView ? { surface: "none", durationMs: null } : confirm(),
214
+ why: "One item, recoverable only by hand: there is no Undo to offer, so a toast would have nothing to do. If the change stays in view, cheap, it is its own feedback; otherwise ask first, so the user knows what happened and where. Make it compensating (an undo that restores it) to get an undo toast instead.",
215
+ source: V,
216
+ final: true
217
+ },
218
+ {
219
+ id: "fails-often",
220
+ when: (c) => c.failsOften,
221
+ then: () => ({ surface: "pending", durationMs: null }),
222
+ why: "An action that often fails, or whose result the server computes, must not look done: keep the control pending until it is, and report a failure with Retry in a notice that stays until closed.",
223
+ source: `${R} \xA76`,
224
+ final: true
225
+ },
226
+ {
227
+ id: "bulk-one-step-undo",
228
+ when: (c) => c.count > 1 && (c.reversal === "compensating" || c.reversal === "deferred"),
229
+ then: () => ({}),
230
+ why: "A bulk action gets an undo toast, not a confirmation, because one Undo takes the whole operation back in place; a dialog would teach people to click through it. If taking it back meant finding the items one by one, it would be reversal: 'manual' and would ask first (the bulk-confirm rule).",
231
+ source: `${V}; ${R} \xA76`
232
+ },
233
+ {
234
+ id: "result-in-view",
235
+ when: (c) => c.resultStaysInView && !isCostly(c) && c.reversal === "compensating",
236
+ then: () => ({ surface: "none", durationMs: null }),
237
+ why: "The changed thing stays on screen in its new state, so it is its own feedback; a toast for a cheap, visible change is noise. Undo stays available through the app's undo history (Ctrl/Cmd+Z) if it has one.",
238
+ source: `${R} \xA76`,
239
+ final: true
240
+ },
241
+ {
242
+ id: "only-way-back-addition",
243
+ when: (c) => c.reversal === "compensating" && !hasFallback(c) && !c.takesAway,
244
+ then: () => ({ durationMs: null }),
245
+ why: "The toast is the only quick way to take the addition back, so it stays until Undo, Close, Escape, or the next action replaces it (Material 3: a snackbar with an action should remain). Nothing is lost if it goes: no trash or undo history is called for.",
246
+ source: `${R} \xA72`
247
+ },
248
+ {
249
+ id: "only-way-back",
250
+ when: (c) => c.reversal === "compensating" && !hasFallback(c) && c.takesAway,
251
+ then: () => ({ durationMs: null }),
252
+ why: "The toast is the only way to undo, so it stays until Undo, Close, Escape, or the next action replaces it (Material 3: a snackbar with an action should remain; WCAG 2.2.1: a time limit must be adjustable). Give the app an undo history or a trash to make it timed.",
253
+ source: `${R} \xA72`
254
+ },
255
+ {
256
+ id: "undo-elsewhere",
257
+ when: (c) => c.reversal === "compensating" && hasFallback(c),
258
+ then: (_a, _c, t) => ({ durationMs: t.actionMs }),
259
+ why: "Undo is also reachable elsewhere (Ctrl/Cmd+Z, history, trash), so the toast is a shortcut and may leave on its own: 10 s, paused while hovered, focused, touched or hidden.",
260
+ source: `${R} \xA72`
261
+ },
262
+ {
263
+ id: "deferred",
264
+ when: (c) => c.reversal === "deferred",
265
+ then: (_a, _c, t) => ({ durationMs: t.deferredMs, onExpire: "commit", onClose: "commit" }),
266
+ why: "Nothing is sent until the window ends: expiry sends, closing sends at once, a replacing toast sends, and so does `pagehide`. The window is always finite (a held action is stale for other tabs and lost with the tab) and the user should be able to choose its length (`timing.deferredMs`), as Gmail offers 5-30 s.",
267
+ source: `${R} \xA72`
268
+ },
269
+ {
270
+ id: "reading-time",
271
+ when: (c, t) => words(c.message) > t.baseWords,
272
+ then: (a, c, t) => a.durationMs === null ? {} : { durationMs: Math.min(t.maxMs, Math.max(a.durationMs, a.durationMs + (words(c.message) - t.baseWords) * t.msPerExtraWord)) },
273
+ why: "A long message gets reading time on top of a timed toast (an estimate, capped).",
274
+ source: `${R} \xA72`
275
+ },
276
+ {
277
+ id: "high-cost",
278
+ when: isCostly,
279
+ then: (a, _c, t) => a.durationMs === null ? {} : { durationMs: Math.max(a.durationMs, t.highCostMs) },
280
+ why: "A costly mistake (lost work, several items) gets a longer window when the toast is timed.",
281
+ source: `${R} \xA72`
282
+ },
283
+ {
284
+ id: "no-trash",
285
+ when: (c) => isCostly(c) && c.takesAway && c.reversal === "compensating" && !hasFallback(c),
286
+ then: (a) => ({
287
+ warnings: [
288
+ ...a.warnings,
289
+ 'Costly and undoable only from the toast: add a trash or "recently removed" that outlives it, or an undo history, so a replaced or closed toast is not a lost item.'
290
+ ]
291
+ }),
292
+ why: "The toast should be a shortcut, not the only way back; prefer a soft delete. Not for an action that only adds (takesAway: false): a lost toast loses nothing.",
293
+ source: `${R} \xA72`
294
+ },
295
+ {
296
+ id: "keep-notices",
297
+ when: (c) => c.keepNotices && c.reversal === "compensating",
298
+ then: () => ({ durationMs: null }),
299
+ why: "The user asked to keep notices until they close them (WCAG 2.2.1, Timing Adjustable).",
300
+ source: `${R} \xA72`
301
+ },
302
+ {
303
+ id: "frequent",
304
+ when: (c) => c.frequency === "frequent",
305
+ then: () => ({ coalesce: true }),
306
+ why: 'A burst of the same action merges into one toast with a count ("3 items deleted. Undo"); one Undo takes back the whole burst.',
307
+ source: `${R} \xA75`
308
+ },
309
+ {
310
+ id: "undo-stack",
311
+ when: (c) => c.hasUndoStack,
312
+ then: (a) => ({ hotkeys: { ...a.hotkeys, undo: null } }),
313
+ why: "The app's own undo history owns Ctrl/Cmd+Z, and a replaced toast's action stays undoable there.",
314
+ source: `${R} \xA74`
315
+ }
316
+ ];
317
+ function baseAdvice(t) {
318
+ return {
319
+ surface: "toast",
320
+ confirmLabel: null,
321
+ typeToConfirm: false,
322
+ durationMs: t.actionMs,
323
+ resumeMinMs: t.resumeMinMs,
324
+ pauseOn: ["hover", "focus", "touch", "hidden"],
325
+ onExpire: "forget",
326
+ onClose: "forget",
327
+ coalesce: false,
328
+ undoLabel: "Undo",
329
+ closeLabel: "Close notification",
330
+ failedText: "Could not undo.",
331
+ retryLabel: "Try again",
332
+ hotkeys: { focus: "F8", undo: "$mod+z" },
333
+ reasons: [],
334
+ warnings: []
335
+ };
336
+ }
337
+ function advise(action = {}, extra = {}, { rules = RULES, timing, overrides, label = confirmLabel } = {}) {
338
+ const t = { ...TIMING, ...timing };
339
+ const context = resolveContext(typeof action === "string" ? presetContext(action, extra) : { ...action, ...extra });
340
+ let advice = baseAdvice(t);
341
+ for (const rule of rules) {
342
+ if (!rule.when(context, t)) continue;
343
+ advice = { ...advice, ...rule.then(advice, context, t) };
344
+ advice.reasons = [...advice.reasons, { rule: rule.id, why: rule.why, source: rule.source }];
345
+ if (rule.final) break;
346
+ }
347
+ if (overrides && Object.keys(overrides).length) {
348
+ advice = { ...advice, ...overrides };
349
+ advice.reasons = [...advice.reasons, { rule: "override", why: `Set by the host: ${Object.keys(overrides).join(", ")}.`, source: "caller" }];
350
+ }
351
+ if (advice.surface === "confirm" && advice.confirmLabel === null) advice.confirmLabel = label(context);
352
+ return advice;
353
+ }
354
+
355
+ export { CONTEXT_FIELDS, PRESETS, RULES, TIMING, advise, confirmLabel, contextJsonSchema, presetContext, resolveContext };
@@ -0,0 +1,64 @@
1
+ #!/usr/bin/env node
2
+ import { CONTEXT_FIELDS, contextJsonSchema, RULES, advise, PRESETS } from '../chunk-JP44LPGK.js';
3
+ import { parseArgs } from 'util';
4
+
5
+ var kebab = (s) => s.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
6
+ var fields = Object.entries(CONTEXT_FIELDS);
7
+ var isBool = (values) => Array.isArray(values) && values.every((v) => typeof v === "boolean");
8
+ var HELP = `undo-toast: decide how to offer undo for an action.
9
+
10
+ undo-toast advise [preset] [flags] the advice, with the reason for each part (JSON)
11
+ undo-toast fields what you can say about an action
12
+ undo-toast schema the same, as a JSON Schema (for an MCP tool or a form)
13
+ undo-toast presets named actions (remove-item, send, pay, ...)
14
+ undo-toast rules the rules advise applies, in order
15
+
16
+ advise flags:
17
+ ${fields.map(([k, f]) => ` --${kebab(k)}${isBool(f.values) ? "" : " <value>"}`).join("\n")}
18
+ `;
19
+ function main(argv) {
20
+ const [command, ...rest] = argv;
21
+ const out = (value) => process.stdout.write(`${JSON.stringify(value, null, 2)}
22
+ `);
23
+ if (!command || command === "--help" || command === "-h" || command === "help") {
24
+ process.stdout.write(HELP);
25
+ return 0;
26
+ }
27
+ if (command === "fields") return out(CONTEXT_FIELDS), 0;
28
+ if (command === "schema") return out(contextJsonSchema()), 0;
29
+ if (command === "presets") return out(PRESETS), 0;
30
+ if (command === "rules") return out(RULES.map(({ id, why, source, final }) => ({ id, why, source, final: !!final }))), 0;
31
+ if (command !== "advise") {
32
+ process.stderr.write(`undo-toast: unknown command "${command}".
33
+
34
+ ${HELP}`);
35
+ return 2;
36
+ }
37
+ const options = Object.fromEntries(fields.map(([k, f]) => [kebab(k), { type: isBool(f.values) ? "boolean" : "string" }]));
38
+ const booleans = new Map(fields.filter(([, f]) => isBool(f.values)).map(([k]) => [kebab(k), k]));
39
+ const explicit = {};
40
+ const args = rest.filter((arg) => {
41
+ const neg = /^--no-(.+)$/.exec(arg);
42
+ if (neg && booleans.has(neg[1])) return explicit[booleans.get(neg[1])] = false, false;
43
+ const eq = /^--([^=]+)=(true|false)$/.exec(arg);
44
+ if (eq && booleans.has(eq[1])) return explicit[booleans.get(eq[1])] = eq[2] === "true", false;
45
+ return true;
46
+ });
47
+ const { values, positionals } = parseArgs({ args, options, allowPositionals: true, strict: true });
48
+ const context = { ...explicit };
49
+ for (const [k, f] of fields) {
50
+ const v = values[kebab(k)];
51
+ if (v === void 0) continue;
52
+ context[k] = f.values === "number" ? Number(v) : v;
53
+ }
54
+ const preset = positionals[0];
55
+ out(preset ? advise(preset, context) : advise(context));
56
+ return 0;
57
+ }
58
+ try {
59
+ process.exitCode = main(process.argv.slice(2));
60
+ } catch (error) {
61
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}
62
+ `);
63
+ process.exitCode = 1;
64
+ }
@@ -0,0 +1,24 @@
1
+ import { U as UndoOffers } from '../offers-c-kCY6ff.js';
2
+
3
+ /**
4
+ * The framework-free undo toast: the same toast as `undo-toast/react`, drawn with plain DOM calls,
5
+ * for a static site with one vanilla `app.js` (no React, no bundler). Call `mountUndoToast()` once
6
+ * at startup; it creates the polite live region, shows whatever the offer store holds, and returns
7
+ * a function that removes it. The markup and class names are the React toast's, so the same
8
+ * `undo-toast/styles.css` styles both. The page wiring (keys, hidden tab, `pagehide`) is the core's
9
+ * `bindPage`; focus never moves except on F8 and goes back where it came from when the toast leaves.
10
+ * Message text is set with `textContent`, never parsed as HTML.
11
+ */
12
+
13
+ interface MountUndoToastOptions {
14
+ /** The offer store to show. Default: the page's shared one (`getUndoOffers()`). */
15
+ offers?: UndoOffers;
16
+ /** The region's accessible name. */
17
+ regionLabel?: string;
18
+ /** Where to put the region. Default: `document.body`. */
19
+ container?: HTMLElement;
20
+ }
21
+ /** Mount the toast once, always (its live region must exist before a message). Returns `unmount`. */
22
+ declare function mountUndoToast({ offers, regionLabel, container }?: MountUndoToastOptions): () => void;
23
+
24
+ export { type MountUndoToastOptions, mountUndoToast };
@@ -0,0 +1,129 @@
1
+ import { bindPage, getUndoOffers, isApple } from '../chunk-6IIGXUXK.js';
2
+ import '../chunk-JP44LPGK.js';
3
+
4
+ // src/dom/index.ts
5
+ var SVG_NS = "http://www.w3.org/2000/svg";
6
+ var nextId = 0;
7
+ function mountUndoToast({ offers = getUndoOffers(), regionLabel = "Notifications", container } = {}) {
8
+ const region = el("section", "undo-toast-region");
9
+ region.setAttribute("aria-label", regionLabel);
10
+ const live = el("div");
11
+ live.setAttribute("role", "status");
12
+ live.setAttribute("aria-live", "polite");
13
+ live.setAttribute("aria-atomic", "true");
14
+ region.append(live);
15
+ const attach = () => (container ?? document.body).append(region);
16
+ if (container || document.body) attach();
17
+ else document.addEventListener("DOMContentLoaded", attach, { once: true });
18
+ let toast = null;
19
+ let undoButton = null;
20
+ let shownId = null;
21
+ let returnFocus = null;
22
+ const remove = () => {
23
+ if (toast && toast.contains(document.activeElement)) {
24
+ const target = returnFocus;
25
+ returnFocus = null;
26
+ toast.remove();
27
+ if (target?.isConnected) target.focus();
28
+ } else toast?.remove();
29
+ toast = undoButton = null;
30
+ shownId = null;
31
+ };
32
+ const render = () => {
33
+ const view = offers.current();
34
+ if (!view) return remove();
35
+ if (view.id !== shownId) {
36
+ remove();
37
+ ({ toast, undoButton } = build(view, offers, (from) => returnFocus = from));
38
+ shownId = view.id;
39
+ live.append(toast);
40
+ }
41
+ update(toast, undoButton, view);
42
+ };
43
+ const unbind = bindPage(offers, {
44
+ focus: () => {
45
+ const active = document.activeElement;
46
+ if (active instanceof HTMLElement && !toast?.contains(active)) returnFocus = active;
47
+ undoButton?.focus();
48
+ },
49
+ contains: (node) => !!node && !!toast?.contains(node)
50
+ });
51
+ const unsubscribe = offers.subscribe(render);
52
+ render();
53
+ return () => {
54
+ unsubscribe();
55
+ unbind();
56
+ remove();
57
+ region.remove();
58
+ };
59
+ }
60
+ function el(tag, className) {
61
+ const node = document.createElement(tag);
62
+ if (className) node.className = className;
63
+ return node;
64
+ }
65
+ function build(view, offers, rememberFocus) {
66
+ const toast = el("div", "undo-toast");
67
+ const message = el("span", "undo-toast-message");
68
+ message.id = `undo-toast-message-${++nextId}`;
69
+ const undo = el("button", "undo-toast-undo");
70
+ undo.type = "button";
71
+ undo.setAttribute("aria-describedby", message.id);
72
+ undo.addEventListener("click", () => void offers.undo());
73
+ const close = el("button", "undo-toast-close");
74
+ close.type = "button";
75
+ close.setAttribute("aria-label", view.advice.closeLabel);
76
+ close.addEventListener("click", () => offers.close());
77
+ const svg = document.createElementNS(SVG_NS, "svg");
78
+ svg.setAttribute("viewBox", "0 0 16 16");
79
+ svg.setAttribute("width", "16");
80
+ svg.setAttribute("height", "16");
81
+ svg.setAttribute("aria-hidden", "true");
82
+ const path = document.createElementNS(SVG_NS, "path");
83
+ path.setAttribute("d", "M4 4l8 8M12 4l-8 8");
84
+ path.setAttribute("stroke", "currentColor");
85
+ path.setAttribute("stroke-width", "1.75");
86
+ path.setAttribute("stroke-linecap", "round");
87
+ svg.append(path);
88
+ close.append(svg);
89
+ toast.append(message, undo, close);
90
+ toast.addEventListener("pointerenter", (e) => e.pointerType === "mouse" && offers.hold("hover", true));
91
+ toast.addEventListener("pointerleave", (e) => e.pointerType === "mouse" && offers.hold("hover", false));
92
+ toast.addEventListener("pointerdown", (e) => e.pointerType !== "mouse" && offers.hold("touch", true));
93
+ toast.addEventListener("pointerup", (e) => e.pointerType !== "mouse" && offers.hold("touch", false));
94
+ toast.addEventListener("pointercancel", () => offers.hold("touch", false));
95
+ toast.addEventListener("focusin", (e) => {
96
+ const from = e.relatedTarget;
97
+ if (from instanceof HTMLElement && !toast.contains(from)) rememberFocus(from);
98
+ offers.hold("focus", true);
99
+ });
100
+ toast.addEventListener("focusout", (e) => {
101
+ if (!toast.contains(e.relatedTarget)) offers.hold("focus", false);
102
+ });
103
+ return { toast, undoButton: undo };
104
+ }
105
+ function update(toast, undo, view) {
106
+ const { advice, status } = view;
107
+ const failed = status === "failed";
108
+ const undoing = status === "undoing";
109
+ toast.dataset.status = status;
110
+ toast.querySelector(".undo-toast-message").textContent = failed ? `${advice.failedText} ${view.message}` : view.message;
111
+ undo.textContent = failed ? advice.retryLabel : advice.undoLabel;
112
+ if (undoing) {
113
+ undo.setAttribute("aria-disabled", "true");
114
+ undo.setAttribute("aria-busy", "true");
115
+ undo.dataset.pending = "true";
116
+ } else {
117
+ undo.removeAttribute("aria-disabled");
118
+ undo.removeAttribute("aria-busy");
119
+ delete undo.dataset.pending;
120
+ }
121
+ if (advice.hotkeys.undo && !failed) {
122
+ const hint = el("kbd", "undo-toast-hint");
123
+ hint.setAttribute("aria-hidden", "true");
124
+ hint.textContent = isApple() ? "\u2318Z" : "Ctrl+Z";
125
+ undo.append(hint);
126
+ }
127
+ }
128
+
129
+ export { mountUndoToast };
@@ -0,0 +1,74 @@
1
+ import { O as OfferInput, P as PresetName, A as ActionContext, U as UndoOffers } from './offers-c-kCY6ff.js';
2
+ export { a as Advice, b as AdviseOptions, C as CONTEXT_FIELDS, c as OfferView, d as PRESETS, e as PageBinding, f as PauseReason, R as RULES, g as ResolvedContext, h as Rule, S as Surface, T as TIMING, i as Timing, j as UndoOffersOptions, k as advise, l as bindPage, m as confirmLabel, n as contextJsonSchema, o as createUndoOffers, p as defaultIsFailure, q as isEditable, r as matchesHotkey, s as presetContext, t as resolveContext } from './offers-c-kCY6ff.js';
3
+
4
+ /**
5
+ * Offers from the undo machinery the fleet already has, typed by shape only (no import of zodal or
6
+ * acture), so when either changes, this file changes and the apps that use it do not.
7
+ *
8
+ * - `offerFromMutationFeedback`: zodal's `createMutations({ onFeedback })` in `undoable` mode.
9
+ * - `offerFromHistory`: acture-undo's `createUndoHistory(...)` (Ctrl/Cmd+Z history).
10
+ */
11
+
12
+ /** The part of zodal's `MutationFeedback` this needs. */
13
+ interface MutationFeedbackLike {
14
+ kind: string;
15
+ /** Seconds left in the window (on `scheduled`). */
16
+ seconds?: number;
17
+ /** Cancel the scheduled mutation; `false` when it is too late. */
18
+ undo?: () => boolean;
19
+ mutation?: {
20
+ kind?: string;
21
+ itemId?: string;
22
+ };
23
+ }
24
+ /**
25
+ * The offer for a zodal undoable mutation, or null for any feedback other than `scheduled`. zodal
26
+ * owns the window's timer, so the toast lasts exactly as long and does not promise a pause zodal
27
+ * cannot keep (i2mint/zodal#146 asks zodal for one). A too-late undo shows as a failure.
28
+ *
29
+ * @example onFeedback: (f) => { const o = offerFromMutationFeedback(f, { message: 'Row deleted' }); if (o) offerUndo(o); }
30
+ */
31
+ declare function offerFromMutationFeedback(feedback: MutationFeedbackLike, { message, context }: {
32
+ message: OfferInput['message'];
33
+ context?: ActionContext;
34
+ }): OfferInput | null;
35
+ /** The part of acture-undo's `UndoHistory` this needs. */
36
+ interface UndoHistoryLike {
37
+ undo(): {
38
+ readonly ok: boolean;
39
+ } | boolean | void;
40
+ }
41
+ /**
42
+ * The offer for the action an undo history just recorded: Undo rolls the history back one entry,
43
+ * and the advice knows the app owns Ctrl/Cmd+Z (so the toast is timed, and leaves that key alone).
44
+ *
45
+ * @example await registry.dispatch('app.segment.remove', { id }); offerUndo(offerFromHistory(history, { message: '“Intro” removed', context: 'remove-item' }));
46
+ */
47
+ declare function offerFromHistory(history: UndoHistoryLike, { message, context, key }: {
48
+ message: OfferInput['message'];
49
+ context?: PresetName | ActionContext;
50
+ key?: string;
51
+ }): OfferInput;
52
+
53
+ /**
54
+ * undo-toast: decide how to offer undo for an action, then offer it.
55
+ *
56
+ * - `advise(action)` — the agent-first decision: toast or not, how long, what closing means, labels,
57
+ * keys, and the reasons. Rules and numbers are data (`RULES`, `TIMING`); presets name the usual cases.
58
+ * - `createUndoOffers()` / `offerUndo(input)` — the framework-free life of one offer (timer, pauses,
59
+ * replace, coalesce, deferred commit, guarded undo).
60
+ * - `bindPage(offers)` — the page wiring every renderer shares (keys, hidden tab, `pagehide`).
61
+ * - `offerFromMutationFeedback`, `offerFromHistory` — offers from zodal mutations and acture-undo.
62
+ * - `undo-toast/react` — the toast itself; `undo-toast/styles.css` — its look.
63
+ */
64
+
65
+ /** The page's shared offer store (created on first use). `<UndoToast />` shows it by default. */
66
+ declare function getUndoOffers(): UndoOffers;
67
+ /**
68
+ * Offer undo on the shared store: the one-line way.
69
+ *
70
+ * @example offerUndo({ message: '“Intro” removed', undo: () => restore(item), context: 'remove-item' })
71
+ */
72
+ declare function offerUndo(input: OfferInput): number | null;
73
+
74
+ export { ActionContext, type MutationFeedbackLike, OfferInput, PresetName, type UndoHistoryLike, UndoOffers, getUndoOffers, offerFromHistory, offerFromMutationFeedback, offerUndo };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { bindPage, createUndoOffers, defaultIsFailure, getUndoOffers, isEditable, matchesHotkey, offerFromHistory, offerFromMutationFeedback, offerUndo } from './chunk-6IIGXUXK.js';
2
+ export { CONTEXT_FIELDS, PRESETS, RULES, TIMING, advise, confirmLabel, contextJsonSchema, presetContext, resolveContext } from './chunk-JP44LPGK.js';