@weasel-js/history 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +23 -0
- package/dist/index.d.ts +234 -0
- package/dist/index.js +371 -0
- package/dist/index.js.map +1 -0
- package/package.json +41 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 orochi235
|
|
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
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# @weasel-js/history
|
|
2
|
+
|
|
3
|
+
Undo/redo history with scoped sub-history (Journal) primitive. No React, no DOM.
|
|
4
|
+
|
|
5
|
+
Part of [weasel](https://github.com/orochi235/weasel), a domain-agnostic 2D
|
|
6
|
+
scene-graph canvas kit for React. See the
|
|
7
|
+
[API reference](https://orochi235.github.io/weasel/api/).
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install @weasel-js/history
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { /* … */ } from '@weasel-js/history';
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## License
|
|
22
|
+
|
|
23
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An invertible mutation. Applied via an adapter; produces an inverse op
|
|
3
|
+
* that, when applied to the same adapter, undoes the original.
|
|
4
|
+
*
|
|
5
|
+
* Adapters are intentionally typed loosely here so different op types can
|
|
6
|
+
* require different adapter capabilities. Each op is responsible for
|
|
7
|
+
* narrowing the adapter via the methods it calls.
|
|
8
|
+
*
|
|
9
|
+
* Lives here rather than in `@weasel-js/core` because an invertible,
|
|
10
|
+
* replayable mutation is a history concept: this package is what pushes ops
|
|
11
|
+
* onto a stack, inverts them, coalesces them, and rebuilds them from a
|
|
12
|
+
* serialized snapshot. Nothing about the shape is core-specific — it names no
|
|
13
|
+
* scene, node, or pose type. Core re-exports it from `core/ops/types` so its
|
|
14
|
+
* own call sites read unchanged.
|
|
15
|
+
*/
|
|
16
|
+
interface Op {
|
|
17
|
+
/** Apply the mutation. Return `false` (or `'noop'`) to signal that
|
|
18
|
+
* nothing changed — the history layer then skips pushing an undo
|
|
19
|
+
* entry for the batch when *every* op reports no-op. Returning
|
|
20
|
+
* `undefined`/`void` means "mutated" (the common case; existing ops
|
|
21
|
+
* don't need to change). */
|
|
22
|
+
apply(adapter: unknown): void | boolean | 'noop';
|
|
23
|
+
invert(): Op;
|
|
24
|
+
label?: string;
|
|
25
|
+
coalesceKey?: string;
|
|
26
|
+
/** Stable factory name for op-registry lookup. Kit-emitted ops always
|
|
27
|
+
* set this; consumer ops without a name can't round-trip through
|
|
28
|
+
* `History.serialize()` and are dropped from persisted snapshots. */
|
|
29
|
+
name?: string;
|
|
30
|
+
/** Serializable args (JSON / structured-clone-safe) that, paired with
|
|
31
|
+
* `name`, reconstruct the op via the registry's `rebuildOp`. */
|
|
32
|
+
args?: unknown;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface BeginJournalOptions {
|
|
36
|
+
label: string;
|
|
37
|
+
targetId?: string;
|
|
38
|
+
}
|
|
39
|
+
interface Journal {
|
|
40
|
+
readonly targetId: string | undefined;
|
|
41
|
+
readonly forkedAtEntryId: number;
|
|
42
|
+
applyBatch(ops: Op[], label: string): void;
|
|
43
|
+
undo(): void;
|
|
44
|
+
redo(): void;
|
|
45
|
+
canUndo(): boolean;
|
|
46
|
+
canRedo(): boolean;
|
|
47
|
+
entries(): {
|
|
48
|
+
undo: HistoryEntry[];
|
|
49
|
+
redo: HistoryEntry[];
|
|
50
|
+
};
|
|
51
|
+
commit(label: string): void;
|
|
52
|
+
cancel(): void;
|
|
53
|
+
suspend(): void;
|
|
54
|
+
isActive(): boolean;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Wire form of a single op inside a serialized history. The pair
|
|
58
|
+
* `(name, args)` reconstructs a live `Op` via the op-factory registry. */
|
|
59
|
+
interface SerializedOp {
|
|
60
|
+
name: string;
|
|
61
|
+
args: unknown;
|
|
62
|
+
}
|
|
63
|
+
/** Wire form of one history entry. `forwardOps` / `baseOps` mirror the
|
|
64
|
+
* in-memory entry's fields (see `Entry` above) but only carry the
|
|
65
|
+
* serializable `(name, args)` projection of each op. */
|
|
66
|
+
interface SerializedHistoryEntry {
|
|
67
|
+
id: number;
|
|
68
|
+
label: string;
|
|
69
|
+
forwardOps: SerializedOp[];
|
|
70
|
+
baseOps: SerializedOp[];
|
|
71
|
+
}
|
|
72
|
+
/** Snapshot of an entire `History` instance. Designed to live alongside the
|
|
73
|
+
* scene snapshot in IDB so a reload restores the undo / redo stacks to
|
|
74
|
+
* exactly where they were. */
|
|
75
|
+
interface SerializedHistory {
|
|
76
|
+
version: 1;
|
|
77
|
+
undoStack: SerializedHistoryEntry[];
|
|
78
|
+
/** Stored newest-first, mirroring the in-memory stack so a deserialized
|
|
79
|
+
* history matches the original's `entries().redo` ordering. */
|
|
80
|
+
redoStack: SerializedHistoryEntry[];
|
|
81
|
+
nextEntryId: number;
|
|
82
|
+
/** Entries dropped because at least one of their ops lacked a `name`
|
|
83
|
+
* and therefore couldn't round-trip through the op-factory registry.
|
|
84
|
+
* Always present (zero when nothing was dropped) so callers can detect
|
|
85
|
+
* loss without parsing the debug log. */
|
|
86
|
+
droppedEntries: number;
|
|
87
|
+
}
|
|
88
|
+
/** Snapshot of an entry handed to `onEvict` when it permanently leaves the
|
|
89
|
+
* reachable stacks. Ops are live references — read `name`/`args`, don't
|
|
90
|
+
* mutate. */
|
|
91
|
+
interface EvictedEntry {
|
|
92
|
+
id: number;
|
|
93
|
+
label: string;
|
|
94
|
+
forwardOps: readonly Op[];
|
|
95
|
+
baseOps: readonly Op[];
|
|
96
|
+
}
|
|
97
|
+
/** Read-only view of a history entry exposed via `History.entries()`. */
|
|
98
|
+
interface HistoryEntry {
|
|
99
|
+
/** Stable monotonic id (preserved across coalesce merges). */
|
|
100
|
+
id: number;
|
|
101
|
+
/** Human-readable label (the `label` arg passed to `applyOps`). */
|
|
102
|
+
label: string;
|
|
103
|
+
/** Push/last-coalesce timestamp (ms). */
|
|
104
|
+
timestamp: number;
|
|
105
|
+
/** Set of node ids touched by any op in this entry. Populated from ops
|
|
106
|
+
* whose `args` carry an `id` field (transform, setPath, reparent) or a
|
|
107
|
+
* `node.id` field (insert, delete). Ops without a recognisable id field
|
|
108
|
+
* contribute nothing. May be `undefined` for deserialized entries
|
|
109
|
+
* restored from an older snapshot that predates this field. */
|
|
110
|
+
touchedIds?: ReadonlySet<string>;
|
|
111
|
+
}
|
|
112
|
+
/** Op-batched undo/redo controller returned by `createHistory`. */
|
|
113
|
+
interface History {
|
|
114
|
+
apply(op: Op, label?: string): void;
|
|
115
|
+
applyOps(ops: Op[], label: string): void;
|
|
116
|
+
undo(): void;
|
|
117
|
+
redo(): void;
|
|
118
|
+
canUndo(): boolean;
|
|
119
|
+
canRedo(): boolean;
|
|
120
|
+
/** Number of entries on the undo stack (O(1); `entries().undo.length`
|
|
121
|
+
* without materializing the views). */
|
|
122
|
+
undoDepth(): number;
|
|
123
|
+
/** Number of entries on the redo stack (O(1)). */
|
|
124
|
+
redoDepth(): number;
|
|
125
|
+
clear(): void;
|
|
126
|
+
/** Snapshot of the current undo + redo stacks. `undo` is oldest→newest
|
|
127
|
+
* (i.e. the last element is what `undo()` would pop next); `redo` is
|
|
128
|
+
* also oldest→newest from the user's perspective (i.e. the *first*
|
|
129
|
+
* element is what `redo()` would pop next — see implementation note).
|
|
130
|
+
* Callers should treat the arrays as immutable. */
|
|
131
|
+
entries(): {
|
|
132
|
+
undo: HistoryEntry[];
|
|
133
|
+
redo: HistoryEntry[];
|
|
134
|
+
};
|
|
135
|
+
/** Walk the history forward/back until exactly `n` entries are on the
|
|
136
|
+
* undo stack (0 ≤ n ≤ entries().undo.length + entries().redo.length).
|
|
137
|
+
* Equivalent to repeated `undo()`/`redo()` calls but doesn't bother
|
|
138
|
+
* rebuilding entry snapshots between steps. No-op if already at `n`. */
|
|
139
|
+
goto(n: number): void;
|
|
140
|
+
/** Monotonic counter bumped on every push/undo/redo/clear/coalesce.
|
|
141
|
+
* Cheap to read; callers use it as a React dep to detect changes. */
|
|
142
|
+
getVersion(): number;
|
|
143
|
+
/** Subscribe to history changes. Fires after every push/undo/redo/
|
|
144
|
+
* clear/coalesce. Returns an unsubscribe fn. */
|
|
145
|
+
subscribe(listener: () => void): () => void;
|
|
146
|
+
/** Snapshot the undo + redo stacks in a structured-clone-safe form.
|
|
147
|
+
* Entries whose ops aren't all kit-registered (i.e. any op missing a
|
|
148
|
+
* `name`) are dropped from the snapshot with a debug-level log — they
|
|
149
|
+
* can't round-trip, so we omit them rather than emit a half-restorable
|
|
150
|
+
* entry. The in-memory stacks aren't modified. */
|
|
151
|
+
serialize(): SerializedHistory;
|
|
152
|
+
/** Replace the current undo + redo stacks with the deserialized contents
|
|
153
|
+
* of `snapshot`. Ops are rebuilt via the `rebuildOp` option when
|
|
154
|
+
* provided, then the global registry; unknown names become no-op
|
|
155
|
+
* placeholders so stack ordering survives across kit-version skew.
|
|
156
|
+
* Bumps `version` and notifies subscribers exactly once. */
|
|
157
|
+
restore(snapshot: SerializedHistory): void;
|
|
158
|
+
/** Push an entry whose ops have already been applied to the adapter.
|
|
159
|
+
* Unlike `applyOps`, does NOT call `op.apply()`. Used by Journal.commit
|
|
160
|
+
* to flush a session's net forward ops to the parent as one entry without
|
|
161
|
+
* re-mutating the scene. */
|
|
162
|
+
recordEntry(ops: Op[], label: string): void;
|
|
163
|
+
/** Concatenated forwardOps of every undo-stack entry, in order. Snapshot
|
|
164
|
+
* of "what changes are currently applied via this history" — useful for
|
|
165
|
+
* Journal.commit to flush to a parent, and for any caller that wants to
|
|
166
|
+
* diff against a baseline. */
|
|
167
|
+
allForwardOps(): Op[];
|
|
168
|
+
/** The id that will be assigned to the *next* pushed entry. Stable
|
|
169
|
+
* monotonic counter; callers use it to tag a fork point (see Journal). */
|
|
170
|
+
currentEntryId(): number;
|
|
171
|
+
/** Open a scoped sub-history. All apply/undo/redo on the returned Journal
|
|
172
|
+
* affect the same adapter; on commit, the Journal's net forward ops are
|
|
173
|
+
* flushed to this History as one entry. See spec docs/superpowers/specs/
|
|
174
|
+
* 2026-05-24-modality-design.md for the full lifecycle. */
|
|
175
|
+
beginJournal(opts: BeginJournalOptions): Journal;
|
|
176
|
+
/** Re-activate a suspended journal. Throws if the journal was committed or
|
|
177
|
+
* cancelled (those are terminal). Staleness checking is the caller's
|
|
178
|
+
* responsibility — consult `journal.forkedAtEntryId` against
|
|
179
|
+
* `currentEntryId()` and your own op-semantic rules to decide whether
|
|
180
|
+
* to resume or discard before calling this. */
|
|
181
|
+
resumeJournal(journal: Journal): void;
|
|
182
|
+
}
|
|
183
|
+
/** Options for `createHistory`. */
|
|
184
|
+
interface CreateHistoryOptions {
|
|
185
|
+
/** Window (ms) within which a new entry may merge into the previous one
|
|
186
|
+
* via matching `Op.coalesceKey`. Defaults to `0` (no coalescing — every
|
|
187
|
+
* `applyOps` pushes a discrete entry). Recommended: ~500ms for typical
|
|
188
|
+
* rapid-input UX (nudge, per-keystroke text edits). The window resets on
|
|
189
|
+
* each successful coalesce, so a sustained burst keeps merging. */
|
|
190
|
+
coalesceWindowMs?: number;
|
|
191
|
+
/** Clock injection point for tests. Defaults to `Date.now`. */
|
|
192
|
+
now?: () => number;
|
|
193
|
+
/** Maximum undo-stack depth. When a push overflows the cap the oldest
|
|
194
|
+
* entry is evicted (reported via `onEvict`) and can no longer be undone.
|
|
195
|
+
* `0` disables the undo stack entirely — every push is evicted
|
|
196
|
+
* synchronously (negative values are clamped to `0`). Default: unbounded. */
|
|
197
|
+
historyLimit?: number;
|
|
198
|
+
/** Fired once per entry that permanently leaves the reachable stacks:
|
|
199
|
+
* redo entries dropped by a branch edit (a new push / coalesce /
|
|
200
|
+
* `recordEntry` after undo) and undo entries evicted by `historyLimit`.
|
|
201
|
+
* NOT fired by `clear()` or `restore()` — those wholesale-replace the
|
|
202
|
+
* history and the caller already knows. Note `restore()` does not enforce
|
|
203
|
+
* `historyLimit` either: a restored snapshot may exceed the cap, which
|
|
204
|
+
* re-applies (evicting via `onEvict`) on the next push. */
|
|
205
|
+
onEvict?: (entry: EvictedEntry) => void;
|
|
206
|
+
/** Custom op rebuilder consulted by `restore()` before the global
|
|
207
|
+
* op-factory registry. Return `null` to fall through (global registry,
|
|
208
|
+
* then a no-op placeholder). Lets an owner rebuild ops whose handlers
|
|
209
|
+
* live in per-instance state the global registry can't reach (e.g. a
|
|
210
|
+
* Scene's registered op kinds).
|
|
211
|
+
*
|
|
212
|
+
* May be invoked more than once per entry with the same `(name, args)` —
|
|
213
|
+
* once per op for `forwardOps` and again for `baseOps` (the same array
|
|
214
|
+
* until a coalesce splits them). Unlike `onEvict`, a throwing hook is
|
|
215
|
+
* NOT caught: it aborts `restore()` mid-rebuild and can leave the
|
|
216
|
+
* stacks partially rebuilt. */
|
|
217
|
+
rebuildOp?: (name: string, args: unknown) => Op | null;
|
|
218
|
+
/** Diagnostics sink. Omitted, the engine is silent — it deliberately owns no
|
|
219
|
+
* logging utility, so that this package depends on nothing. `@weasel-js/core`'s
|
|
220
|
+
* `createHistory` wrapper routes these into its `debug/flag` namespace, which
|
|
221
|
+
* is what makes `DEBUG=history` work for kit consumers. */
|
|
222
|
+
debug?: HistoryLogger;
|
|
223
|
+
}
|
|
224
|
+
/** Diagnostics sink for {@link CreateHistoryOptions.debug}. Messages arrive
|
|
225
|
+
* pre-formatted and unconditional; deciding whether to emit them is the
|
|
226
|
+
* caller's job. */
|
|
227
|
+
interface HistoryLogger {
|
|
228
|
+
log(message: string): void;
|
|
229
|
+
warn(message: string): void;
|
|
230
|
+
}
|
|
231
|
+
/** Build an op-batched undo/redo `History`. The adapter is passed to each op's `apply`/`invert`. */
|
|
232
|
+
declare function createHistory(adapter: unknown, options?: CreateHistoryOptions): History;
|
|
233
|
+
|
|
234
|
+
export { type BeginJournalOptions, type CreateHistoryOptions, type EvictedEntry, type History, type HistoryEntry, type HistoryLogger, type Journal, type Op, type SerializedHistory, type SerializedHistoryEntry, type SerializedOp, createHistory };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
// src/journal.ts
|
|
2
|
+
var RESUMERS = /* @__PURE__ */ new WeakMap();
|
|
3
|
+
function _resumeJournalInternal(j) {
|
|
4
|
+
const r = RESUMERS.get(j);
|
|
5
|
+
if (!r) throw new Error("Journal is not resumable (already committed or cancelled)");
|
|
6
|
+
r();
|
|
7
|
+
}
|
|
8
|
+
function createJournalInternal(parent, adapter, opts, onClose) {
|
|
9
|
+
const inner = createHistory(adapter);
|
|
10
|
+
const forkedAtEntryId = parent.currentEntryId();
|
|
11
|
+
let state = "active";
|
|
12
|
+
const targetId = opts.targetId;
|
|
13
|
+
const journal = {
|
|
14
|
+
targetId,
|
|
15
|
+
forkedAtEntryId,
|
|
16
|
+
applyBatch(ops, label) {
|
|
17
|
+
if (state !== "active") throw new Error("Journal is not active");
|
|
18
|
+
inner.applyOps(ops, label);
|
|
19
|
+
},
|
|
20
|
+
undo() {
|
|
21
|
+
if (state !== "active") throw new Error("Journal is not active");
|
|
22
|
+
inner.undo();
|
|
23
|
+
},
|
|
24
|
+
redo() {
|
|
25
|
+
if (state !== "active") throw new Error("Journal is not active");
|
|
26
|
+
inner.redo();
|
|
27
|
+
},
|
|
28
|
+
canUndo() {
|
|
29
|
+
return inner.canUndo();
|
|
30
|
+
},
|
|
31
|
+
canRedo() {
|
|
32
|
+
return inner.canRedo();
|
|
33
|
+
},
|
|
34
|
+
entries() {
|
|
35
|
+
return inner.entries();
|
|
36
|
+
},
|
|
37
|
+
commit(label) {
|
|
38
|
+
if (state !== "active") throw new Error("Journal is not active");
|
|
39
|
+
const netOps = inner.allForwardOps();
|
|
40
|
+
if (netOps.length > 0) {
|
|
41
|
+
parent.recordEntry(netOps, label);
|
|
42
|
+
}
|
|
43
|
+
state = "closed";
|
|
44
|
+
RESUMERS.delete(journal);
|
|
45
|
+
onClose?.();
|
|
46
|
+
},
|
|
47
|
+
cancel() {
|
|
48
|
+
if (state !== "active") throw new Error("Journal is not active");
|
|
49
|
+
inner.goto(0);
|
|
50
|
+
state = "closed";
|
|
51
|
+
RESUMERS.delete(journal);
|
|
52
|
+
onClose?.();
|
|
53
|
+
},
|
|
54
|
+
suspend() {
|
|
55
|
+
if (state !== "active") throw new Error("Journal is not active");
|
|
56
|
+
state = "suspended";
|
|
57
|
+
onClose?.();
|
|
58
|
+
},
|
|
59
|
+
isActive() {
|
|
60
|
+
return state === "active";
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
RESUMERS.set(journal, () => {
|
|
64
|
+
if (state !== "suspended") throw new Error("Journal is not suspended");
|
|
65
|
+
state = "active";
|
|
66
|
+
});
|
|
67
|
+
return journal;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// src/history.ts
|
|
71
|
+
var SILENT = { log: () => {
|
|
72
|
+
}, warn: () => {
|
|
73
|
+
} };
|
|
74
|
+
function createHistory(adapter, options = {}) {
|
|
75
|
+
const undoStack = [];
|
|
76
|
+
const redoStack = [];
|
|
77
|
+
let activeJournal = null;
|
|
78
|
+
const coalesceWindowMs = options.coalesceWindowMs ?? 0;
|
|
79
|
+
const now = options.now ?? (() => Date.now());
|
|
80
|
+
const historyLimit = Math.max(0, options.historyLimit ?? Infinity);
|
|
81
|
+
const onEvict = options.onEvict;
|
|
82
|
+
const customRebuild = options.rebuildOp;
|
|
83
|
+
const logger = options.debug ?? SILENT;
|
|
84
|
+
let nextEntryId = 1;
|
|
85
|
+
let version = 0;
|
|
86
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
87
|
+
function bump() {
|
|
88
|
+
version++;
|
|
89
|
+
for (const l of listeners) l();
|
|
90
|
+
}
|
|
91
|
+
function reportEvicted(entries) {
|
|
92
|
+
if (!onEvict) return;
|
|
93
|
+
for (const e of entries) {
|
|
94
|
+
try {
|
|
95
|
+
onEvict({ id: e.id, label: e.label, forwardOps: e.forwardOps, baseOps: e.baseOps });
|
|
96
|
+
} catch (err) {
|
|
97
|
+
logger.warn(`onEvict callback threw for entry id=${e.id} "${e.label}": ${String(err)}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function dropRedo() {
|
|
102
|
+
if (redoStack.length === 0) return;
|
|
103
|
+
reportEvicted(redoStack.splice(0));
|
|
104
|
+
}
|
|
105
|
+
function enforceLimit() {
|
|
106
|
+
while (undoStack.length > historyLimit) {
|
|
107
|
+
reportEvicted([undoStack.shift()]);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function applyOps(ops) {
|
|
111
|
+
for (const op of ops) op.apply(adapter);
|
|
112
|
+
}
|
|
113
|
+
function applyOpsAndDetectMutation(ops) {
|
|
114
|
+
let anyMutated = false;
|
|
115
|
+
for (const op of ops) {
|
|
116
|
+
const r = op.apply(adapter);
|
|
117
|
+
if (r !== false && r !== "noop") anyMutated = true;
|
|
118
|
+
}
|
|
119
|
+
return anyMutated;
|
|
120
|
+
}
|
|
121
|
+
function invertEntry(entry) {
|
|
122
|
+
return [...entry.baseOps].reverse().map((op) => op.invert());
|
|
123
|
+
}
|
|
124
|
+
function canCoalesce(top, incoming) {
|
|
125
|
+
if (coalesceWindowMs <= 0) return false;
|
|
126
|
+
if (now() - top.timestamp > coalesceWindowMs) return false;
|
|
127
|
+
if (top.forwardOps.length === 0 || incoming.length === 0) return false;
|
|
128
|
+
if (top.forwardOps.length !== incoming.length) return false;
|
|
129
|
+
const counts = /* @__PURE__ */ new Map();
|
|
130
|
+
for (const op of top.forwardOps) {
|
|
131
|
+
const k = op.coalesceKey;
|
|
132
|
+
if (k === void 0) return false;
|
|
133
|
+
counts.set(k, (counts.get(k) ?? 0) + 1);
|
|
134
|
+
}
|
|
135
|
+
for (const op of incoming) {
|
|
136
|
+
const k = op.coalesceKey;
|
|
137
|
+
if (k === void 0) return false;
|
|
138
|
+
const c = counts.get(k);
|
|
139
|
+
if (!c) return false;
|
|
140
|
+
counts.set(k, c - 1);
|
|
141
|
+
}
|
|
142
|
+
return true;
|
|
143
|
+
}
|
|
144
|
+
function pushOrCoalesce(ops, label) {
|
|
145
|
+
if (ops.length === 0) return;
|
|
146
|
+
const anyMutated = applyOpsAndDetectMutation(ops);
|
|
147
|
+
if (!anyMutated) {
|
|
148
|
+
logger.warn(
|
|
149
|
+
`'${label}' batch was a no-op \u2014 every op reported false/'noop'. Skipping the undo entry; consider gating the dispatch upstream to avoid the wasted work.`
|
|
150
|
+
);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const incoming = touchedIdsFromOps(ops);
|
|
154
|
+
const top = undoStack[undoStack.length - 1];
|
|
155
|
+
if (top && canCoalesce(top, ops)) {
|
|
156
|
+
top.forwardOps = ops;
|
|
157
|
+
top.timestamp = now();
|
|
158
|
+
if (incoming.size > 0) {
|
|
159
|
+
const merged = new Set(top.touchedIds);
|
|
160
|
+
for (const id of incoming) merged.add(id);
|
|
161
|
+
top.touchedIds = merged;
|
|
162
|
+
}
|
|
163
|
+
dropRedo();
|
|
164
|
+
logger.log(`coalesce '${label}' into entry id=${top.id} (${ops.length} ops)`);
|
|
165
|
+
bump();
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
logger.log(`push '${label}' (${ops.length} ops)`);
|
|
169
|
+
undoStack.push({ id: nextEntryId++, forwardOps: ops, baseOps: ops, label, timestamp: now(), touchedIds: incoming });
|
|
170
|
+
dropRedo();
|
|
171
|
+
enforceLimit();
|
|
172
|
+
bump();
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
apply(op, label) {
|
|
176
|
+
pushOrCoalesce([op], label ?? op.label ?? "");
|
|
177
|
+
},
|
|
178
|
+
applyOps(ops, label) {
|
|
179
|
+
pushOrCoalesce(ops, label);
|
|
180
|
+
},
|
|
181
|
+
undo() {
|
|
182
|
+
const entry = undoStack.pop();
|
|
183
|
+
if (!entry) return;
|
|
184
|
+
applyOps(invertEntry(entry));
|
|
185
|
+
redoStack.push(entry);
|
|
186
|
+
bump();
|
|
187
|
+
},
|
|
188
|
+
redo() {
|
|
189
|
+
const entry = redoStack.pop();
|
|
190
|
+
if (!entry) return;
|
|
191
|
+
applyOps(entry.forwardOps);
|
|
192
|
+
undoStack.push(entry);
|
|
193
|
+
bump();
|
|
194
|
+
},
|
|
195
|
+
canUndo: () => undoStack.length > 0,
|
|
196
|
+
canRedo: () => redoStack.length > 0,
|
|
197
|
+
undoDepth: () => undoStack.length,
|
|
198
|
+
redoDepth: () => redoStack.length,
|
|
199
|
+
clear: () => {
|
|
200
|
+
const had = undoStack.length > 0 || redoStack.length > 0;
|
|
201
|
+
undoStack.length = 0;
|
|
202
|
+
redoStack.length = 0;
|
|
203
|
+
if (had) bump();
|
|
204
|
+
},
|
|
205
|
+
entries() {
|
|
206
|
+
const toView = (e) => ({ id: e.id, label: e.label, timestamp: e.timestamp, touchedIds: e.touchedIds });
|
|
207
|
+
return {
|
|
208
|
+
undo: undoStack.map(toView),
|
|
209
|
+
redo: [...redoStack].reverse().map(toView)
|
|
210
|
+
};
|
|
211
|
+
},
|
|
212
|
+
goto(n) {
|
|
213
|
+
const total = undoStack.length + redoStack.length;
|
|
214
|
+
if (n < 0 || n > total) return;
|
|
215
|
+
while (undoStack.length > n) {
|
|
216
|
+
const entry = undoStack.pop();
|
|
217
|
+
applyOps(invertEntry(entry));
|
|
218
|
+
redoStack.push(entry);
|
|
219
|
+
}
|
|
220
|
+
while (undoStack.length < n) {
|
|
221
|
+
const entry = redoStack.pop();
|
|
222
|
+
if (!entry) break;
|
|
223
|
+
applyOps(entry.forwardOps);
|
|
224
|
+
undoStack.push(entry);
|
|
225
|
+
}
|
|
226
|
+
bump();
|
|
227
|
+
},
|
|
228
|
+
getVersion: () => version,
|
|
229
|
+
subscribe(listener) {
|
|
230
|
+
listeners.add(listener);
|
|
231
|
+
return () => {
|
|
232
|
+
listeners.delete(listener);
|
|
233
|
+
};
|
|
234
|
+
},
|
|
235
|
+
serialize() {
|
|
236
|
+
let dropped = 0;
|
|
237
|
+
const project = (e) => {
|
|
238
|
+
const s = entryToSerial(e, logger);
|
|
239
|
+
if (s === null) dropped++;
|
|
240
|
+
return s;
|
|
241
|
+
};
|
|
242
|
+
return {
|
|
243
|
+
version: 1,
|
|
244
|
+
undoStack: undoStack.map(project).filter((e) => e !== null),
|
|
245
|
+
redoStack: redoStack.map(project).filter((e) => e !== null),
|
|
246
|
+
nextEntryId,
|
|
247
|
+
droppedEntries: dropped
|
|
248
|
+
};
|
|
249
|
+
},
|
|
250
|
+
recordEntry(ops, label) {
|
|
251
|
+
if (ops.length === 0) return;
|
|
252
|
+
undoStack.push({ id: nextEntryId++, forwardOps: ops, baseOps: ops, label, timestamp: now(), touchedIds: touchedIdsFromOps(ops) });
|
|
253
|
+
dropRedo();
|
|
254
|
+
enforceLimit();
|
|
255
|
+
bump();
|
|
256
|
+
},
|
|
257
|
+
allForwardOps() {
|
|
258
|
+
const out = [];
|
|
259
|
+
for (const e of undoStack) {
|
|
260
|
+
for (const op of e.forwardOps) out.push(op);
|
|
261
|
+
}
|
|
262
|
+
return out;
|
|
263
|
+
},
|
|
264
|
+
currentEntryId() {
|
|
265
|
+
return nextEntryId;
|
|
266
|
+
},
|
|
267
|
+
beginJournal(opts) {
|
|
268
|
+
if (activeJournal !== null && activeJournal.isActive()) {
|
|
269
|
+
throw new Error("A journal is already active \u2014 commit, cancel, or suspend it first");
|
|
270
|
+
}
|
|
271
|
+
const j = createJournalInternal(this, adapter, opts, () => {
|
|
272
|
+
activeJournal = null;
|
|
273
|
+
});
|
|
274
|
+
activeJournal = j;
|
|
275
|
+
return j;
|
|
276
|
+
},
|
|
277
|
+
resumeJournal(journal) {
|
|
278
|
+
_resumeJournalInternal(journal);
|
|
279
|
+
},
|
|
280
|
+
restore(snapshot) {
|
|
281
|
+
undoStack.length = 0;
|
|
282
|
+
redoStack.length = 0;
|
|
283
|
+
for (const se of snapshot.undoStack) {
|
|
284
|
+
undoStack.push(serialToEntry(se, customRebuild, logger));
|
|
285
|
+
}
|
|
286
|
+
for (const se of snapshot.redoStack) {
|
|
287
|
+
redoStack.push(serialToEntry(se, customRebuild, logger));
|
|
288
|
+
}
|
|
289
|
+
nextEntryId = snapshot.nextEntryId;
|
|
290
|
+
for (const e of undoStack) if (e.id >= nextEntryId) nextEntryId = e.id + 1;
|
|
291
|
+
for (const e of redoStack) if (e.id >= nextEntryId) nextEntryId = e.id + 1;
|
|
292
|
+
bump();
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
function touchedIdsFromOps(ops) {
|
|
297
|
+
const ids = /* @__PURE__ */ new Set();
|
|
298
|
+
for (const op of ops) {
|
|
299
|
+
if (op.args === null || typeof op.args !== "object") continue;
|
|
300
|
+
const a = op.args;
|
|
301
|
+
if (typeof a["id"] === "string") {
|
|
302
|
+
ids.add(a["id"]);
|
|
303
|
+
} else if (a["node"] !== null && typeof a["node"] === "object") {
|
|
304
|
+
const n = a["node"];
|
|
305
|
+
if (typeof n["id"] === "string") ids.add(n["id"]);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return ids;
|
|
309
|
+
}
|
|
310
|
+
function opToSerial(op) {
|
|
311
|
+
if (typeof op.name !== "string") return null;
|
|
312
|
+
return { name: op.name, args: op.args };
|
|
313
|
+
}
|
|
314
|
+
function entryToSerial(e, logger) {
|
|
315
|
+
const forwardOps = [];
|
|
316
|
+
for (const op of e.forwardOps) {
|
|
317
|
+
const s = opToSerial(op);
|
|
318
|
+
if (s === null) {
|
|
319
|
+
logger.log(`serialize: dropping entry id=${e.id} "${e.label}" \u2014 forwardOp without name`);
|
|
320
|
+
return null;
|
|
321
|
+
}
|
|
322
|
+
forwardOps.push(s);
|
|
323
|
+
}
|
|
324
|
+
const baseOps = [];
|
|
325
|
+
for (const op of e.baseOps) {
|
|
326
|
+
const s = opToSerial(op);
|
|
327
|
+
if (s === null) {
|
|
328
|
+
logger.log(`serialize: dropping entry id=${e.id} "${e.label}" \u2014 baseOp without name`);
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
baseOps.push(s);
|
|
332
|
+
}
|
|
333
|
+
return { id: e.id, label: e.label, forwardOps, baseOps };
|
|
334
|
+
}
|
|
335
|
+
function placeholderOp(name, args, label) {
|
|
336
|
+
const op = {
|
|
337
|
+
name,
|
|
338
|
+
args,
|
|
339
|
+
label,
|
|
340
|
+
apply: () => "noop",
|
|
341
|
+
invert: () => op
|
|
342
|
+
};
|
|
343
|
+
return op;
|
|
344
|
+
}
|
|
345
|
+
function rebuildSerialOp(so, label, custom, logger) {
|
|
346
|
+
const viaCustom = custom ? custom(so.name, so.args) : null;
|
|
347
|
+
if (viaCustom !== null) return viaCustom;
|
|
348
|
+
logger.log(`restore: unknown op name "${so.name}" \u2014 substituting no-op placeholder`);
|
|
349
|
+
return placeholderOp(so.name, so.args, label);
|
|
350
|
+
}
|
|
351
|
+
function serialToEntry(se, custom, logger) {
|
|
352
|
+
const forwardOps = se.forwardOps.map((so) => rebuildSerialOp(so, se.label, custom, logger));
|
|
353
|
+
const baseOps = se.baseOps.map((so) => rebuildSerialOp(so, se.label, custom, logger));
|
|
354
|
+
return {
|
|
355
|
+
id: se.id,
|
|
356
|
+
label: se.label,
|
|
357
|
+
forwardOps,
|
|
358
|
+
baseOps,
|
|
359
|
+
// Restored entries inherit a "now" timestamp — coalesce eligibility is
|
|
360
|
+
// a within-session concept and a restored entry shouldn't merge with a
|
|
361
|
+
// freshly-typed one regardless of when it was originally pushed.
|
|
362
|
+
timestamp: 0,
|
|
363
|
+
// Re-derive touchedIds from the rebuilt ops rather than trying to
|
|
364
|
+
// round-trip the Set through the serialized form (Sets aren't JSON-safe).
|
|
365
|
+
touchedIds: touchedIdsFromOps(forwardOps)
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export { createHistory };
|
|
370
|
+
//# sourceMappingURL=index.js.map
|
|
371
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/journal.ts","../src/history.ts"],"names":[],"mappings":";AAGA,IAAM,QAAA,uBAAe,OAAA,EAA6B;AAG3C,SAAS,uBAAuB,CAAA,EAAkB;AACvD,EAAA,MAAM,CAAA,GAAI,QAAA,CAAS,GAAA,CAAI,CAAC,CAAA;AACxB,EAAA,IAAI,CAAC,CAAA,EAAG,MAAM,IAAI,MAAM,2DAA2D,CAAA;AACnF,EAAA,CAAA,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AA,EAAO,MAAA,EAAQ,MAAM,CAAC,CAAA;AACpF,EAAA,OAAO;AAAA,IACL,IAAI,EAAA,CAAG,EAAA;AAAA,IACP,OAAO,EAAA,CAAG,KAAA;AAAA,IACV,UAAA;AAAA,IACA,OAAA;AAAA;AAAA;AAAA;AAAA,IAIA,SAAA,EAAW,CAAA;AAAA;AAAA;AAAA,IAGX,UAAA,EAAY,kBAAkB,UAAU;AAAA,GAC1C;AACF","file":"index.js","sourcesContent":["import type { Op } from './op';\nimport { createHistory, type History, type HistoryEntry } from './history';\n\nconst RESUMERS = new WeakMap<Journal, () => void>();\n\n/** Called by `history.resumeJournal`. Not part of the public API. */\nexport function _resumeJournalInternal(j: Journal): void {\n const r = RESUMERS.get(j);\n if (!r) throw new Error('Journal is not resumable (already committed or cancelled)');\n r();\n}\n\nexport interface BeginJournalOptions {\n label: string;\n targetId?: string;\n}\n\nexport interface Journal {\n readonly targetId: string | undefined;\n readonly forkedAtEntryId: number;\n\n // Same operational surface as History\n applyBatch(ops: Op[], label: string): void;\n undo(): void;\n redo(): void;\n canUndo(): boolean;\n canRedo(): boolean;\n entries(): { undo: HistoryEntry[]; redo: HistoryEntry[] };\n\n // Lifecycle\n commit(label: string): void;\n cancel(): void;\n suspend(): void;\n isActive(): boolean;\n}\n\n/** Internal factory used by `createHistory`'s `beginJournal` method.\n * Not exported via the package's `index.ts` — callers go through\n * `history.beginJournal()`. */\nexport function createJournalInternal(\n parent: History,\n adapter: unknown,\n opts: BeginJournalOptions,\n onClose?: () => void,\n): Journal {\n const inner = createHistory(adapter);\n const forkedAtEntryId = parent.currentEntryId();\n type State = 'active' | 'suspended' | 'closed';\n let state: State = 'active';\n const targetId = opts.targetId;\n\n const journal: Journal = {\n targetId,\n forkedAtEntryId,\n\n applyBatch(ops: Op[], label: string): void {\n if (state !== 'active') throw new Error('Journal is not active');\n inner.applyOps(ops, label);\n },\n undo(): void {\n if (state !== 'active') throw new Error('Journal is not active');\n inner.undo();\n },\n redo(): void {\n if (state !== 'active') throw new Error('Journal is not active');\n inner.redo();\n },\n canUndo(): boolean {\n return inner.canUndo();\n },\n canRedo(): boolean {\n return inner.canRedo();\n },\n entries() {\n return inner.entries();\n },\n commit(label: string): void {\n if (state !== 'active') throw new Error('Journal is not active');\n const netOps = inner.allForwardOps();\n if (netOps.length > 0) {\n parent.recordEntry(netOps, label);\n }\n state = 'closed';\n RESUMERS.delete(journal);\n onClose?.();\n },\n cancel(): void {\n if (state !== 'active') throw new Error('Journal is not active');\n inner.goto(0);\n state = 'closed';\n RESUMERS.delete(journal);\n onClose?.();\n },\n suspend(): void {\n if (state !== 'active') throw new Error('Journal is not active');\n state = 'suspended';\n onClose?.();\n },\n isActive(): boolean {\n return state === 'active';\n },\n };\n\n RESUMERS.set(journal, () => {\n if (state !== 'suspended') throw new Error('Journal is not suspended');\n state = 'active';\n });\n\n return journal;\n}\n","import type { Op } from './op';\nimport { createJournalInternal, _resumeJournalInternal, type Journal, type BeginJournalOptions } from './journal';\n\ninterface Entry {\n /** Monotonic id assigned at first push. Stable across coalesce merges\n * (a merged entry keeps the original id) so UI lists keyed on `id` don't\n * flicker when the underlying entry mutates. */\n id: number;\n /** Forward ops — applied on redo, reflect the latest to-state after any\n * coalescing. Diverges from `baseOps` only after a coalesce. */\n forwardOps: Op[];\n /** Original ops at first push — their `.invert()` is what undo replays.\n * Preserved across coalesces so undo always returns to the original\n * pre-edit state, no matter how many coalesces happened. */\n baseOps: Op[];\n label: string;\n /** ms timestamp at last push or coalesce; used to gate the coalesce window. */\n timestamp: number;\n /** Node ids touched by ops in this entry. See `HistoryEntry.touchedIds`. */\n touchedIds: ReadonlySet<string>;\n}\n\n/** Wire form of a single op inside a serialized history. The pair\n * `(name, args)` reconstructs a live `Op` via the op-factory registry. */\nexport interface SerializedOp {\n name: string;\n args: unknown;\n}\n\n/** Wire form of one history entry. `forwardOps` / `baseOps` mirror the\n * in-memory entry's fields (see `Entry` above) but only carry the\n * serializable `(name, args)` projection of each op. */\nexport interface SerializedHistoryEntry {\n id: number;\n label: string;\n forwardOps: SerializedOp[];\n baseOps: SerializedOp[];\n}\n\n/** Snapshot of an entire `History` instance. Designed to live alongside the\n * scene snapshot in IDB so a reload restores the undo / redo stacks to\n * exactly where they were. */\nexport interface SerializedHistory {\n version: 1;\n undoStack: SerializedHistoryEntry[];\n /** Stored newest-first, mirroring the in-memory stack so a deserialized\n * history matches the original's `entries().redo` ordering. */\n redoStack: SerializedHistoryEntry[];\n nextEntryId: number;\n /** Entries dropped because at least one of their ops lacked a `name`\n * and therefore couldn't round-trip through the op-factory registry.\n * Always present (zero when nothing was dropped) so callers can detect\n * loss without parsing the debug log. */\n droppedEntries: number;\n}\n\n/** Snapshot of an entry handed to `onEvict` when it permanently leaves the\n * reachable stacks. Ops are live references — read `name`/`args`, don't\n * mutate. */\nexport interface EvictedEntry {\n id: number;\n label: string;\n forwardOps: readonly Op[];\n baseOps: readonly Op[];\n}\n\n/** Read-only view of a history entry exposed via `History.entries()`. */\nexport interface HistoryEntry {\n /** Stable monotonic id (preserved across coalesce merges). */\n id: number;\n /** Human-readable label (the `label` arg passed to `applyOps`). */\n label: string;\n /** Push/last-coalesce timestamp (ms). */\n timestamp: number;\n /** Set of node ids touched by any op in this entry. Populated from ops\n * whose `args` carry an `id` field (transform, setPath, reparent) or a\n * `node.id` field (insert, delete). Ops without a recognisable id field\n * contribute nothing. May be `undefined` for deserialized entries\n * restored from an older snapshot that predates this field. */\n touchedIds?: ReadonlySet<string>;\n}\n\n/** Op-batched undo/redo controller returned by `createHistory`. */\nexport interface History {\n apply(op: Op, label?: string): void;\n applyOps(ops: Op[], label: string): void;\n undo(): void;\n redo(): void;\n canUndo(): boolean;\n canRedo(): boolean;\n /** Number of entries on the undo stack (O(1); `entries().undo.length`\n * without materializing the views). */\n undoDepth(): number;\n /** Number of entries on the redo stack (O(1)). */\n redoDepth(): number;\n clear(): void;\n /** Snapshot of the current undo + redo stacks. `undo` is oldest→newest\n * (i.e. the last element is what `undo()` would pop next); `redo` is\n * also oldest→newest from the user's perspective (i.e. the *first*\n * element is what `redo()` would pop next — see implementation note).\n * Callers should treat the arrays as immutable. */\n entries(): { undo: HistoryEntry[]; redo: HistoryEntry[] };\n /** Walk the history forward/back until exactly `n` entries are on the\n * undo stack (0 ≤ n ≤ entries().undo.length + entries().redo.length).\n * Equivalent to repeated `undo()`/`redo()` calls but doesn't bother\n * rebuilding entry snapshots between steps. No-op if already at `n`. */\n goto(n: number): void;\n /** Monotonic counter bumped on every push/undo/redo/clear/coalesce.\n * Cheap to read; callers use it as a React dep to detect changes. */\n getVersion(): number;\n /** Subscribe to history changes. Fires after every push/undo/redo/\n * clear/coalesce. Returns an unsubscribe fn. */\n subscribe(listener: () => void): () => void;\n /** Snapshot the undo + redo stacks in a structured-clone-safe form.\n * Entries whose ops aren't all kit-registered (i.e. any op missing a\n * `name`) are dropped from the snapshot with a debug-level log — they\n * can't round-trip, so we omit them rather than emit a half-restorable\n * entry. The in-memory stacks aren't modified. */\n serialize(): SerializedHistory;\n /** Replace the current undo + redo stacks with the deserialized contents\n * of `snapshot`. Ops are rebuilt via the `rebuildOp` option when\n * provided, then the global registry; unknown names become no-op\n * placeholders so stack ordering survives across kit-version skew.\n * Bumps `version` and notifies subscribers exactly once. */\n restore(snapshot: SerializedHistory): void;\n /** Push an entry whose ops have already been applied to the adapter.\n * Unlike `applyOps`, does NOT call `op.apply()`. Used by Journal.commit\n * to flush a session's net forward ops to the parent as one entry without\n * re-mutating the scene. */\n recordEntry(ops: Op[], label: string): void;\n /** Concatenated forwardOps of every undo-stack entry, in order. Snapshot\n * of \"what changes are currently applied via this history\" — useful for\n * Journal.commit to flush to a parent, and for any caller that wants to\n * diff against a baseline. */\n allForwardOps(): Op[];\n /** The id that will be assigned to the *next* pushed entry. Stable\n * monotonic counter; callers use it to tag a fork point (see Journal). */\n currentEntryId(): number;\n /** Open a scoped sub-history. All apply/undo/redo on the returned Journal\n * affect the same adapter; on commit, the Journal's net forward ops are\n * flushed to this History as one entry. See spec docs/superpowers/specs/\n * 2026-05-24-modality-design.md for the full lifecycle. */\n beginJournal(opts: BeginJournalOptions): Journal;\n /** Re-activate a suspended journal. Throws if the journal was committed or\n * cancelled (those are terminal). Staleness checking is the caller's\n * responsibility — consult `journal.forkedAtEntryId` against\n * `currentEntryId()` and your own op-semantic rules to decide whether\n * to resume or discard before calling this. */\n resumeJournal(journal: Journal): void;\n}\n\n/** Options for `createHistory`. */\nexport interface CreateHistoryOptions {\n /** Window (ms) within which a new entry may merge into the previous one\n * via matching `Op.coalesceKey`. Defaults to `0` (no coalescing — every\n * `applyOps` pushes a discrete entry). Recommended: ~500ms for typical\n * rapid-input UX (nudge, per-keystroke text edits). The window resets on\n * each successful coalesce, so a sustained burst keeps merging. */\n coalesceWindowMs?: number;\n /** Clock injection point for tests. Defaults to `Date.now`. */\n now?: () => number;\n /** Maximum undo-stack depth. When a push overflows the cap the oldest\n * entry is evicted (reported via `onEvict`) and can no longer be undone.\n * `0` disables the undo stack entirely — every push is evicted\n * synchronously (negative values are clamped to `0`). Default: unbounded. */\n historyLimit?: number;\n /** Fired once per entry that permanently leaves the reachable stacks:\n * redo entries dropped by a branch edit (a new push / coalesce /\n * `recordEntry` after undo) and undo entries evicted by `historyLimit`.\n * NOT fired by `clear()` or `restore()` — those wholesale-replace the\n * history and the caller already knows. Note `restore()` does not enforce\n * `historyLimit` either: a restored snapshot may exceed the cap, which\n * re-applies (evicting via `onEvict`) on the next push. */\n onEvict?: (entry: EvictedEntry) => void;\n /** Custom op rebuilder consulted by `restore()` before the global\n * op-factory registry. Return `null` to fall through (global registry,\n * then a no-op placeholder). Lets an owner rebuild ops whose handlers\n * live in per-instance state the global registry can't reach (e.g. a\n * Scene's registered op kinds).\n *\n * May be invoked more than once per entry with the same `(name, args)` —\n * once per op for `forwardOps` and again for `baseOps` (the same array\n * until a coalesce splits them). Unlike `onEvict`, a throwing hook is\n * NOT caught: it aborts `restore()` mid-rebuild and can leave the\n * stacks partially rebuilt. */\n rebuildOp?: (name: string, args: unknown) => Op | null;\n /** Diagnostics sink. Omitted, the engine is silent — it deliberately owns no\n * logging utility, so that this package depends on nothing. `@weasel-js/core`'s\n * `createHistory` wrapper routes these into its `debug/flag` namespace, which\n * is what makes `DEBUG=history` work for kit consumers. */\n debug?: HistoryLogger;\n}\n\n/** Diagnostics sink for {@link CreateHistoryOptions.debug}. Messages arrive\n * pre-formatted and unconditional; deciding whether to emit them is the\n * caller's job. */\nexport interface HistoryLogger {\n log(message: string): void;\n warn(message: string): void;\n}\n\n/** Silent default — keeps every call site unconditional. */\nconst SILENT: HistoryLogger = { log: () => {}, warn: () => {} };\n\n/** Build an op-batched undo/redo `History`. The adapter is passed to each op's `apply`/`invert`. */\nexport function createHistory(adapter: unknown, options: CreateHistoryOptions = {}): History {\n const undoStack: Entry[] = [];\n const redoStack: Entry[] = [];\n let activeJournal: Journal | null = null;\n const coalesceWindowMs = options.coalesceWindowMs ?? 0;\n const now = options.now ?? (() => Date.now());\n const historyLimit = Math.max(0, options.historyLimit ?? Infinity);\n const onEvict = options.onEvict;\n const customRebuild = options.rebuildOp;\n const logger = options.debug ?? SILENT;\n let nextEntryId = 1;\n let version = 0;\n const listeners = new Set<() => void>();\n function bump(): void {\n version++;\n for (const l of listeners) l();\n }\n\n /** Report entries that just became permanently unreachable. A throwing\n * callback must not desync the stacks mid-mutation, so failures are\n * contained and surfaced via the debug flag. */\n function reportEvicted(entries: Entry[]): void {\n if (!onEvict) return;\n for (const e of entries) {\n try {\n onEvict({ id: e.id, label: e.label, forwardOps: e.forwardOps, baseOps: e.baseOps });\n } catch (err) {\n logger.warn(`onEvict callback threw for entry id=${e.id} \"${e.label}\": ${String(err)}`);\n }\n }\n }\n\n /** Clear the redo stack (branch-on-edit), reporting dropped entries. */\n function dropRedo(): void {\n if (redoStack.length === 0) return;\n reportEvicted(redoStack.splice(0));\n }\n\n /** Evict the oldest undo entries past `historyLimit`, reporting each. */\n function enforceLimit(): void {\n while (undoStack.length > historyLimit) {\n reportEvicted([undoStack.shift()!]);\n }\n }\n\n function applyOps(ops: Op[]): void {\n for (const op of ops) op.apply(adapter);\n }\n\n /** Apply each op and collect whether any reported a real mutation.\n * Returns true iff at least one op did NOT explicitly return `false` /\n * `'noop'`. Used by `pushOrCoalesce` to skip pushing entries when every\n * op in the batch was a silent no-op (e.g. reorder where the order\n * already matched). Existing ops that return `undefined`/`void` count\n * as \"mutated\" — the default — so this is backwards-compatible. */\n function applyOpsAndDetectMutation(ops: Op[]): boolean {\n let anyMutated = false;\n for (const op of ops) {\n const r = op.apply(adapter);\n if (r !== false && r !== 'noop') anyMutated = true;\n }\n return anyMutated;\n }\n\n function invertEntry(entry: Entry): Op[] {\n return [...entry.baseOps].reverse().map((op) => op.invert());\n }\n\n /** Coalesce eligibility: every op on both sides has a `coalesceKey`, and\n * the multisets of keys match (order-independent). Match by multiset\n * rather than positional index so a multi-id selection can re-emit ops in\n * any order between batches without breaking the merge. */\n function canCoalesce(top: Entry, incoming: Op[]): boolean {\n if (coalesceWindowMs <= 0) return false;\n if (now() - top.timestamp > coalesceWindowMs) return false;\n if (top.forwardOps.length === 0 || incoming.length === 0) return false;\n if (top.forwardOps.length !== incoming.length) return false;\n const counts = new Map<string, number>();\n for (const op of top.forwardOps) {\n const k = op.coalesceKey;\n if (k === undefined) return false;\n counts.set(k, (counts.get(k) ?? 0) + 1);\n }\n for (const op of incoming) {\n const k = op.coalesceKey;\n if (k === undefined) return false;\n const c = counts.get(k);\n if (!c) return false;\n counts.set(k, c - 1);\n }\n return true;\n }\n\n function pushOrCoalesce(ops: Op[], label: string): void {\n if (ops.length === 0) return;\n const anyMutated = applyOpsAndDetectMutation(ops);\n if (!anyMutated) {\n // Every op reported `false`/`'noop'`. Skip the push so undo stays\n // tied to real state changes. Surfaced through the kit's debug\n // flag so the upstream caller can consider avoiding the dispatch\n // entirely. Hidden by default; enable via\n // `localStorage.setItem('weasel.debug', '1')`.\n logger.warn(\n `'${label}' batch was a no-op — every op reported false/'noop'. ` +\n `Skipping the undo entry; consider gating the dispatch upstream to avoid the wasted work.`,\n );\n return;\n }\n const incoming = touchedIdsFromOps(ops);\n const top = undoStack[undoStack.length - 1];\n if (top && canCoalesce(top, ops)) {\n top.forwardOps = ops;\n top.timestamp = now();\n // Merge incoming touched ids into the coalesced entry's set.\n if (incoming.size > 0) {\n const merged = new Set(top.touchedIds);\n for (const id of incoming) merged.add(id);\n top.touchedIds = merged;\n }\n // baseOps + label + id intentionally preserved — undo returns to the\n // pre-edit state, the original label sticks, and the entry id stays\n // stable so React lists keyed on id don't flicker.\n dropRedo();\n logger.log(`coalesce '${label}' into entry id=${top.id} (${ops.length} ops)`);\n bump();\n return;\n }\n logger.log(`push '${label}' (${ops.length} ops)`);\n undoStack.push({ id: nextEntryId++, forwardOps: ops, baseOps: ops, label, timestamp: now(), touchedIds: incoming });\n dropRedo();\n enforceLimit();\n bump();\n }\n\n return {\n apply(op, label) {\n pushOrCoalesce([op], label ?? op.label ?? '');\n },\n applyOps(ops, label) {\n pushOrCoalesce(ops, label);\n },\n undo() {\n const entry = undoStack.pop();\n if (!entry) return;\n applyOps(invertEntry(entry));\n redoStack.push(entry);\n bump();\n },\n redo() {\n const entry = redoStack.pop();\n if (!entry) return;\n applyOps(entry.forwardOps);\n undoStack.push(entry);\n bump();\n },\n canUndo: () => undoStack.length > 0,\n canRedo: () => redoStack.length > 0,\n undoDepth: () => undoStack.length,\n redoDepth: () => redoStack.length,\n clear: () => {\n const had = undoStack.length > 0 || redoStack.length > 0;\n undoStack.length = 0;\n redoStack.length = 0;\n if (had) bump();\n },\n entries() {\n const toView = (e: Entry): HistoryEntry => ({ id: e.id, label: e.label, timestamp: e.timestamp, touchedIds: e.touchedIds });\n // redoStack is internally stored newest-on-top (so `pop()` redoes the\n // next-most-recent undo). Reverse on the way out so callers see the\n // entries in chronological order — the user's next redo is the first\n // element, matching `entries().redo[0]` semantics.\n return {\n undo: undoStack.map(toView),\n redo: [...redoStack].reverse().map(toView),\n };\n },\n goto(n) {\n // Total length stays constant during this walk (we only shuffle\n // entries between undo and redo stacks).\n const total = undoStack.length + redoStack.length;\n if (n < 0 || n > total) return;\n while (undoStack.length > n) {\n const entry = undoStack.pop()!;\n applyOps(invertEntry(entry));\n redoStack.push(entry);\n }\n while (undoStack.length < n) {\n const entry = redoStack.pop();\n if (!entry) break; // defensive — shouldn't fire given the bounds check above\n applyOps(entry.forwardOps);\n undoStack.push(entry);\n }\n bump();\n },\n getVersion: () => version,\n subscribe(listener) {\n listeners.add(listener);\n return () => { listeners.delete(listener); };\n },\n serialize(): SerializedHistory {\n let dropped = 0;\n const project = (e: Entry): SerializedHistoryEntry | null => {\n const s = entryToSerial(e, logger);\n if (s === null) dropped++;\n return s;\n };\n return {\n version: 1,\n undoStack: undoStack.map(project).filter((e): e is SerializedHistoryEntry => e !== null),\n redoStack: redoStack.map(project).filter((e): e is SerializedHistoryEntry => e !== null),\n nextEntryId,\n droppedEntries: dropped,\n };\n },\n recordEntry(ops: Op[], label: string): void {\n if (ops.length === 0) return;\n undoStack.push({ id: nextEntryId++, forwardOps: ops, baseOps: ops, label, timestamp: now(), touchedIds: touchedIdsFromOps(ops) });\n dropRedo();\n enforceLimit();\n bump();\n },\n allForwardOps(): Op[] {\n const out: Op[] = [];\n for (const e of undoStack) {\n for (const op of e.forwardOps) out.push(op);\n }\n return out;\n },\n currentEntryId(): number {\n return nextEntryId;\n },\n beginJournal(opts: BeginJournalOptions): Journal {\n if (activeJournal !== null && activeJournal.isActive()) {\n throw new Error('A journal is already active — commit, cancel, or suspend it first');\n }\n // `adapter` is the closure-captured adapter passed to createHistory.\n // The returned History object's `this` doesn't carry it, so we pass\n // it through to the factory directly.\n const j = createJournalInternal(this, adapter, opts, () => { activeJournal = null; });\n activeJournal = j;\n return j;\n },\n resumeJournal(journal: Journal): void {\n _resumeJournalInternal(journal);\n },\n restore(snapshot: SerializedHistory): void {\n undoStack.length = 0;\n redoStack.length = 0;\n for (const se of snapshot.undoStack) {\n undoStack.push(serialToEntry(se, customRebuild, logger));\n }\n for (const se of snapshot.redoStack) {\n redoStack.push(serialToEntry(se, customRebuild, logger));\n }\n // Seed nextEntryId from the snapshot, then defensively bump past any\n // restored id — a malformed snapshot with duplicate or out-of-range\n // ids should never produce a collision with future entries.\n nextEntryId = snapshot.nextEntryId;\n for (const e of undoStack) if (e.id >= nextEntryId) nextEntryId = e.id + 1;\n for (const e of redoStack) if (e.id >= nextEntryId) nextEntryId = e.id + 1;\n bump();\n },\n };\n}\n\n/** Extract node ids from an op's `args`. Handles the common patterns:\n * - `args.id` (string) — transform, setPath, reparent\n * - `args.node.id` (string) — insert, delete\n * Ops that don't match either pattern contribute nothing.\n * Exported for in-package test use; not part of the published package API. */\nexport function touchedIdsFromOps(ops: Op[]): ReadonlySet<string> {\n const ids = new Set<string>();\n for (const op of ops) {\n if (op.args === null || typeof op.args !== 'object') continue;\n const a = op.args as Record<string, unknown>;\n if (typeof a['id'] === 'string') {\n ids.add(a['id']);\n } else if (a['node'] !== null && typeof a['node'] === 'object') {\n const n = a['node'] as Record<string, unknown>;\n if (typeof n['id'] === 'string') ids.add(n['id']);\n }\n }\n return ids;\n}\n\n/** Project an `Op` to its `(name, args)` wire form. Returns `null` for ops\n * missing `name` — the caller drops the containing entry. */\nfunction opToSerial(op: Op): SerializedOp | null {\n if (typeof op.name !== 'string') return null;\n return { name: op.name, args: op.args };\n}\n\n/** Project a runtime entry to its serialized form, or `null` if any op in\n * the entry can't be serialized (we drop the whole entry then — a partially\n * serializable entry would invert against the wrong baseline on undo). */\nfunction entryToSerial(e: Entry, logger: HistoryLogger): SerializedHistoryEntry | null {\n const forwardOps: SerializedOp[] = [];\n for (const op of e.forwardOps) {\n const s = opToSerial(op);\n if (s === null) {\n logger.log(`serialize: dropping entry id=${e.id} \"${e.label}\" — forwardOp without name`);\n return null;\n }\n forwardOps.push(s);\n }\n const baseOps: SerializedOp[] = [];\n for (const op of e.baseOps) {\n const s = opToSerial(op);\n if (s === null) {\n logger.log(`serialize: dropping entry id=${e.id} \"${e.label}\" — baseOp without name`);\n return null;\n }\n baseOps.push(s);\n }\n return { id: e.id, label: e.label, forwardOps, baseOps };\n}\n\n/** Placeholder op used when the registry lacks the requested name. Stable\n * identity (each placeholder is its own invert) keeps undo/redo plumbing\n * happy without performing any adapter mutation. */\nfunction placeholderOp(name: string, args: unknown, label?: string): Op {\n const op: Op = {\n name,\n args,\n label,\n apply: () => 'noop' as const,\n invert: () => op,\n };\n return op;\n}\n\n/** Signature of a per-instance op rebuilder (`CreateHistoryOptions.rebuildOp`). */\ntype CustomRebuild = (name: string, args: unknown) => Op | null;\n\n/** Rebuild a single serialized op via `custom` (if provided), falling back to\n * a no-op placeholder.\n *\n * This engine deliberately knows nothing about any op registry: hydrating a\n * `(name, args)` pair back into an op is the caller's concern, injected\n * through `CreateHistoryOptions.rebuildOp`. `@weasel-js/core`'s\n * `createHistory` wrapper supplies its global op-factory registry as that\n * hook, so core consumers see unchanged behavior. */\nfunction rebuildSerialOp(so: SerializedOp, label: string, custom: CustomRebuild | undefined, logger: HistoryLogger): Op {\n const viaCustom = custom ? custom(so.name, so.args) : null;\n if (viaCustom !== null) return viaCustom;\n logger.log(`restore: unknown op name \"${so.name}\" — substituting no-op placeholder`);\n return placeholderOp(so.name, so.args, label);\n}\n\n/** Rebuild a runtime entry from its serialized form. Unknown op names become\n * no-op placeholders so the entry still occupies its slot in the stack. */\nfunction serialToEntry(se: SerializedHistoryEntry, custom: CustomRebuild | undefined, logger: HistoryLogger): Entry {\n const forwardOps = se.forwardOps.map((so) => rebuildSerialOp(so, se.label, custom, logger));\n const baseOps = se.baseOps.map((so) => rebuildSerialOp(so, se.label, custom, logger));\n return {\n id: se.id,\n label: se.label,\n forwardOps,\n baseOps,\n // Restored entries inherit a \"now\" timestamp — coalesce eligibility is\n // a within-session concept and a restored entry shouldn't merge with a\n // freshly-typed one regardless of when it was originally pushed.\n timestamp: 0,\n // Re-derive touchedIds from the rebuilt ops rather than trying to\n // round-trip the Set through the serialized form (Sets aren't JSON-safe).\n touchedIds: touchedIdsFromOps(forwardOps),\n };\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@weasel-js/history",
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "Undo/redo history with scoped sub-history (Journal) primitive. No React, no DOM.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"module": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"types": "./dist/index.d.ts"
|
|
14
|
+
},
|
|
15
|
+
"./package.json": "./package.json"
|
|
16
|
+
},
|
|
17
|
+
"author": "orochi235",
|
|
18
|
+
"homepage": "https://orochi235.github.io/weasel/",
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/orochi235/weasel.git",
|
|
22
|
+
"directory": "packages/history"
|
|
23
|
+
},
|
|
24
|
+
"bugs": {
|
|
25
|
+
"url": "https://github.com/orochi235/weasel/issues"
|
|
26
|
+
},
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=20"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"README.md",
|
|
33
|
+
"LICENSE"
|
|
34
|
+
],
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "tsup"
|
|
40
|
+
}
|
|
41
|
+
}
|