@1337exp/taoux 0.3.0 → 0.4.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/CHANGELOG.md +4 -0
- package/README.md +1 -0
- package/README.ru.md +1 -0
- package/dist/undo.d.ts +113 -0
- package/dist/undo.js +166 -0
- package/dist/undo.js.map +1 -0
- package/package.json +5 -1
- package/skills/taoux/SKILL.md +2 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
- **New module `undo` (tier 0): undo and redo by records.** `UndoStack` keeps steps made of only the records they touched (`before` and `after` images), not snapshots of the whole document as `History` does, so a step costs what it changed, and an undo after a sync does not roll back what another device has just changed. `diffRecords(prev, next, id)` makes a step from two lists (records are immutable, found by identity); `record(entry, key?)` merges quick edits with one key within `coalesceMs` (3 s) into one step; `undo(current)` / `redo(current)` take the current list and return the next one. Two hooks carry what only the app knows: `revive(image, now)` stamps a returned record as new (`updatedAt: now`), and `vanish(record, now)` marks a record the step created as gone instead of erasing it (a tombstone; without it the record is dropped). A record that comes back takes its old place (a step keeps where its records stood, `beforeAt` / `afterAt`), so a note removed from the middle returns to the middle and «delete all» undone is the same list in the same order; the nearest place if the list changed meanwhile. The merge window slides with every edit, so typing without a pause stays one step; `coalesceMaxMs` caps how long a merged step may grow (no cap by default). It came out of Next Up's `core/undo.ts`; nothing else changes.
|
|
6
|
+
|
|
3
7
|
## 0.3.0
|
|
4
8
|
|
|
5
9
|
Additions for apps that are not canvas editors (a list of notes); everything that was there works as before, nothing to migrate.
|
package/README.md
CHANGED
|
@@ -81,6 +81,7 @@ import { History } from '@1337exp/taoux/history';
|
|
|
81
81
|
|---|---|---|
|
|
82
82
|
| `camera` | canvas camera: pan, zoom around the cursor, screen ↔ world | nothing |
|
|
83
83
|
| `history` | undo/redo on string snapshots, rapid edits merged into one step | nothing |
|
|
84
|
+
| `undo` | undo/redo by records, not snapshots: a step keeps only the records it touched, so it is small and an undo after a sync does not roll back another device's edits; quick edits merge (`UndoStack`, `diffRecords`) | nothing |
|
|
84
85
|
| `hotkeys` | shortcuts: `parseHotkey('Mod+Shift+Z')`, `matchHotkey` (Mod = ⌘ / Ctrl, non-Latin layouts by the physical key), `formatHotkey` (`Ctrl+Shift+Z` / `⇧⌘Z`), `isReservedHotkey` (⌘W, ⌘T, ⌘Q…), `bindHotkeys` on an element | DOM (for `bindHotkeys`) |
|
|
85
86
|
| `storage` | autosave to localStorage without exceptions; `tryWrite` (why it failed: quota / denied), `remove`, `subscribe` (another tab changed the key) | nothing |
|
|
86
87
|
| `file` | download text as a file (any `mime`), read a picked file as text with a size limit | DOM |
|
package/README.ru.md
CHANGED
|
@@ -81,6 +81,7 @@ import { History } from '@1337exp/taoux/history';
|
|
|
81
81
|
|---|---|---|
|
|
82
82
|
| `camera` | камера холста: pan, zoom вокруг курсора, экран ↔ мир | нет |
|
|
83
83
|
| `history` | undo/redo на снимках-строках со склейкой частых правок | нет |
|
|
84
|
+
| `undo` | undo/redo по записям, а не по снимкам: шаг хранит только затронутые записи, поэтому он мал, а отмена после синхронизации не откатывает правки другого устройства; частые правки склеиваются (`UndoStack`, `diffRecords`) | нет |
|
|
84
85
|
| `hotkeys` | сочетания клавиш: `parseHotkey('Mod+Shift+Z')`, `matchHotkey` (Mod = ⌘ / Ctrl, нелатинские раскладки по физической клавише), `formatHotkey` (`Ctrl+Shift+Z` / `⇧⌘Z`), `isReservedHotkey` (⌘W, ⌘T, ⌘Q…), `bindHotkeys` на элементе | DOM (для `bindHotkeys`) |
|
|
85
86
|
| `storage` | автосохранение в localStorage без исключений; `tryWrite` (почему не вышло: квота / запрет), `remove`, `subscribe` (ключ изменила другая вкладка) | нет |
|
|
86
87
|
| `file` | скачивание текста как файла (любой `mime`), чтение выбранного файла как текста с лимитом размера | DOM |
|
package/dist/undo.d.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Undo and redo by records, not by snapshots of the whole document. A step keeps only the records it touched, before
|
|
3
|
+
* and after. For a list that is edited and synced (notes, tasks, contacts) that is what `History` cannot give:
|
|
4
|
+
* a snapshot of the whole list costs the whole list per step, and an undo made after a sync would roll back what
|
|
5
|
+
* another device has just changed. Here an undo touches only the records of its step.
|
|
6
|
+
* Undo и redo по записям, а не по снимкам всего документа. Шаг хранит только затронутые им записи, до и после. Для
|
|
7
|
+
* списка, который правят и синхронизируют (заметки, задачи, контакты), это то, чего не даёт `History`: снимок всего
|
|
8
|
+
* списка стоит всего списка на шаг, а отмена после синхронизации откатила бы то, что только что изменило другое
|
|
9
|
+
* устройство. Здесь отмена трогает только записи своего шага.
|
|
10
|
+
*
|
|
11
|
+
* Pure TypeScript, no Vue and no DOM. Records are immutable: an edit makes a new object, and `diffRecords` finds the
|
|
12
|
+
* changed ones by identity.
|
|
13
|
+
* Чистый TypeScript, без Vue и DOM. Записи неизменяемы: правка создаёт новый объект, а `diffRecords` находит
|
|
14
|
+
* изменённые по тождеству.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Edits with the same key made faster than this many ms apart merge into one step (autosave while typing).
|
|
18
|
+
* Правки с одним ключом, сделанные чаще чем раз в столько мс, склеиваются в один шаг (автосохранение при наборе).
|
|
19
|
+
*/
|
|
20
|
+
export declare const COALESCE_MS = 3000;
|
|
21
|
+
/**
|
|
22
|
+
* What one step changed: the touched records before and after (`null`: the record did not exist / is gone).
|
|
23
|
+
* Что изменил один шаг: затронутые записи до и после (`null`: записи не было / её больше нет).
|
|
24
|
+
*/
|
|
25
|
+
export interface UndoEntry<T> {
|
|
26
|
+
before: Map<string, T | null>;
|
|
27
|
+
after: Map<string, T | null>;
|
|
28
|
+
/**
|
|
29
|
+
* Where a record stood in the list before / after the step (its index), so a record that comes back takes its old
|
|
30
|
+
* place instead of the end. `diffRecords` fills them; a hand-made entry may leave them out.
|
|
31
|
+
* Где запись стояла в списке до / после шага (её индекс), чтобы вернувшаяся запись встала на своё место, а не в
|
|
32
|
+
* конец. `diffRecords` их заполняет; шаг, собранный вручную, может их не задавать.
|
|
33
|
+
*/
|
|
34
|
+
beforeAt?: Map<string, number>;
|
|
35
|
+
afterAt?: Map<string, number>;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The step between two lists, or null when nothing changed. Records are compared by identity, so an unchanged
|
|
39
|
+
* record must stay the same object.
|
|
40
|
+
* Шаг между двумя списками или null, если ничего не изменилось. Записи сравниваются по тождеству, поэтому
|
|
41
|
+
* нетронутая запись должна остаться тем же объектом.
|
|
42
|
+
*/
|
|
43
|
+
export declare function diffRecords<T>(prev: readonly T[], next: readonly T[], id: (record: T) => string): UndoEntry<T> | null;
|
|
44
|
+
export interface UndoOptions<T> {
|
|
45
|
+
/** The id of a record. / Id записи. */
|
|
46
|
+
id(record: T): string;
|
|
47
|
+
/**
|
|
48
|
+
* A record comes back from a step (an image). Stamp it as new, so that a sync does not take the undo for stale:
|
|
49
|
+
* `{ ...image, updatedAt: now }`.
|
|
50
|
+
* Запись возвращается из шага (образ). Пометьте её свежей, чтобы синхронизация не сочла отмену устаревшей.
|
|
51
|
+
*/
|
|
52
|
+
revive(image: T, now: number): T;
|
|
53
|
+
/**
|
|
54
|
+
* A record that the step created (or removed) has to go away. Do not delete it from the list when the list is
|
|
55
|
+
* synced: mark it gone, as a tombstone: `{ ...record, deletedAt: now, updatedAt: now }`. Without it the record
|
|
56
|
+
* is dropped from the list.
|
|
57
|
+
* Запись, которую шаг создал (или удалил), должна исчезнуть. В синхронизируемом списке не стирайте её, а пометьте
|
|
58
|
+
* исчезнувшей, надгробием. Без этого запись просто убирается из списка.
|
|
59
|
+
*/
|
|
60
|
+
vanish?(record: T, now: number): T;
|
|
61
|
+
/** How many steps to keep. / Сколько шагов хранить. */
|
|
62
|
+
limit?: number;
|
|
63
|
+
/** The merge window of `record(entry, key)`, ms. / Окно склейки для `record(entry, key)`, мс. */
|
|
64
|
+
coalesceMs?: number;
|
|
65
|
+
/**
|
|
66
|
+
* The longest a merged step may grow, ms from its first edit. The window above slides with every edit, so typing
|
|
67
|
+
* without a pause would otherwise stay one step however long it goes on (one undo would take a minute of text
|
|
68
|
+
* away). No limit by default.
|
|
69
|
+
* Сколько может расти склеенный шаг, мс от его первой правки. Окно выше сдвигается с каждой правкой, поэтому набор
|
|
70
|
+
* без пауз иначе остаётся одним шагом сколь угодно долго (одна отмена унесла бы минуту текста). По умолчанию без
|
|
71
|
+
* предела.
|
|
72
|
+
*/
|
|
73
|
+
coalesceMaxMs?: number;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The stack of steps and the pointer in it. It does not hold the list: `undo` and `redo` take the current list and
|
|
77
|
+
* return the next one (or null when there is nothing to do), the app puts it where it keeps its records.
|
|
78
|
+
* Стек шагов и указатель в нём. Список он не хранит: `undo` и `redo` принимают текущий список и возвращают следующий
|
|
79
|
+
* (или null, если делать нечего), а приложение кладёт его туда, где хранит записи.
|
|
80
|
+
*/
|
|
81
|
+
export declare class UndoStack<T> {
|
|
82
|
+
private readonly options;
|
|
83
|
+
private entries;
|
|
84
|
+
private index;
|
|
85
|
+
private lastKey;
|
|
86
|
+
private lastTime;
|
|
87
|
+
private firstTime;
|
|
88
|
+
private readonly limit;
|
|
89
|
+
private readonly coalesceMs;
|
|
90
|
+
private readonly coalesceMaxMs;
|
|
91
|
+
constructor(options: UndoOptions<T>);
|
|
92
|
+
get canUndo(): boolean;
|
|
93
|
+
get canRedo(): boolean;
|
|
94
|
+
/**
|
|
95
|
+
* Records a step; it drops the "future" (redo). With the same `key` in a row and within `coalesceMs` the step
|
|
96
|
+
* merges into the previous one: the first `before` stays, the last `after` wins.
|
|
97
|
+
* Записывает шаг и отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `coalesceMs` шаг
|
|
98
|
+
* склеивается с предыдущим: остаётся первый `before`, побеждает последний `after`.
|
|
99
|
+
*/
|
|
100
|
+
record(entry: UndoEntry<T>, key?: string, now?: number): void;
|
|
101
|
+
undo(current: readonly T[], now?: number): T[] | null;
|
|
102
|
+
redo(current: readonly T[], now?: number): T[] | null;
|
|
103
|
+
clear(): void;
|
|
104
|
+
/**
|
|
105
|
+
* Puts the images over the current list; the other records are not touched. A record that is in the list keeps its
|
|
106
|
+
* place; one that comes back goes to the place it had (the list may have changed since, so it is the nearest one),
|
|
107
|
+
* and without a known place to the end.
|
|
108
|
+
* Кладёт образы поверх текущего списка; остальные записи не трогает. Запись, которая есть в списке, остаётся на
|
|
109
|
+
* месте; вернувшаяся встаёт туда, где стояла (список с тех пор мог измениться, поэтому — на ближайшее место), а без
|
|
110
|
+
* известного места — в конец.
|
|
111
|
+
*/
|
|
112
|
+
private apply;
|
|
113
|
+
}
|
package/dist/undo.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
//#region src/undo.ts
|
|
2
|
+
/**
|
|
3
|
+
* Undo and redo by records, not by snapshots of the whole document. A step keeps only the records it touched, before
|
|
4
|
+
* and after. For a list that is edited and synced (notes, tasks, contacts) that is what `History` cannot give:
|
|
5
|
+
* a snapshot of the whole list costs the whole list per step, and an undo made after a sync would roll back what
|
|
6
|
+
* another device has just changed. Here an undo touches only the records of its step.
|
|
7
|
+
* Undo и redo по записям, а не по снимкам всего документа. Шаг хранит только затронутые им записи, до и после. Для
|
|
8
|
+
* списка, который правят и синхронизируют (заметки, задачи, контакты), это то, чего не даёт `History`: снимок всего
|
|
9
|
+
* списка стоит всего списка на шаг, а отмена после синхронизации откатила бы то, что только что изменило другое
|
|
10
|
+
* устройство. Здесь отмена трогает только записи своего шага.
|
|
11
|
+
*
|
|
12
|
+
* Pure TypeScript, no Vue and no DOM. Records are immutable: an edit makes a new object, and `diffRecords` finds the
|
|
13
|
+
* changed ones by identity.
|
|
14
|
+
* Чистый TypeScript, без Vue и DOM. Записи неизменяемы: правка создаёт новый объект, а `diffRecords` находит
|
|
15
|
+
* изменённые по тождеству.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Edits with the same key made faster than this many ms apart merge into one step (autosave while typing).
|
|
19
|
+
* Правки с одним ключом, сделанные чаще чем раз в столько мс, склеиваются в один шаг (автосохранение при наборе).
|
|
20
|
+
*/
|
|
21
|
+
var COALESCE_MS = 3e3;
|
|
22
|
+
/**
|
|
23
|
+
* The step between two lists, or null when nothing changed. Records are compared by identity, so an unchanged
|
|
24
|
+
* record must stay the same object.
|
|
25
|
+
* Шаг между двумя списками или null, если ничего не изменилось. Записи сравниваются по тождеству, поэтому
|
|
26
|
+
* нетронутая запись должна остаться тем же объектом.
|
|
27
|
+
*/
|
|
28
|
+
function diffRecords(prev, next, id) {
|
|
29
|
+
const was = new Map(prev.map((r) => [id(r), r]));
|
|
30
|
+
const is = new Map(next.map((r) => [id(r), r]));
|
|
31
|
+
const wasAt = new Map(prev.map((r, i) => [id(r), i]));
|
|
32
|
+
const isAt = new Map(next.map((r, i) => [id(r), i]));
|
|
33
|
+
const entry = {
|
|
34
|
+
before: /* @__PURE__ */ new Map(),
|
|
35
|
+
after: /* @__PURE__ */ new Map(),
|
|
36
|
+
beforeAt: /* @__PURE__ */ new Map(),
|
|
37
|
+
afterAt: /* @__PURE__ */ new Map()
|
|
38
|
+
};
|
|
39
|
+
const place = (key) => {
|
|
40
|
+
const before = wasAt.get(key);
|
|
41
|
+
const after = isAt.get(key);
|
|
42
|
+
if (before !== void 0) entry.beforeAt.set(key, before);
|
|
43
|
+
if (after !== void 0) entry.afterAt.set(key, after);
|
|
44
|
+
};
|
|
45
|
+
for (const [key, record] of is) if (was.get(key) !== record) {
|
|
46
|
+
entry.before.set(key, was.get(key) ?? null);
|
|
47
|
+
entry.after.set(key, record);
|
|
48
|
+
place(key);
|
|
49
|
+
}
|
|
50
|
+
for (const [key, record] of was) if (!is.has(key)) {
|
|
51
|
+
entry.before.set(key, record);
|
|
52
|
+
entry.after.set(key, null);
|
|
53
|
+
place(key);
|
|
54
|
+
}
|
|
55
|
+
return entry.after.size === 0 ? null : entry;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The stack of steps and the pointer in it. It does not hold the list: `undo` and `redo` take the current list and
|
|
59
|
+
* return the next one (or null when there is nothing to do), the app puts it where it keeps its records.
|
|
60
|
+
* Стек шагов и указатель в нём. Список он не хранит: `undo` и `redo` принимают текущий список и возвращают следующий
|
|
61
|
+
* (или null, если делать нечего), а приложение кладёт его туда, где хранит записи.
|
|
62
|
+
*/
|
|
63
|
+
var UndoStack = class {
|
|
64
|
+
options;
|
|
65
|
+
entries = [];
|
|
66
|
+
index = 0;
|
|
67
|
+
lastKey;
|
|
68
|
+
lastTime = 0;
|
|
69
|
+
firstTime = 0;
|
|
70
|
+
limit;
|
|
71
|
+
coalesceMs;
|
|
72
|
+
coalesceMaxMs;
|
|
73
|
+
constructor(options) {
|
|
74
|
+
this.options = options;
|
|
75
|
+
this.limit = options.limit ?? 50;
|
|
76
|
+
this.coalesceMs = options.coalesceMs ?? 3e3;
|
|
77
|
+
this.coalesceMaxMs = options.coalesceMaxMs ?? Infinity;
|
|
78
|
+
}
|
|
79
|
+
get canUndo() {
|
|
80
|
+
return this.index > 0;
|
|
81
|
+
}
|
|
82
|
+
get canRedo() {
|
|
83
|
+
return this.index < this.entries.length;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Records a step; it drops the "future" (redo). With the same `key` in a row and within `coalesceMs` the step
|
|
87
|
+
* merges into the previous one: the first `before` stays, the last `after` wins.
|
|
88
|
+
* Записывает шаг и отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `coalesceMs` шаг
|
|
89
|
+
* склеивается с предыдущим: остаётся первый `before`, побеждает последний `after`.
|
|
90
|
+
*/
|
|
91
|
+
record(entry, key, now = Date.now()) {
|
|
92
|
+
const atTop = this.index > 0 && this.index === this.entries.length;
|
|
93
|
+
if (key !== void 0 && key === this.lastKey && atTop && now - this.lastTime <= this.coalesceMs && now - this.firstTime <= this.coalesceMaxMs) {
|
|
94
|
+
const previous = this.entries[this.index - 1];
|
|
95
|
+
for (const [id, record] of entry.before) {
|
|
96
|
+
if (previous.before.has(id)) continue;
|
|
97
|
+
previous.before.set(id, record);
|
|
98
|
+
const at = entry.beforeAt?.get(id);
|
|
99
|
+
if (at !== void 0) (previous.beforeAt ??= /* @__PURE__ */ new Map()).set(id, at);
|
|
100
|
+
}
|
|
101
|
+
for (const [id, record] of entry.after) {
|
|
102
|
+
previous.after.set(id, record);
|
|
103
|
+
const at = entry.afterAt?.get(id);
|
|
104
|
+
if (at !== void 0) (previous.afterAt ??= /* @__PURE__ */ new Map()).set(id, at);
|
|
105
|
+
else previous.afterAt?.delete(id);
|
|
106
|
+
}
|
|
107
|
+
} else {
|
|
108
|
+
this.entries.length = this.index;
|
|
109
|
+
this.entries.push(entry);
|
|
110
|
+
if (this.entries.length > this.limit) this.entries.shift();
|
|
111
|
+
this.index = this.entries.length;
|
|
112
|
+
this.firstTime = now;
|
|
113
|
+
}
|
|
114
|
+
this.lastKey = key;
|
|
115
|
+
this.lastTime = now;
|
|
116
|
+
}
|
|
117
|
+
undo(current, now = Date.now()) {
|
|
118
|
+
if (!this.canUndo) return null;
|
|
119
|
+
this.lastKey = void 0;
|
|
120
|
+
const entry = this.entries[--this.index];
|
|
121
|
+
return this.apply(current, entry.before, entry.beforeAt, now);
|
|
122
|
+
}
|
|
123
|
+
redo(current, now = Date.now()) {
|
|
124
|
+
if (!this.canRedo) return null;
|
|
125
|
+
this.lastKey = void 0;
|
|
126
|
+
const entry = this.entries[this.index++];
|
|
127
|
+
return this.apply(current, entry.after, entry.afterAt, now);
|
|
128
|
+
}
|
|
129
|
+
clear() {
|
|
130
|
+
this.entries = [];
|
|
131
|
+
this.index = 0;
|
|
132
|
+
this.lastKey = void 0;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Puts the images over the current list; the other records are not touched. A record that is in the list keeps its
|
|
136
|
+
* place; one that comes back goes to the place it had (the list may have changed since, so it is the nearest one),
|
|
137
|
+
* and without a known place to the end.
|
|
138
|
+
* Кладёт образы поверх текущего списка; остальные записи не трогает. Запись, которая есть в списке, остаётся на
|
|
139
|
+
* месте; вернувшаяся встаёт туда, где стояла (список с тех пор мог измениться, поэтому — на ближайшее место), а без
|
|
140
|
+
* известного места — в конец.
|
|
141
|
+
*/
|
|
142
|
+
apply(current, images, places, now) {
|
|
143
|
+
const { id, revive, vanish } = this.options;
|
|
144
|
+
const result = new Map(current.map((r) => [id(r), r]));
|
|
145
|
+
const back = [];
|
|
146
|
+
for (const [key, image] of images) {
|
|
147
|
+
if (image) {
|
|
148
|
+
if (result.has(key)) result.set(key, revive(image, now));
|
|
149
|
+
else back.push([places?.get(key) ?? Infinity, revive(image, now)]);
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const existing = result.get(key);
|
|
153
|
+
if (!existing) continue;
|
|
154
|
+
if (vanish) result.set(key, vanish(existing, now));
|
|
155
|
+
else result.delete(key);
|
|
156
|
+
}
|
|
157
|
+
const list = [...result.values()];
|
|
158
|
+
back.sort((a, b) => a[0] - b[0]);
|
|
159
|
+
for (const [at, record] of back) list.splice(Math.min(at, list.length), 0, record);
|
|
160
|
+
return list;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
//#endregion
|
|
164
|
+
export { COALESCE_MS, UndoStack, diffRecords };
|
|
165
|
+
|
|
166
|
+
//# sourceMappingURL=undo.js.map
|
package/dist/undo.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"undo.js","names":[],"sources":["../src/undo.ts"],"sourcesContent":["/**\n * Undo and redo by records, not by snapshots of the whole document. A step keeps only the records it touched, before\n * and after. For a list that is edited and synced (notes, tasks, contacts) that is what `History` cannot give:\n * a snapshot of the whole list costs the whole list per step, and an undo made after a sync would roll back what\n * another device has just changed. Here an undo touches only the records of its step.\n * Undo и redo по записям, а не по снимкам всего документа. Шаг хранит только затронутые им записи, до и после. Для\n * списка, который правят и синхронизируют (заметки, задачи, контакты), это то, чего не даёт `History`: снимок всего\n * списка стоит всего списка на шаг, а отмена после синхронизации откатила бы то, что только что изменило другое\n * устройство. Здесь отмена трогает только записи своего шага.\n *\n * Pure TypeScript, no Vue and no DOM. Records are immutable: an edit makes a new object, and `diffRecords` finds the\n * changed ones by identity.\n * Чистый TypeScript, без Vue и DOM. Записи неизменяемы: правка создаёт новый объект, а `diffRecords` находит\n * изменённые по тождеству.\n */\n\n/**\n * Edits with the same key made faster than this many ms apart merge into one step (autosave while typing).\n * Правки с одним ключом, сделанные чаще чем раз в столько мс, склеиваются в один шаг (автосохранение при наборе).\n */\nexport const COALESCE_MS = 3000;\n\n/**\n * What one step changed: the touched records before and after (`null`: the record did not exist / is gone).\n * Что изменил один шаг: затронутые записи до и после (`null`: записи не было / её больше нет).\n */\nexport interface UndoEntry<T> {\n before: Map<string, T | null>;\n after: Map<string, T | null>;\n /**\n * Where a record stood in the list before / after the step (its index), so a record that comes back takes its old\n * place instead of the end. `diffRecords` fills them; a hand-made entry may leave them out.\n * Где запись стояла в списке до / после шага (её индекс), чтобы вернувшаяся запись встала на своё место, а не в\n * конец. `diffRecords` их заполняет; шаг, собранный вручную, может их не задавать.\n */\n beforeAt?: Map<string, number>;\n afterAt?: Map<string, number>;\n}\n\n/**\n * The step between two lists, or null when nothing changed. Records are compared by identity, so an unchanged\n * record must stay the same object.\n * Шаг между двумя списками или null, если ничего не изменилось. Записи сравниваются по тождеству, поэтому\n * нетронутая запись должна остаться тем же объектом.\n */\nexport function diffRecords<T>(prev: readonly T[], next: readonly T[], id: (record: T) => string): UndoEntry<T> | null {\n const was = new Map(prev.map((r) => [id(r), r]));\n const is = new Map(next.map((r) => [id(r), r]));\n const wasAt = new Map(prev.map((r, i) => [id(r), i]));\n const isAt = new Map(next.map((r, i) => [id(r), i]));\n const entry: UndoEntry<T> = { before: new Map(), after: new Map(), beforeAt: new Map(), afterAt: new Map() };\n const place = (key: string) => {\n const before = wasAt.get(key);\n const after = isAt.get(key);\n if (before !== undefined) entry.beforeAt!.set(key, before);\n if (after !== undefined) entry.afterAt!.set(key, after);\n };\n\n for (const [key, record] of is) {\n if (was.get(key) !== record) {\n entry.before.set(key, was.get(key) ?? null);\n entry.after.set(key, record);\n place(key);\n }\n }\n for (const [key, record] of was) {\n if (!is.has(key)) {\n entry.before.set(key, record);\n entry.after.set(key, null);\n place(key);\n }\n }\n return entry.after.size === 0 ? null : entry;\n}\n\nexport interface UndoOptions<T> {\n /** The id of a record. / Id записи. */\n id(record: T): string;\n /**\n * A record comes back from a step (an image). Stamp it as new, so that a sync does not take the undo for stale:\n * `{ ...image, updatedAt: now }`.\n * Запись возвращается из шага (образ). Пометьте её свежей, чтобы синхронизация не сочла отмену устаревшей.\n */\n revive(image: T, now: number): T;\n /**\n * A record that the step created (or removed) has to go away. Do not delete it from the list when the list is\n * synced: mark it gone, as a tombstone: `{ ...record, deletedAt: now, updatedAt: now }`. Without it the record\n * is dropped from the list.\n * Запись, которую шаг создал (или удалил), должна исчезнуть. В синхронизируемом списке не стирайте её, а пометьте\n * исчезнувшей, надгробием. Без этого запись просто убирается из списка.\n */\n vanish?(record: T, now: number): T;\n /** How many steps to keep. / Сколько шагов хранить. */\n limit?: number;\n /** The merge window of `record(entry, key)`, ms. / Окно склейки для `record(entry, key)`, мс. */\n coalesceMs?: number;\n /**\n * The longest a merged step may grow, ms from its first edit. The window above slides with every edit, so typing\n * without a pause would otherwise stay one step however long it goes on (one undo would take a minute of text\n * away). No limit by default.\n * Сколько может расти склеенный шаг, мс от его первой правки. Окно выше сдвигается с каждой правкой, поэтому набор\n * без пауз иначе остаётся одним шагом сколь угодно долго (одна отмена унесла бы минуту текста). По умолчанию без\n * предела.\n */\n coalesceMaxMs?: number;\n}\n\n/**\n * The stack of steps and the pointer in it. It does not hold the list: `undo` and `redo` take the current list and\n * return the next one (or null when there is nothing to do), the app puts it where it keeps its records.\n * Стек шагов и указатель в нём. Список он не хранит: `undo` и `redo` принимают текущий список и возвращают следующий\n * (или null, если делать нечего), а приложение кладёт его туда, где хранит записи.\n */\nexport class UndoStack<T> {\n private entries: UndoEntry<T>[] = [];\n private index = 0;\n private lastKey: string | undefined;\n private lastTime = 0;\n // when the step on top began: the limit of a merged step counts from here / когда начался верхний шаг\n private firstTime = 0;\n private readonly limit: number;\n private readonly coalesceMs: number;\n private readonly coalesceMaxMs: number;\n\n constructor(private readonly options: UndoOptions<T>) {\n this.limit = options.limit ?? 50;\n this.coalesceMs = options.coalesceMs ?? COALESCE_MS;\n this.coalesceMaxMs = options.coalesceMaxMs ?? Infinity;\n }\n\n get canUndo(): boolean {\n return this.index > 0;\n }\n\n get canRedo(): boolean {\n return this.index < this.entries.length;\n }\n\n /**\n * Records a step; it drops the \"future\" (redo). With the same `key` in a row and within `coalesceMs` the step\n * merges into the previous one: the first `before` stays, the last `after` wins.\n * Записывает шаг и отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `coalesceMs` шаг\n * склеивается с предыдущим: остаётся первый `before`, побеждает последний `after`.\n */\n record(entry: UndoEntry<T>, key?: string, now: number = Date.now()): void {\n const atTop = this.index > 0 && this.index === this.entries.length;\n const merge =\n key !== undefined &&\n key === this.lastKey &&\n atTop &&\n now - this.lastTime <= this.coalesceMs &&\n now - this.firstTime <= this.coalesceMaxMs;\n if (merge) {\n const previous = this.entries[this.index - 1]!;\n for (const [id, record] of entry.before) {\n if (previous.before.has(id)) continue;\n previous.before.set(id, record);\n const at = entry.beforeAt?.get(id);\n if (at !== undefined) (previous.beforeAt ??= new Map()).set(id, at);\n }\n for (const [id, record] of entry.after) {\n previous.after.set(id, record);\n const at = entry.afterAt?.get(id);\n if (at !== undefined) (previous.afterAt ??= new Map()).set(id, at);\n else previous.afterAt?.delete(id);\n }\n } else {\n this.entries.length = this.index;\n this.entries.push(entry);\n if (this.entries.length > this.limit) this.entries.shift();\n this.index = this.entries.length;\n this.firstTime = now;\n }\n this.lastKey = key;\n this.lastTime = now;\n }\n\n undo(current: readonly T[], now: number = Date.now()): T[] | null {\n if (!this.canUndo) return null;\n this.lastKey = undefined;\n const entry = this.entries[--this.index]!;\n return this.apply(current, entry.before, entry.beforeAt, now);\n }\n\n redo(current: readonly T[], now: number = Date.now()): T[] | null {\n if (!this.canRedo) return null;\n this.lastKey = undefined;\n const entry = this.entries[this.index++]!;\n return this.apply(current, entry.after, entry.afterAt, now);\n }\n\n clear(): void {\n this.entries = [];\n this.index = 0;\n this.lastKey = undefined;\n }\n\n /**\n * Puts the images over the current list; the other records are not touched. A record that is in the list keeps its\n * place; one that comes back goes to the place it had (the list may have changed since, so it is the nearest one),\n * and without a known place to the end.\n * Кладёт образы поверх текущего списка; остальные записи не трогает. Запись, которая есть в списке, остаётся на\n * месте; вернувшаяся встаёт туда, где стояла (список с тех пор мог измениться, поэтому — на ближайшее место), а без\n * известного места — в конец.\n */\n private apply(current: readonly T[], images: Map<string, T | null>, places: Map<string, number> | undefined, now: number): T[] {\n const { id, revive, vanish } = this.options;\n const result = new Map(current.map((r) => [id(r), r]));\n const back: [number, T][] = [];\n for (const [key, image] of images) {\n if (image) {\n if (result.has(key)) result.set(key, revive(image, now));\n else back.push([places?.get(key) ?? Infinity, revive(image, now)]);\n continue;\n }\n const existing = result.get(key);\n if (!existing) continue;\n if (vanish) result.set(key, vanish(existing, now));\n else result.delete(key);\n }\n const list = [...result.values()];\n // in order of their old places, so «delete all» undone is the same list again / по возрастанию старых мест\n back.sort((a, b) => a[0] - b[0]);\n for (const [at, record] of back) list.splice(Math.min(at, list.length), 0, record);\n return list;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,cAAc;;;;;;;AAyB3B,SAAgB,YAAe,MAAoB,MAAoB,IAAgD;CACnH,MAAM,MAAM,IAAI,IAAI,KAAK,KAAK,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;CAC/C,MAAM,KAAK,IAAI,IAAI,KAAK,KAAK,MAAM,CAAC,GAAG,CAA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,KAAK,IAAI,IAAI,KAAK,MAAM,GAAG,GAAG,MAAM;EACjF,OAAO;CACX;AACJ"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@1337exp/taoux",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Interaction and behavior building blocks for Vue apps: curve and gradient editors, canvas, undo/redo, playback. Import only what you need, bring your own design.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"vue",
|
|
@@ -139,6 +139,10 @@
|
|
|
139
139
|
"types": "./dist/touch.d.ts",
|
|
140
140
|
"import": "./dist/touch.js"
|
|
141
141
|
},
|
|
142
|
+
"./undo": {
|
|
143
|
+
"types": "./dist/undo.d.ts",
|
|
144
|
+
"import": "./dist/undo.js"
|
|
145
|
+
},
|
|
142
146
|
"./wheel": {
|
|
143
147
|
"types": "./dist/wheel.d.ts",
|
|
144
148
|
"import": "./dist/wheel.js"
|
package/skills/taoux/SKILL.md
CHANGED
|
@@ -25,6 +25,7 @@ shells, and TaoUX has **no buttons or fields of its own**. Pair it with TaoUI fo
|
|
|
25
25
|
|---|---|
|
|
26
26
|
| `camera` | pan, zoom around the cursor, screen ↔ world (`zoomAt`) |
|
|
27
27
|
| `history` | `new History(snapshot)`: undo / redo on string snapshots, rapid edits with one `key` merged into one step |
|
|
28
|
+
| `undo` | `new UndoStack({ id, revive, vanish? })`: undo / redo of a list of records by steps that keep only the touched ones (`diffRecords(prev, next, id)` makes a step; a returned record takes its old place); right for a list that is edited and synced, where `History` would store the whole list per step and an undo would roll back a sync. `coalesceMaxMs` caps a merged step of typing |
|
|
28
29
|
| `session` | `createDocumentSession(...)`: history + autosave + files + restore + notices for one document; `canUndo` / `canRedo` refs. `camera` is optional (a list, not a canvas); count with `countItems` (`countNodes` is its old name) |
|
|
29
30
|
| `commands` | `createCommands([...])`: one registry for menus, shortcuts and palettes (see below) |
|
|
30
31
|
| `hotkeys` | `parseHotkey('Mod+Shift+Z')`, `matchHotkey`, `formatHotkey` (`Ctrl+Shift+Z` / `⇧⌘Z`), `isReservedHotkey`, `bindHotkeys(element, map)` |
|
|
@@ -88,6 +89,7 @@ onBeforeUnmount(() => unbind());
|
|
|
88
89
|
- Importing from `@1337exp/taoux` (no root entry) or from `dist/` paths.
|
|
89
90
|
- Forgetting the module CSS (`curveeditor.css`…) or the bridge `taoui.css`: the editor renders unstyled or dark.
|
|
90
91
|
- Calling `toMenu` outside `computed`: the menu does not follow the state.
|
|
92
|
+
- Using `History` for a list of records that is synced: its snapshots are the whole list, and an undo after a sync rolls back the other device's edits. Use `undo` (`UndoStack`), and stamp a returned record as new in `revive`.
|
|
91
93
|
- Keeping editor state outside `history` / `session` and then wondering why Undo skips it: commit a snapshot after
|
|
92
94
|
every edit (`session.commit(key)` or `recorded(fn)`).
|
|
93
95
|
- Offering a reserved shortcut (⌘W, ⌘T, ⌘N, Ctrl+Tab): the browser takes it before the page.
|