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.
- package/AGENTS.md +9 -0
- package/LICENSE +21 -0
- package/README.md +120 -2
- package/dist/chunk-6IIGXUXK.js +259 -0
- package/dist/chunk-JP44LPGK.js +355 -0
- package/dist/cli/main.js +64 -0
- package/dist/dom/index.d.ts +24 -0
- package/dist/dom/index.js +129 -0
- package/dist/index.d.ts +74 -0
- package/dist/index.js +2 -0
- package/dist/offers-c-kCY6ff.d.ts +426 -0
- package/dist/react/index.d.ts +57 -0
- package/dist/react/index.js +140 -0
- package/dist/styles.css +118 -0
- package/dist/undo-toast.global.js +1 -0
- package/docs/adr/0001-undo-toast-package.md +48 -0
- package/docs/research/bulk-confirm.md +80 -0
- package/docs/research/undo-toast-standard.md +193 -0
- package/package.json +88 -4
- package/skills/undo-toast/SKILL.md +75 -0
package/AGENTS.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Agent notes for developing undo-toast
|
|
2
|
+
|
|
3
|
+
You are working on the package itself. Agents *using* undo-toast in an app read `skills/undo-toast/SKILL.md` instead.
|
|
4
|
+
|
|
5
|
+
- The decision lives in `src/advise.ts` (`RULES`, ordered, each citing a section of `docs/research/undo-toast-standard.md`; `TIMING`, every number). The vocabulary is `src/spec.ts` (`CONTEXT_FIELDS`, `PRESETS`): the CLI flags, the validation and the types derive from it, so a new field is one entry there (plus a rule that reads it) and a row in the skill's table and the README.
|
|
6
|
+
- The offer's life is `src/offers.ts` (framework-free); the React toast is `src/react/index.tsx`; the look is `src/styles.css` (copied to `dist/` by the build).
|
|
7
|
+
- A rule change is a behaviour change for every host: update its test in `tests/advise.test.ts`, the skill, and the research section it cites.
|
|
8
|
+
- Commands: `npm run typecheck && npm run build && npm test` (the CLI test runs `dist/`, so build first). Definition of done: all green, and `node dist/cli/main.js advise remove-item` prints a toast that stays (`durationMs: null`, rule `only-way-back`).
|
|
9
|
+
- Decision record: `docs/adr/`. Seams: the undo/commit callbacks, the renderer (any subscriber), `rules`/`timing`/`overrides`, `timers`.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Thor Whalen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,121 @@
|
|
|
1
|
-
#
|
|
1
|
+
# undo-toast
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Decide whether and how to offer undo after an action, then offer it: an agent-first decision function, a framework-free offer store, and a React toast that follows the standard (placement, timing, labels, keys, accessibility).
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install undo-toast
|
|
7
|
+
npx undo-toast advise remove-item # what to do, and why (JSON)
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```tsx
|
|
11
|
+
import { offerUndo } from 'undo-toast';
|
|
12
|
+
import { UndoToast } from 'undo-toast/react';
|
|
13
|
+
import 'undo-toast/styles.css';
|
|
14
|
+
|
|
15
|
+
<UndoToast /> // once, near the root
|
|
16
|
+
|
|
17
|
+
removeSegment(item);
|
|
18
|
+
offerUndo({ message: `“${item.title}” removed`, undo: () => restore(item), context: 'remove-item' });
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
**No React?** A static site with one vanilla `app.js` uses the same toast through plain DOM calls: `import { offerUndo } from 'undo-toast'; import { mountUndoToast } from 'undo-toast/dom'` and call `mountUndoToast()` once at startup (it returns an `unmount`). With no bundler at all, load `dist/undo-toast.global.js` (`undo-toast/global`) with a script tag: it defines `UndoToast.offerUndo` and `UndoToast.mountUndoToast`. Same markup, same `styles.css`, same behaviour as the React toast.
|
|
22
|
+
|
|
23
|
+
The toast appears bottom-left on a wide screen and full width at the bottom on a phone. When it is the only way back it stays until Undo, Close or the next action (Material 3, WCAG 2.2.1); when undo is also reachable elsewhere (Ctrl/Cmd+Z, a trash) it leaves after 10 s, longer for long text or costly actions; a deferred action (an undo send) commits when its window ends. The timer pauses while the pointer, the focus or a finger is on the toast and while the tab is hidden. It has an **Undo** button and a **Close** (×) button, never takes focus, and announces itself politely.
|
|
24
|
+
|
|
25
|
+
## The decision
|
|
26
|
+
|
|
27
|
+
`advise(action)` takes a preset name or what you know about the action, and returns the advice with its reasons:
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { advise } from 'undo-toast';
|
|
31
|
+
|
|
32
|
+
advise('pay').surface; // 'confirm': nothing can take it back
|
|
33
|
+
advise('toggle').surface; // 'none': the change is its own feedback
|
|
34
|
+
advise({ reversal: 'deferred', cost: 'high' }); // a 15 s window that commits on expiry or close
|
|
35
|
+
advise('bulk-delete', { count: 12 }).warnings; // ['… add a trash or "recently removed" …']
|
|
36
|
+
advise('remove-item').durationMs; // null: the toast is the only way back, so it stays
|
|
37
|
+
advise('remove-item', { hasUndoStack: true }).durationMs; // 10000
|
|
38
|
+
advise('remove-item').reasons; // [{ rule, why, source }, …]
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
| Field | Values (default first) | Means |
|
|
42
|
+
|---|---|---|
|
|
43
|
+
| `reversal` | `compensating`, `deferred`, `manual`, `none` | one Undo applies the inverse, in place / nothing is sent until the window ends / recoverable only by hand, item by item / cannot be taken back |
|
|
44
|
+
| `cost` | `low`, `high` | what a mistake costs |
|
|
45
|
+
| `frequency` | `occasional`, `rare`, `frequent` | `frequent` coalesces bursts into one toast |
|
|
46
|
+
| `resultStaysInView` | `false`, `true` | the change is visible where it happened (then no toast) |
|
|
47
|
+
| `failsOften` | `false`, `true` | show it pending instead |
|
|
48
|
+
| `count` | `1` | items touched |
|
|
49
|
+
| `hasUndoStack`, `hasTrash` | `false` | the toast is not the only way back |
|
|
50
|
+
| `takesAway` | `true` | the action takes something away (delete, remove, overwrite); `false` for an addition, which needs no trash |
|
|
51
|
+
| `keepNotices` | `false` | the user's "keep notices until closed" setting |
|
|
52
|
+
| `message` | | longer text stays longer |
|
|
53
|
+
| `verb` | | the confirm button's label when the advice is to confirm (`'Move {count} {item|items} to Trash'`) |
|
|
54
|
+
|
|
55
|
+
Presets: `remove-item`, `delete-work`, `bulk-delete`, `move-to-trash`, `bulk-move-to-trash`, `add-to-collection`, `delete-permanently`, `empty-trash`, `archive`, `clear-history`, `forget-secret`, `send`, `toggle`, `pay` (`npx undo-toast presets`). Every rule and number can be replaced: `advise(action, extra, { rules, timing, overrides })`, with `RULES` and `TIMING` exported.
|
|
56
|
+
|
|
57
|
+
### Bulk actions on a selection
|
|
58
|
+
|
|
59
|
+
A bulk action asks for confirmation, with the count, **unless one Undo takes the whole operation back in place**. Recoverable is not reversible: if taking it back means going to the playlist or the Trash and finding the 30 items one by one, say `reversal: 'manual'` and it confirms.
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
advise({ reversal: 'manual', count: 12, verb: 'Move {count} {item|items} to Trash' });
|
|
63
|
+
// { surface: 'confirm', confirmLabel: 'Move 12 items to Trash', reasons: [{ rule: 'bulk-confirm', … }] }
|
|
64
|
+
advise('bulk-move-to-trash', { count: 12 }); // a 15 s toast: one Undo restores the selection
|
|
65
|
+
advise('empty-trash', { count: 40 }).typeToConfirm; // true: irreversible, above timing.confirmTypeAbove (10)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Earn the toast by running the selection as one undo step (one history entry, one restore); the `bulk-one-step-undo` reason says so, for an agent to quote. Delete permanently and Empty Trash always confirm. A `manual` bulk action gets a plain confirmation however large (the items can still be recovered); only irreversible ones are typed. `{one|other}` in `verb` picks the singular at a count of 1, and `advise(…, …, { label })` replaces the wording (translations). Why: [`docs/research/bulk-confirm.md`](docs/research/bulk-confirm.md).
|
|
69
|
+
|
|
70
|
+
## The offer store
|
|
71
|
+
|
|
72
|
+
`createUndoOffers()` holds the offer showing: its timer and pauses (`hold`), `undo` (guarded while it runs; a failure stays on screen with *Try again*), `close`, `flush` (commit a deferred action now; the React toast calls it on `pagehide`), coalescing by `key`, and `subscribe` + `current()` for any renderer. `offerUndo` uses a shared one.
|
|
73
|
+
|
|
74
|
+
For a deferred action (an undo send), pass `commit`: it runs once when the window ends, the toast is closed or replaced, or the page is hidden for good.
|
|
75
|
+
|
|
76
|
+
## From zodal or acture
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
import { offerFromHistory, offerFromMutationFeedback, offerUndo } from 'undo-toast';
|
|
80
|
+
|
|
81
|
+
// acture-undo: after the dispatch
|
|
82
|
+
offerUndo(offerFromHistory(history, { message: '“Intro” removed', context: 'remove-item' }));
|
|
83
|
+
|
|
84
|
+
// zodal undoable mutations
|
|
85
|
+
createMutations(provider, get, set, { mode: 'undoable', onFeedback: (f) => {
|
|
86
|
+
const offer = offerFromMutationFeedback(f, { message: 'Row deleted' });
|
|
87
|
+
if (offer) offerUndo(offer);
|
|
88
|
+
} });
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
An `undo` fails when it throws, rejects, or returns `false` or `{ ok: false }`; the toast then stays with *Try again*, and a deferred action is never committed once Undo was pressed. Another renderer reads `subscribe` + `current()` and calls `bindPage(offers, { focus, contains })` for the keys, the hidden-tab pause and `pagehide`.
|
|
92
|
+
|
|
93
|
+
## Above a docked bar
|
|
94
|
+
|
|
95
|
+
```tsx
|
|
96
|
+
const playerRef = useRef<HTMLDivElement>(null);
|
|
97
|
+
useBottomDock(playerRef); // the toast sits just above the player (floating bars too), or at the bottom when it is gone or slid away
|
|
98
|
+
// a bar that mounts later than this hook: pass the element itself (a callback ref kept in state)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## The host's own buttons
|
|
102
|
+
|
|
103
|
+
An app with its own pressable component (large touch targets, a tap guard, a lockout after a press: an app for users with hand tremor needs all three) draws the controls itself and keeps the toast's policy (timing, pauses, hotkeys, coalescing, failure and *Try again*):
|
|
104
|
+
|
|
105
|
+
```tsx
|
|
106
|
+
<UndoToast renderAction={(a) => (
|
|
107
|
+
<Press ref={a.ref} aria-describedby={a.describedBy} pending={a.pending} onTap={a.onActivate}>{a.label}</Press>
|
|
108
|
+
)} />
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
`a.kind` is `'undo'` or `'close'`; return `undefined` to keep the default control for a kind. A longer offer for an accessibility setting is the host's advice: `offerUndo({ …, advice: { ...advise('remove-item'), durationMs: 15000 } })`.
|
|
112
|
+
|
|
113
|
+
Styles are plain CSS with custom properties (`--undo-toast-bg`, `--undo-toast-fg`, `--undo-toast-accent`, `--undo-toast-gap`, `--undo-toast-z`, …); the toast inherits the page's font.
|
|
114
|
+
|
|
115
|
+
## For agents
|
|
116
|
+
|
|
117
|
+
The shipped skill, `skills/undo-toast/SKILL.md`, is the agent's guide: how to describe an action, how to wire zodal mutations or acture-undo, and the rules any other renderer must keep. The research behind every rule is `docs/research/undo-toast-standard.md`; the design decision is `docs/adr/0001-undo-toast-package.md`.
|
|
118
|
+
|
|
119
|
+
## License
|
|
120
|
+
|
|
121
|
+
MIT
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import { advise } from './chunk-JP44LPGK.js';
|
|
2
|
+
|
|
3
|
+
// src/offers.ts
|
|
4
|
+
var defaultTimers = {
|
|
5
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
6
|
+
clearTimeout: (h) => clearTimeout(h),
|
|
7
|
+
now: () => Date.now()
|
|
8
|
+
};
|
|
9
|
+
var defaultIsFailure = (result) => result === false || typeof result === "object" && result !== null && result.ok === false;
|
|
10
|
+
function createUndoOffers({
|
|
11
|
+
timers = defaultTimers,
|
|
12
|
+
onError = (e, phase) => console.error(`undo-toast: ${phase} failed`, e),
|
|
13
|
+
isFailure = defaultIsFailure
|
|
14
|
+
} = {}) {
|
|
15
|
+
let live = null;
|
|
16
|
+
let queued = null;
|
|
17
|
+
let seq = 0;
|
|
18
|
+
const holds = /* @__PURE__ */ new Set();
|
|
19
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
20
|
+
const emit = () => listeners.forEach((l) => l());
|
|
21
|
+
const textOf = (input, count) => typeof input.message === "function" ? input.message(count) : count > 1 ? `${input.message} (${count})` : input.message;
|
|
22
|
+
const isHeld = (advice) => advice.pauseOn.some((r) => holds.has(r));
|
|
23
|
+
const adviceFor = (input, count) => {
|
|
24
|
+
if (input.advice) return input.advice;
|
|
25
|
+
const context = input.context ?? {};
|
|
26
|
+
return count > 1 ? advise(context, { count }) : advise(context);
|
|
27
|
+
};
|
|
28
|
+
function setView(l, patch) {
|
|
29
|
+
l.view = { ...l.view, ...patch };
|
|
30
|
+
}
|
|
31
|
+
function stopTimer(l) {
|
|
32
|
+
if (!l.running) return;
|
|
33
|
+
timers.clearTimeout(l.timer);
|
|
34
|
+
l.running = false;
|
|
35
|
+
if (l.remaining !== null) l.remaining -= timers.now() - l.startedAt;
|
|
36
|
+
}
|
|
37
|
+
function syncTimer(l) {
|
|
38
|
+
const shouldRun = l.remaining !== null && l.view.status === "shown" && !isHeld(l.view.advice);
|
|
39
|
+
if (shouldRun === l.running) return;
|
|
40
|
+
if (!shouldRun) return stopTimer(l);
|
|
41
|
+
l.startedAt = timers.now();
|
|
42
|
+
l.running = true;
|
|
43
|
+
l.timer = timers.setTimeout(() => {
|
|
44
|
+
if (live === l) retire("expire");
|
|
45
|
+
}, Math.max(0, l.remaining ?? 0));
|
|
46
|
+
}
|
|
47
|
+
function commitAll(entries) {
|
|
48
|
+
for (const e of entries) {
|
|
49
|
+
if (!e.commit) continue;
|
|
50
|
+
try {
|
|
51
|
+
Promise.resolve(e.commit()).catch((err) => onError(err, "commit"));
|
|
52
|
+
} catch (err) {
|
|
53
|
+
onError(err, "commit");
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function show(input, advice, id) {
|
|
58
|
+
const l = {
|
|
59
|
+
view: { id, message: textOf(input, 1), count: 1, advice, status: "shown", paused: isHeld(advice) },
|
|
60
|
+
input,
|
|
61
|
+
entries: [{ undo: input.undo, commit: input.commit }],
|
|
62
|
+
remaining: advice.durationMs,
|
|
63
|
+
startedAt: timers.now(),
|
|
64
|
+
running: false,
|
|
65
|
+
timer: void 0
|
|
66
|
+
};
|
|
67
|
+
live = l;
|
|
68
|
+
syncTimer(l);
|
|
69
|
+
}
|
|
70
|
+
function retire(how) {
|
|
71
|
+
const l = live;
|
|
72
|
+
if (!l) return;
|
|
73
|
+
stopTimer(l);
|
|
74
|
+
live = null;
|
|
75
|
+
const policy = how === "close" ? l.view.advice.onClose : l.view.advice.onExpire;
|
|
76
|
+
if (policy === "commit" && l.view.status === "shown") commitAll(l.entries);
|
|
77
|
+
drainQueue();
|
|
78
|
+
emit();
|
|
79
|
+
}
|
|
80
|
+
function drainQueue() {
|
|
81
|
+
if (live || !queued) return;
|
|
82
|
+
const q = queued;
|
|
83
|
+
queued = null;
|
|
84
|
+
show(q.input, q.advice, q.id);
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
offer(input) {
|
|
88
|
+
const advice = adviceFor(input, 1);
|
|
89
|
+
if (advice.surface === "none") return null;
|
|
90
|
+
if (advice.surface !== "toast") {
|
|
91
|
+
const why = advice.reasons.at(-1)?.why ?? "";
|
|
92
|
+
throw new Error(`undo-toast: this action calls for '${advice.surface}', not an undo toast. ${why}`);
|
|
93
|
+
}
|
|
94
|
+
const l = live;
|
|
95
|
+
if (l && l.view.status === "undoing") {
|
|
96
|
+
if (queued && queued.advice.onExpire === "commit") commitAll([{ undo: queued.input.undo, commit: queued.input.commit }]);
|
|
97
|
+
queued = { input, advice, id: ++seq };
|
|
98
|
+
return queued.id;
|
|
99
|
+
}
|
|
100
|
+
if (l && advice.coalesce && input.key !== void 0 && l.input.key === input.key && l.view.status === "shown") {
|
|
101
|
+
stopTimer(l);
|
|
102
|
+
const count = l.view.count + 1;
|
|
103
|
+
const merged = adviceFor(input, count);
|
|
104
|
+
l.entries.push({ undo: input.undo, commit: input.commit });
|
|
105
|
+
l.remaining = merged.durationMs;
|
|
106
|
+
l.input = input;
|
|
107
|
+
setView(l, { message: textOf(input, count), count, advice: merged, paused: isHeld(merged) });
|
|
108
|
+
syncTimer(l);
|
|
109
|
+
emit();
|
|
110
|
+
return l.view.id;
|
|
111
|
+
}
|
|
112
|
+
if (l) {
|
|
113
|
+
stopTimer(l);
|
|
114
|
+
live = null;
|
|
115
|
+
const policy = l.view.advice.onExpire;
|
|
116
|
+
if (policy === "commit" && l.view.status === "shown") commitAll(l.entries);
|
|
117
|
+
}
|
|
118
|
+
const id = ++seq;
|
|
119
|
+
show(input, advice, id);
|
|
120
|
+
emit();
|
|
121
|
+
return id;
|
|
122
|
+
},
|
|
123
|
+
async undo() {
|
|
124
|
+
const l = live;
|
|
125
|
+
if (!l || l.view.status === "undoing") return false;
|
|
126
|
+
stopTimer(l);
|
|
127
|
+
setView(l, { status: "undoing", error: void 0 });
|
|
128
|
+
emit();
|
|
129
|
+
let failure;
|
|
130
|
+
try {
|
|
131
|
+
while (l.entries.length) {
|
|
132
|
+
const entry = l.entries[l.entries.length - 1];
|
|
133
|
+
const result = await entry.undo();
|
|
134
|
+
if (isFailure(result)) throw new Error("undo-toast: the undo reported failure");
|
|
135
|
+
l.entries.pop();
|
|
136
|
+
}
|
|
137
|
+
} catch (error) {
|
|
138
|
+
failure = error;
|
|
139
|
+
}
|
|
140
|
+
if (failure !== void 0) {
|
|
141
|
+
onError(failure, "undo");
|
|
142
|
+
if (live === l) {
|
|
143
|
+
l.remaining = null;
|
|
144
|
+
setView(l, { status: "failed", error: failure });
|
|
145
|
+
emit();
|
|
146
|
+
}
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
if (live === l) live = null;
|
|
150
|
+
drainQueue();
|
|
151
|
+
emit();
|
|
152
|
+
return true;
|
|
153
|
+
},
|
|
154
|
+
close() {
|
|
155
|
+
retire("close");
|
|
156
|
+
},
|
|
157
|
+
hold(reason, on) {
|
|
158
|
+
if (on === holds.has(reason)) return;
|
|
159
|
+
if (on) holds.add(reason);
|
|
160
|
+
else holds.delete(reason);
|
|
161
|
+
const l = live;
|
|
162
|
+
if (!l) return;
|
|
163
|
+
const wasPaused = l.view.paused;
|
|
164
|
+
const paused = isHeld(l.view.advice);
|
|
165
|
+
if (wasPaused === paused) return;
|
|
166
|
+
if (paused) stopTimer(l);
|
|
167
|
+
else if (l.remaining !== null) l.remaining = Math.max(l.remaining, l.view.advice.resumeMinMs);
|
|
168
|
+
setView(l, { paused });
|
|
169
|
+
syncTimer(l);
|
|
170
|
+
emit();
|
|
171
|
+
},
|
|
172
|
+
flush() {
|
|
173
|
+
if (live && live.view.advice.onExpire === "commit") retire("expire");
|
|
174
|
+
if (queued && queued.advice.onExpire === "commit") {
|
|
175
|
+
commitAll([{ undo: queued.input.undo, commit: queued.input.commit }]);
|
|
176
|
+
queued = null;
|
|
177
|
+
}
|
|
178
|
+
},
|
|
179
|
+
current: () => live?.view ?? null,
|
|
180
|
+
subscribe(listener) {
|
|
181
|
+
listeners.add(listener);
|
|
182
|
+
return () => listeners.delete(listener);
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
function matchesHotkey(event, hotkey, mac = isApple()) {
|
|
187
|
+
if (!hotkey) return false;
|
|
188
|
+
const parts = hotkey.toLowerCase().split("+");
|
|
189
|
+
const key = parts.pop();
|
|
190
|
+
const mod = parts.includes("$mod") || parts.includes("mod");
|
|
191
|
+
const wantMeta = parts.includes("meta") || mod && mac;
|
|
192
|
+
const wantCtrl = parts.includes("ctrl") || mod && !mac;
|
|
193
|
+
return event.key.toLowerCase() === key && event.metaKey === wantMeta && event.ctrlKey === wantCtrl && event.shiftKey === parts.includes("shift") && event.altKey === parts.includes("alt");
|
|
194
|
+
}
|
|
195
|
+
function isApple() {
|
|
196
|
+
return typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
|
|
197
|
+
}
|
|
198
|
+
function isEditable(el) {
|
|
199
|
+
let node = el;
|
|
200
|
+
while (node?.shadowRoot?.activeElement) node = node.shadowRoot.activeElement;
|
|
201
|
+
if (!node) return false;
|
|
202
|
+
const tag = node.tagName;
|
|
203
|
+
return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || node.isContentEditable === true;
|
|
204
|
+
}
|
|
205
|
+
function bindPage(offers, { doc = document, focus, contains } = {}) {
|
|
206
|
+
const win = doc.defaultView;
|
|
207
|
+
const onVisibility = () => offers.hold("hidden", doc.visibilityState === "hidden");
|
|
208
|
+
const onPageHide = () => offers.flush();
|
|
209
|
+
const onKey = (e) => {
|
|
210
|
+
const view = offers.current();
|
|
211
|
+
if (!view || e.defaultPrevented || e.repeat) return;
|
|
212
|
+
const { hotkeys } = view.advice;
|
|
213
|
+
if (focus && matchesHotkey(e, hotkeys.focus)) {
|
|
214
|
+
e.preventDefault();
|
|
215
|
+
focus();
|
|
216
|
+
} else if (matchesHotkey(e, hotkeys.undo) && !isEditable(doc.activeElement)) {
|
|
217
|
+
e.preventDefault();
|
|
218
|
+
void offers.undo();
|
|
219
|
+
} else if (e.key === "Escape" && contains?.(doc.activeElement)) {
|
|
220
|
+
e.preventDefault();
|
|
221
|
+
offers.close();
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
onVisibility();
|
|
225
|
+
doc.addEventListener("visibilitychange", onVisibility);
|
|
226
|
+
win?.addEventListener("pagehide", onPageHide);
|
|
227
|
+
win?.addEventListener("keydown", onKey);
|
|
228
|
+
return () => {
|
|
229
|
+
doc.removeEventListener("visibilitychange", onVisibility);
|
|
230
|
+
win?.removeEventListener("pagehide", onPageHide);
|
|
231
|
+
win?.removeEventListener("keydown", onKey);
|
|
232
|
+
offers.hold("hidden", false);
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// src/adapters.ts
|
|
237
|
+
function offerFromMutationFeedback(feedback, { message, context = {} }) {
|
|
238
|
+
if (feedback.kind !== "scheduled" || !feedback.undo || feedback.seconds === void 0) return null;
|
|
239
|
+
const undo = feedback.undo;
|
|
240
|
+
const advice = advise({ ...context, reversal: "deferred" }, {}, {
|
|
241
|
+
overrides: { durationMs: feedback.seconds * 1e3, pauseOn: [], onExpire: "forget", onClose: "forget" }
|
|
242
|
+
});
|
|
243
|
+
return { message, undo: () => undo(), advice };
|
|
244
|
+
}
|
|
245
|
+
function offerFromHistory(history, { message, context = {}, key }) {
|
|
246
|
+
const advice = typeof context === "string" ? advise(context, { hasUndoStack: true }) : advise({ ...context, hasUndoStack: true });
|
|
247
|
+
return { message, undo: () => history.undo(), advice, ...key === void 0 ? {} : { key } };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// src/index.ts
|
|
251
|
+
var shared;
|
|
252
|
+
function getUndoOffers() {
|
|
253
|
+
return shared ??= createUndoOffers();
|
|
254
|
+
}
|
|
255
|
+
function offerUndo(input) {
|
|
256
|
+
return getUndoOffers().offer(input);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export { bindPage, createUndoOffers, defaultIsFailure, getUndoOffers, isApple, isEditable, matchesHotkey, offerFromHistory, offerFromMutationFeedback, offerUndo };
|