@1337exp/taoux 0.12.1 → 0.13.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 CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.13.0
4
+
5
+ Nothing to migrate: new optional members.
6
+
7
+ - **`history`: `save()` and `restore(state)`.** An editor with several documents (tabs, a project tree) wants an undo of its own for each: switching from one to another must not lose the steps of the first or give them to the second. `save()` returns the whole history (a copy of the snapshots and the position, plain data, `HistoryState`), `restore(state)` puts it back; a position outside the snapshots, or no snapshots, is a `RangeError`. A series of merged edits (the `key`) is not continued across a restore.
8
+ - **`session`: `saveHistory()` and `restoreHistory(state)`.** The same for a document session: when another document is shown, take the history of the one you leave (`saveHistory`), `load` the next with `resetHistory`, then give it its own (`restoreHistory`); `canUndo` and `canRedo` follow it. The document, `dirty` and the autosave are not touched, so the app keeps its own `dirty` per document if it wants it.
9
+
3
10
  ## 0.12.1
4
11
 
5
12
  Nothing to migrate; the behaviour of `zip` does not change.
package/README.md CHANGED
@@ -82,7 +82,7 @@ import { History } from '@1337exp/taoux/history';
82
82
  | Module | What it does | Depends on |
83
83
  |---|---|---|
84
84
  | `camera` | canvas camera: pan, zoom around the cursor, screen ↔ world | nothing |
85
- | `history` | undo/redo on string snapshots, rapid edits merged into one step | nothing |
85
+ | `history` | undo/redo on string snapshots, rapid edits merged into one step; `save()` / `restore()` take a whole history out and put it back (a document each) | nothing |
86
86
  | `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 |
87
87
  | `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`) |
88
88
  | `storage` | autosave to localStorage without exceptions; `tryWrite` (why it failed: quota / denied), `remove`, `subscribe` (another tab changed the key) | nothing |
@@ -99,7 +99,7 @@ import { History } from '@1337exp/taoux/history';
99
99
  | `ease` | easing functions between curve points: 8 families × in / out / in-out, `linear`, `step`, cubic Bezier; `easeValue`, `isEase` (the editor draws with it, a runtime evaluates with it) | nothing |
100
100
  | `num` | small numeric helpers: `clamp`, `roundTo`, `snapTo`, `niceStep`, `ticks` (shared by the curve, gradient and playback modules) | nothing |
101
101
  | `sortable` (Vue) | reorder a list by a grip and by the keyboard: `useSortable(listRef, { onMove })`, `data-sortable-item` / `data-sortable-handle`; the others make room, the list scrolls at its edge, Esc puts it back, a live region tells a screen reader; `moveItem` | vue (peer) |
102
- | `session` | document lifecycle: history, autosave, files, restore, notices, `dirty` / `markSaved()`; a canvas camera is optional (`countItems`) | vue (peer) |
102
+ | `session` | document lifecycle: history, autosave, files, restore, notices, `dirty` / `markSaved()`, `saveHistory()` / `restoreHistory()` for an editor with several documents; a canvas camera is optional (`countItems`) | vue (peer) |
103
103
  | `commands` | a registry of commands (label, shortcut, `enabled`, `checked`, `run`): `toMenu(layout)` builds a `TaoMenuItem[]` tree for `TaoMenubar` / `TaoContextMenu`, `bind` listens to the same shortcuts, `historyCommands` gives Undo / Redo that disable themselves, `check` finds reserved and duplicate shortcuts | DOM (for `bind`) |
104
104
  | `palette` | search and groups of nodes for a palette | nothing |
105
105
  | `links` (Vue) | links layer: SVG from ready geometry, `--tx-link-*` | vue (peer) |
package/README.ru.md CHANGED
@@ -82,7 +82,7 @@ import { History } from '@1337exp/taoux/history';
82
82
  | Модуль | Что делает | Зависимости |
83
83
  |---|---|---|
84
84
  | `camera` | камера холста: pan, zoom вокруг курсора, экран ↔ мир | нет |
85
- | `history` | undo/redo на снимках-строках со склейкой частых правок | нет |
85
+ | `history` | undo/redo на снимках-строках со склейкой частых правок; `save()` / `restore()` уносят всю историю и возвращают её (по одной на документ) | нет |
86
86
  | `undo` | undo/redo по записям, а не по снимкам: шаг хранит только затронутые записи, поэтому он мал, а отмена после синхронизации не откатывает правки другого устройства; частые правки склеиваются (`UndoStack`, `diffRecords`) | нет |
87
87
  | `hotkeys` | сочетания клавиш: `parseHotkey('Mod+Shift+Z')`, `matchHotkey` (Mod = ⌘ / Ctrl, нелатинские раскладки по физической клавише), `formatHotkey` (`Ctrl+Shift+Z` / `⇧⌘Z`), `isReservedHotkey` (⌘W, ⌘T, ⌘Q…), `bindHotkeys` на элементе | DOM (для `bindHotkeys`) |
88
88
  | `storage` | автосохранение в localStorage без исключений; `tryWrite` (почему не вышло: квота / запрет), `remove`, `subscribe` (ключ изменила другая вкладка) | нет |
@@ -99,7 +99,7 @@ import { History } from '@1337exp/taoux/history';
99
99
  | `ease` | функции движения между точками кривой: 8 семейств × in / out / in-out, `linear`, `step`, кубический Безье; `easeValue`, `isEase` (редактор рисует ими, рантайм считает ими же) | нет |
100
100
  | `num` | мелкая числовая математика: `clamp`, `roundTo`, `snapTo`, `niceStep`, `ticks` (общая для кривой, градиента и воспроизведения) | нет |
101
101
  | `sortable` (Vue) | перестановка списка за ручку и с клавиатуры: `useSortable(listRef, { onMove })`, `data-sortable-item` / `data-sortable-handle`; остальные расступаются, у края список прокручивается, Esc возвращает, живой регион сообщает скринридеру; `moveItem` | vue (peer) |
102
- | `session` | жизненный цикл документа: история, автосохранение, файлы, восстановление, уведомления, `dirty` / `markSaved()`; камера холста необязательна (`countItems`) | vue (peer) |
102
+ | `session` | жизненный цикл документа: история, автосохранение, файлы, восстановление, уведомления, `dirty` / `markSaved()`, `saveHistory()` / `restoreHistory()` для редактора с несколькими документами; камера холста необязательна (`countItems`) | vue (peer) |
103
103
  | `commands` | реестр команд (подпись, сочетание, `enabled`, `checked`, `run`): `toMenu(layout)` строит дерево `TaoMenuItem[]` для `TaoMenubar` / `TaoContextMenu`, `bind` слушает те же сочетания, `historyCommands` даёт Undo / Redo, которые сами становятся недоступными, `check` находит занятые браузером и повторённые сочетания | DOM (для `bind`) |
104
104
  | `palette` | поиск и группы нод для палитры | нет |
105
105
  | `links` (Vue) | слой связей: SVG из готовой геометрии, `--tx-link-*` | vue (peer) |
package/dist/history.d.ts CHANGED
@@ -3,6 +3,16 @@
3
3
  * Правки с одним ключом, сделанные чаще чем раз в столько мс, склеиваются в одну запись (набор числа в поле и т.п.).
4
4
  */
5
5
  export declare const COALESCE_MS = 800;
6
+ /**
7
+ * A history taken out of a `History` to be put back later: for an editor with several documents, each keeps its own.
8
+ * It is plain data (strings and a number), so it can be stored anywhere.
9
+ * История, вынутая из `History`, чтобы вернуть её позже: у редактора с несколькими документами у каждого своя.
10
+ * Это простые данные (строки и число), их можно хранить где угодно.
11
+ */
12
+ export interface HistoryState {
13
+ states: readonly string[];
14
+ index: number;
15
+ }
6
16
  /**
7
17
  * Undo/redo state history: a linear list of snapshots and a pointer to the current one.
8
18
  * Snapshots are strings (graph JSON): they are immutable, easy to compare and need no copying.
@@ -34,6 +44,19 @@ export declare class History {
34
44
  */
35
45
  undo(): string | null;
36
46
  redo(): string | null;
47
+ /**
48
+ * A copy of the whole history (the snapshots and the position), to put back with `restore`.
49
+ * Копия всей истории (снимки и положение), чтобы вернуть её через `restore`.
50
+ */
51
+ save(): HistoryState;
52
+ /**
53
+ * Puts a saved history back. The current snapshot of it should be the state of the document the app shows now;
54
+ * what is not (an index out of range, no snapshots) is refused with an error. A series of merged edits is not
55
+ * continued across a restore.
56
+ * Возвращает сохранённую историю. Текущий снимок в ней должен быть состоянием документа, который приложение показывает
57
+ * сейчас; негодное (положение вне списка, нет снимков) отклоняется ошибкой. Серия склеенных правок через возврат не продолжается.
58
+ */
59
+ restore(state: HistoryState): void;
37
60
  /**
38
61
  * Start the history over (for example, after loading a file).
39
62
  * Начать историю заново (например, после загрузки файла).
package/dist/history.js CHANGED
@@ -74,6 +74,29 @@ var History = class {
74
74
  return this.states[++this.index];
75
75
  }
76
76
  /**
77
+ * A copy of the whole history (the snapshots and the position), to put back with `restore`.
78
+ * Копия всей истории (снимки и положение), чтобы вернуть её через `restore`.
79
+ */
80
+ save() {
81
+ return {
82
+ states: [...this.states],
83
+ index: this.index
84
+ };
85
+ }
86
+ /**
87
+ * Puts a saved history back. The current snapshot of it should be the state of the document the app shows now;
88
+ * what is not (an index out of range, no snapshots) is refused with an error. A series of merged edits is not
89
+ * continued across a restore.
90
+ * Возвращает сохранённую историю. Текущий снимок в ней должен быть состоянием документа, который приложение показывает
91
+ * сейчас; негодное (положение вне списка, нет снимков) отклоняется ошибкой. Серия склеенных правок через возврат не продолжается.
92
+ */
93
+ restore(state) {
94
+ if (!Number.isInteger(state.index) || state.index < 0 || state.index >= state.states.length) throw new RangeError("History.restore: the position is outside the saved snapshots");
95
+ this.states = [...state.states];
96
+ this.index = state.index;
97
+ this.lastKey = void 0;
98
+ }
99
+ /**
77
100
  * Start the history over (for example, after loading a file).
78
101
  * Начать историю заново (например, после загрузки файла).
79
102
  */
@@ -1 +1 @@
1
- {"version":3,"file":"history.js","names":[],"sources":["../src/history.ts"],"sourcesContent":["/**\n * Edits with the same key made faster than this many ms apart merge into one entry (typing a number into a field and the like).\n * Правки с одним ключом, сделанные чаще чем раз в столько мс, склеиваются в одну запись (набор числа в поле и т.п.).\n */\nexport const COALESCE_MS = 800;\n\n/**\n * Undo/redo state history: a linear list of snapshots and a pointer to the current one.\n * Snapshots are strings (graph JSON): they are immutable, easy to compare and need no copying.\n * История состояний для undo/redo: линейный список снимков и указатель на текущий.\n * Снимки — строки (JSON графа): они неизменяемы, их легко сравнивать и не нужно копировать.\n */\nexport class History {\n private states: string[];\n private index = 0;\n private lastKey: string | undefined;\n private lastTime = 0;\n\n constructor(\n initial: string,\n private readonly limit = 100,\n private readonly now: () => number = Date.now,\n ) {\n this.states = [initial];\n }\n\n get canUndo(): boolean {\n return this.index > 0;\n }\n\n get canRedo(): boolean {\n return this.index < this.states.length - 1;\n }\n\n /**\n * Records a new state. If it does not differ from the current one, does nothing (returns false).\n * An edit discards the \"future\" (redo). With the same `key` in a row and within `COALESCE_MS`,\n * edits replace each other instead of piling up.\n * Записывает новое состояние. Если оно не отличается от текущего, ничего не делает (вернёт false).\n * Правка отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `COALESCE_MS`\n * правки заменяют друг друга, а не копятся.\n */\n commit(state: string, key?: string): boolean {\n if (state === this.states[this.index]) return false;\n\n const t = this.now();\n const atTop = this.index === this.states.length - 1;\n const coalesce = key !== undefined && key === this.lastKey && t - this.lastTime <= COALESCE_MS && this.index > 0 && atTop;\n\n if (coalesce) {\n this.states[this.index] = state;\n // Back to the state before the series of edits: no entry is needed.\n // Вернулись к состоянию до серии правок: запись не нужна.\n if (this.states[this.index - 1] === state) {\n this.states.pop();\n this.index--;\n }\n } else {\n this.states.length = this.index + 1;\n this.states.push(state);\n this.index++;\n if (this.states.length > this.limit + 1) {\n this.states.shift();\n this.index--;\n }\n }\n\n this.lastKey = key;\n this.lastTime = t;\n return true;\n }\n\n /**\n * Returns the previous state, or null if there is nothing to undo.\n * Возвращает предыдущее состояние или null, если отменять нечего.\n */\n undo(): string | null {\n if (!this.canUndo) return null;\n this.lastKey = undefined;\n return this.states[--this.index]!;\n }\n\n redo(): string | null {\n if (!this.canRedo) return null;\n this.lastKey = undefined;\n return this.states[++this.index]!;\n }\n\n /**\n * Start the history over (for example, after loading a file).\n * Начать историю заново (например, после загрузки файла).\n */\n reset(state: string): void {\n this.states = [state];\n this.index = 0;\n this.lastKey = undefined;\n }\n}\n"],"mappings":";;;;;AAIA,IAAa,cAAc;;;;;;;AAQ3B,IAAa,UAAb,MAAqB;CAQI;CACA;CARrB;CACA,QAAgB;CAChB;CACA,WAAmB;CAEnB,YACI,SACA,QAAyB,KACzB,MAAqC,KAAK,KAC5C;EAFmB,KAAA,QAAA;EACA,KAAA,MAAA;EAEjB,KAAK,SAAS,CAAC,OAAO;CAC1B;CAEA,IAAI,UAAmB;EACnB,OAAO,KAAK,QAAQ;CACxB;CAEA,IAAI,UAAmB;EACnB,OAAO,KAAK,QAAQ,KAAK,OAAO,SAAS;CAC7C;;;;;;;;;CAUA,OAAO,OAAe,KAAuB;EACzC,IAAI,UAAU,KAAK,OAAO,KAAK,QAAQ,OAAO;EAE9C,MAAM,IAAI,KAAK,IAAI;EACnB,MAAM,QAAQ,KAAK,UAAU,KAAK,OAAO,SAAS;EAGlD,IAFiB,QAAQ,KAAA,KAAa,QAAQ,KAAK,WAAW,IAAI,KAAK,YAAA,OAA2B,KAAK,QAAQ,KAAK,OAEtG;GACV,KAAK,OAAO,KAAK,SAAS;GAG1B,IAAI,KAAK,OAAO,KAAK,QAAQ,OAAO,OAAO;IACvC,KAAK,OAAO,IAAI;IAChB,KAAK;GACT;EACJ,OAAO;GACH,KAAK,OAAO,SAAS,KAAK,QAAQ;GAClC,KAAK,OAAO,KAAK,KAAK;GACtB,KAAK;GACL,IAAI,KAAK,OAAO,SAAS,KAAK,QAAQ,GAAG;IACrC,KAAK,OAAO,MAAM;IAClB,KAAK;GACT;EACJ;EAEA,KAAK,UAAU;EACf,KAAK,WAAW;EAChB,OAAO;CACX;;;;;CAMA,OAAsB;EAClB,IAAI,CAAC,KAAK,SAAS,OAAO;EAC1B,KAAK,UAAU,KAAA;EACf,OAAO,KAAK,OAAO,EAAE,KAAK;CAC9B;CAEA,OAAsB;EAClB,IAAI,CAAC,KAAK,SAAS,OAAO;EAC1B,KAAK,UAAU,KAAA;EACf,OAAO,KAAK,OAAO,EAAE,KAAK;CAC9B;;;;;CAMA,MAAM,OAAqB;EACvB,KAAK,SAAS,CAAC,KAAK;EACpB,KAAK,QAAQ;EACb,KAAK,UAAU,KAAA;CACnB;AACJ"}
1
+ {"version":3,"file":"history.js","names":[],"sources":["../src/history.ts"],"sourcesContent":["/**\n * Edits with the same key made faster than this many ms apart merge into one entry (typing a number into a field and the like).\n * Правки с одним ключом, сделанные чаще чем раз в столько мс, склеиваются в одну запись (набор числа в поле и т.п.).\n */\nexport const COALESCE_MS = 800;\n\n/**\n * A history taken out of a `History` to be put back later: for an editor with several documents, each keeps its own.\n * It is plain data (strings and a number), so it can be stored anywhere.\n * История, вынутая из `History`, чтобы вернуть её позже: у редактора с несколькими документами у каждого своя.\n * Это простые данные (строки и число), их можно хранить где угодно.\n */\nexport interface HistoryState {\n states: readonly string[];\n index: number;\n}\n\n/**\n * Undo/redo state history: a linear list of snapshots and a pointer to the current one.\n * Snapshots are strings (graph JSON): they are immutable, easy to compare and need no copying.\n * История состояний для undo/redo: линейный список снимков и указатель на текущий.\n * Снимки — строки (JSON графа): они неизменяемы, их легко сравнивать и не нужно копировать.\n */\nexport class History {\n private states: string[];\n private index = 0;\n private lastKey: string | undefined;\n private lastTime = 0;\n\n constructor(\n initial: string,\n private readonly limit = 100,\n private readonly now: () => number = Date.now,\n ) {\n this.states = [initial];\n }\n\n get canUndo(): boolean {\n return this.index > 0;\n }\n\n get canRedo(): boolean {\n return this.index < this.states.length - 1;\n }\n\n /**\n * Records a new state. If it does not differ from the current one, does nothing (returns false).\n * An edit discards the \"future\" (redo). With the same `key` in a row and within `COALESCE_MS`,\n * edits replace each other instead of piling up.\n * Записывает новое состояние. Если оно не отличается от текущего, ничего не делает (вернёт false).\n * Правка отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `COALESCE_MS`\n * правки заменяют друг друга, а не копятся.\n */\n commit(state: string, key?: string): boolean {\n if (state === this.states[this.index]) return false;\n\n const t = this.now();\n const atTop = this.index === this.states.length - 1;\n const coalesce = key !== undefined && key === this.lastKey && t - this.lastTime <= COALESCE_MS && this.index > 0 && atTop;\n\n if (coalesce) {\n this.states[this.index] = state;\n // Back to the state before the series of edits: no entry is needed.\n // Вернулись к состоянию до серии правок: запись не нужна.\n if (this.states[this.index - 1] === state) {\n this.states.pop();\n this.index--;\n }\n } else {\n this.states.length = this.index + 1;\n this.states.push(state);\n this.index++;\n if (this.states.length > this.limit + 1) {\n this.states.shift();\n this.index--;\n }\n }\n\n this.lastKey = key;\n this.lastTime = t;\n return true;\n }\n\n /**\n * Returns the previous state, or null if there is nothing to undo.\n * Возвращает предыдущее состояние или null, если отменять нечего.\n */\n undo(): string | null {\n if (!this.canUndo) return null;\n this.lastKey = undefined;\n return this.states[--this.index]!;\n }\n\n redo(): string | null {\n if (!this.canRedo) return null;\n this.lastKey = undefined;\n return this.states[++this.index]!;\n }\n\n /**\n * A copy of the whole history (the snapshots and the position), to put back with `restore`.\n * Копия всей истории (снимки и положение), чтобы вернуть её через `restore`.\n */\n save(): HistoryState {\n return { states: [...this.states], index: this.index };\n }\n\n /**\n * Puts a saved history back. The current snapshot of it should be the state of the document the app shows now;\n * what is not (an index out of range, no snapshots) is refused with an error. A series of merged edits is not\n * continued across a restore.\n * Возвращает сохранённую историю. Текущий снимок в ней должен быть состоянием документа, который приложение показывает\n * сейчас; негодное (положение вне списка, нет снимков) отклоняется ошибкой. Серия склеенных правок через возврат не продолжается.\n */\n restore(state: HistoryState): void {\n if (!Number.isInteger(state.index) || state.index < 0 || state.index >= state.states.length) {\n throw new RangeError('History.restore: the position is outside the saved snapshots');\n }\n this.states = [...state.states];\n this.index = state.index;\n this.lastKey = undefined;\n }\n\n /**\n * Start the history over (for example, after loading a file).\n * Начать историю заново (например, после загрузки файла).\n */\n reset(state: string): void {\n this.states = [state];\n this.index = 0;\n this.lastKey = undefined;\n }\n}\n"],"mappings":";;;;;AAIA,IAAa,cAAc;;;;;;;AAmB3B,IAAa,UAAb,MAAqB;CAQI;CACA;CARrB;CACA,QAAgB;CAChB;CACA,WAAmB;CAEnB,YACI,SACA,QAAyB,KACzB,MAAqC,KAAK,KAC5C;EAFmB,KAAA,QAAA;EACA,KAAA,MAAA;EAEjB,KAAK,SAAS,CAAC,OAAO;CAC1B;CAEA,IAAI,UAAmB;EACnB,OAAO,KAAK,QAAQ;CACxB;CAEA,IAAI,UAAmB;EACnB,OAAO,KAAK,QAAQ,KAAK,OAAO,SAAS;CAC7C;;;;;;;;;CAUA,OAAO,OAAe,KAAuB;EACzC,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B,KAAK,QAAQ;EACb,KAAK,UAAU,KAAA;CACnB;AACJ"}
package/dist/session.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type Camera, type ZoomLimits } from './camera';
2
+ import { type HistoryState } from './history';
2
3
  import type { SavedStorage } from './storage';
3
4
  export type NoticeArgs = readonly (string | number)[];
4
5
  /**
@@ -131,6 +132,8 @@ export declare function createDocumentSession<D, K extends string>(options: Sess
131
132
  commit: (key?: string) => void;
132
133
  undo: () => boolean;
133
134
  redo: () => boolean;
135
+ saveHistory: () => HistoryState;
136
+ restoreHistory: (state: HistoryState) => void;
134
137
  recorded: <A extends unknown[], R>(fn: (...args: A) => R, key?: (...args: A) => string) => (...args: A) => R;
135
138
  load: (next: D, view?: Camera, resetHistory?: boolean) => void;
136
139
  exportText: () => string;
package/dist/session.js CHANGED
@@ -90,6 +90,24 @@ function createDocumentSession(options) {
90
90
  scheduleSave();
91
91
  }
92
92
  /**
93
+ * The history of this document, to keep while another one is shown (`restoreHistory` puts it back). The `dirty` flag
94
+ * is not part of it: keep it with the history if the app wants it back too.
95
+ * История этого документа, чтобы хранить её, пока показан другой (`restoreHistory` возвращает её). Флаг `dirty` в неё
96
+ * не входит: если приложению нужен и он, хранить его надо вместе с историей.
97
+ */
98
+ const saveHistory = () => history.save();
99
+ /**
100
+ * Puts a saved history back, for a document that was just put on the screen (`load` with `resetHistory`, then this).
101
+ * The history decides `canUndo` / `canRedo`; `dirty` and the document are not touched, nothing is autosaved.
102
+ * Возвращает сохранённую историю документу, который только что выставлен на экран (`load` с `resetHistory`, потом это).
103
+ * История решает `canUndo` / `canRedo`; `dirty` и сам документ не трогаются, автосохранения нет.
104
+ */
105
+ function restoreHistory(state) {
106
+ history.restore(state);
107
+ canUndo.value = history.canUndo;
108
+ canRedo.value = history.canRedo;
109
+ }
110
+ /**
93
111
  * Remembers the current state as a history step. The same `key` in a row merges edits (typing text).
94
112
  * Запоминает текущее состояние как шаг истории. Одинаковый `key` подряд склеивает правки (набор текста).
95
113
  */
@@ -198,6 +216,8 @@ function createDocumentSession(options) {
198
216
  commit,
199
217
  undo,
200
218
  redo,
219
+ saveHistory,
220
+ restoreHistory,
201
221
  recorded,
202
222
  load,
203
223
  exportText,
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { ref } from 'vue';\nimport { clampZoom, zoomLimits, type Camera, type ZoomLimits } from './camera';\nimport { History } from './history';\nimport type { SavedStorage } from './storage';\n\nexport type NoticeArgs = readonly (string | number)[];\n\n/**\n * A short message to the user. Holds a translation key: the interface builds the text.\n * Короткое сообщение пользователю. Хранит ключ перевода: текст собирает интерфейс.\n */\nexport interface SessionNotice<K extends string = string> {\n kind: 'info' | 'error';\n key: K;\n args?: NoticeArgs;\n}\n\n/**\n * Why opening a file was refused; the interface builds the user text from `code`.\n * Причина отказа открыть файл; текст для пользователя собирает интерфейс по `code`.\n */\nexport interface LoadError {\n code: string;\n detail?: string | number;\n}\n\nexport type LoadResult<D> =\n | { ok: true; doc: D; view?: Camera; dropped: number }\n | { ok: false; error: LoadError };\n\n/**\n * Message keys the session shows by itself. The app dictionary must contain them.\n * Ключи сообщений, которые сессия показывает сама. Словарь приложения обязан их содержать.\n */\nexport interface SessionKeys<K extends string> {\n loaded: K; // {0} is the number of items (`countItems`) / {0} — число элементов (`countItems`)\n loadedWithDropped: K; // {0} is the number of items, {1} how many entries the codec dropped / {0} — число элементов, {1} — сколько записей отбросил кодек\n newDocument: K;\n saveFailed: K;\n restoreFailed: K;\n /**\n * The key for the reason a file was refused.\n * Ключ для причины отказа открыть файл.\n */\n loadError(code: string): K;\n}\n\nexport interface SessionOptions<D, K extends string> {\n /**\n * The document in the app store.\n * Документ в сторе приложения.\n */\n document: { get(): D; set(doc: D): void };\n /**\n * The view of a canvas editor: saved with the document and brought back on open. Leave it out for a document\n * without one (a list of notes): `serialize` then gets `undefined`, and a `view` from `parse` is ignored.\n * Вид редактора-холста: сохраняется с документом и возвращается при открытии. Не задавайте для документа без него\n * (список заметок): тогда `serialize` получает `undefined`, а `view` из `parse` пропускается.\n */\n camera?: { get(): Camera; set(camera: Camera): void };\n storage: SavedStorage;\n codec: {\n serialize(doc: D, view: Camera | undefined, pretty: boolean): string;\n parse(text: string): LoadResult<D>;\n };\n empty(): D;\n /**\n * How many items are in the document (nodes, notes): substituted into the message about opening a file.\n * Сколько элементов в документе (узлов, заметок): подставляется в сообщение об открытии файла.\n */\n countItems?(doc: D): number;\n /**\n * @deprecated The old name of `countItems`; still read when `countItems` is not given.\n * Старое имя `countItems`; читается, если `countItems` не задан.\n */\n countNodes?(doc: D): number;\n keys: SessionKeys<K>;\n /**\n * The document was replaced as a whole (open, new, restore): reset the selection, the drag, the palette.\n * Документ подменён целиком (открытие, новый, восстановление): сбросить выделение, протягивание, палитру.\n */\n onReset?(): void;\n /**\n * The state was restored from history (undo/redo): drop references to what is gone.\n * Состояние восстановлено из истории (undo/redo): убрать ссылки на то, чего больше нет.\n */\n onRestore?(doc: D): void;\n /**\n * The pause before autosave, ms.\n * Пауза перед автосохранением, мс.\n */\n autosaveDelay?: number;\n /**\n * How long to show a notice, ms.\n * Сколько секунд показывать уведомление, мс.\n */\n noticeMs?: number;\n /**\n * The zoom range a loaded view is clamped to: the same as the canvas `zoom` option (default 0.2…2).\n * Диапазон, в который зажимается масштаб загруженного вида: тот же, что у опции холста `zoom` (по умолчанию 0.2…2).\n */\n zoom?: Partial<ZoomLimits>;\n}\n\nconst DEFAULT_NOTICE_MS = 5000;\nconst DEFAULT_AUTOSAVE_MS = 400;\n\n/**\n * The lifecycle of an editor document: history (undo/redo with merged edits), autosave guarded against storage\n * failures, opening and saving a file, restore after a reload, notices.\n * The document, the camera and the file format belong to the app, only the mechanics are here.\n * Жизненный цикл документа редактора: история (undo/redo со склейкой правок), автосохранение с защитой от сбоев\n * хранилища, открытие и сохранение файла, восстановление после перезагрузки, уведомления.\n * Документ, камера и формат файла принадлежат приложению, здесь только механика.\n */\nexport function createDocumentSession<D, K extends string>(options: SessionOptions<D, K>) {\n const { document: doc, camera, storage, codec, keys } = options;\n const noticeMs = options.noticeMs ?? DEFAULT_NOTICE_MS;\n const count = (d: D) => (options.countItems ?? options.countNodes)?.(d) ?? 0;\n const autosaveDelay = options.autosaveDelay ?? DEFAULT_AUTOSAVE_MS;\n\n //---]>\n // notices\n // уведомления\n\n const notice = ref<SessionNotice<K> | null>(null);\n let noticeTimer: ReturnType<typeof setTimeout> | undefined;\n\n function showNotice(kind: SessionNotice<K>['kind'], key: K, args?: NoticeArgs) {\n notice.value = { kind, key, args };\n clearTimeout(noticeTimer);\n noticeTimer = setTimeout(() => (notice.value = null), noticeMs);\n }\n\n //---]>\n // autosave\n // автосохранение\n\n let autosaveOn = false;\n let saveTimer: ReturnType<typeof setTimeout> | undefined;\n let saveFailedShown = false;\n\n /**\n * Writes the document and the camera position to storage.\n * Записывает документ и положение камеры в хранилище.\n */\n function flushSave() {\n clearTimeout(saveTimer);\n saveTimer = undefined;\n if (!autosaveOn) return;\n\n if (storage.write(codec.serialize(doc.get(), camera?.get(), false))) {\n saveFailedShown = false;\n } else if (!saveFailedShown) {\n saveFailedShown = true; // tell once, not on every edit / сообщаем один раз, а не при каждой правке\n showNotice('error', keys.saveFailed);\n }\n }\n\n function scheduleSave() {\n if (!autosaveOn) return;\n clearTimeout(saveTimer);\n saveTimer = setTimeout(flushSave, autosaveDelay);\n }\n\n /**\n * Turns autosave on. Off by default (nothing is written in tests and before restore).\n * Edits are saved with a small delay, and at once when the tab is hidden or closed.\n * Returns a function that turns everything off.\n * Включает автосохранение. Выключено по умолчанию (в тестах и до восстановления ничего не пишется).\n * Правки сохраняются с небольшой задержкой, а при скрытии вкладки и закрытии сразу.\n * Возвращает функцию, которая всё отключает.\n */\n function startAutosave(): () => void {\n autosaveOn = true;\n const onHide = () => {\n if (document.visibilityState === 'hidden') flushSave();\n };\n window.addEventListener('pagehide', flushSave);\n document.addEventListener('visibilitychange', onHide);\n\n return () => {\n autosaveOn = false;\n clearTimeout(saveTimer);\n window.removeEventListener('pagehide', flushSave);\n document.removeEventListener('visibilitychange', onHide);\n };\n }\n\n //---]>\n // history\n // история\n\n const snapshot = () => JSON.stringify(doc.get());\n const history = new History(snapshot());\n const canUndo = ref(false);\n const canRedo = ref(false);\n /**\n * The document changed since it was opened or last marked saved (an edit, undo, redo, or a replacement by `load`).\n * Undoing back to the saved state does not clear it: only `markSaved` or a `load` with `resetHistory` does.\n * Документ изменился с момента открытия или последнего `markSaved` (правка, undo, redo, подмена через `load`).\n * Откат назад к сохранённому состоянию флаг не снимает: его снимает только `markSaved` или `load` с `resetHistory`.\n */\n const dirty = ref(false);\n\n function syncHistory() {\n canUndo.value = history.canUndo;\n canRedo.value = history.canRedo;\n dirty.value = true;\n scheduleSave(); // the document changed (an edit, undo or redo): autosave will pick it up / документ изменился (правка, undo или redo): автосохранение подхватит\n }\n\n /**\n * Remembers the current state as a history step. The same `key` in a row merges edits (typing text).\n * Запоминает текущее состояние как шаг истории. Одинаковый `key` подряд склеивает правки (набор текста).\n */\n function commit(key?: string) {\n history.commit(snapshot(), key);\n syncHistory();\n }\n\n function restore(state: string | null): boolean {\n if (state === null) return false;\n\n doc.set(JSON.parse(state) as D);\n options.onRestore?.(doc.get());\n syncHistory();\n return true;\n }\n\n const undo = () => restore(history.undo());\n const redo = () => restore(history.redo());\n\n /**\n * An action that changes the document: afterwards the state goes into history.\n * Действие, меняющее документ: после него состояние попадает в историю.\n */\n function recorded<A extends unknown[], R>(fn: (...args: A) => R, key?: (...args: A) => string): (...args: A) => R {\n return (...args) => {\n const result = fn(...args);\n commit(key?.(...args));\n return result;\n };\n }\n\n //---]>\n // opening, files, restore\n // открытие, файлы, восстановление\n\n /**\n * Replaces the document as a whole. Without `resetHistory` it is an ordinary edit: it can be undone.\n * Подменяет документ целиком. Без `resetHistory` это обычная правка: её можно отменить.\n */\n function load(next: D, view?: Camera, resetHistory = false) {\n doc.set(next);\n options.onReset?.();\n if (view && camera) camera.set({ x: view.x, y: view.y, z: clampZoom(view.z, zoomLimits(options.zoom)) });\n\n if (resetHistory) {\n history.reset(snapshot());\n syncHistory();\n dirty.value = false; // a fresh start: nothing to lose yet / чистый старт: терять пока нечего\n } else {\n commit();\n }\n }\n\n /**\n * The app has written the document somewhere (a file, a disk): `dirty` goes off until the next change.\n * Приложение записало документ куда-то (файл, диск): `dirty` снимается до следующей правки.\n */\n const markSaved = () => {\n dirty.value = false;\n };\n\n /**\n * The file text for download.\n * Текст файла для скачивания.\n */\n const exportText = () => codec.serialize(doc.get(), camera?.get(), true);\n\n /**\n * Opens a document from file text. On an error the document is unchanged. The result is shown as a notice.\n * Открывает документ из текста файла. При ошибке документ не меняется. Результат показывается уведомлением.\n */\n function importText(text: string): LoadError | null {\n const result = codec.parse(text);\n if (!result.ok) {\n const { code, detail } = result.error;\n showNotice('error', keys.loadError(code), detail === undefined ? undefined : [detail]);\n return result.error;\n }\n\n load(result.doc, result.view);\n const items = count(result.doc);\n if (result.dropped > 0) showNotice('error', keys.loadedWithDropped, [items, result.dropped]);\n else showNotice('info', keys.loaded, [items]);\n return null;\n }\n\n function newDocument() {\n load(options.empty(), { x: 0, y: 0, z: 1 });\n showNotice('info', keys.newDocument);\n }\n\n /**\n * At app start: brings the document back from autosave. Returns true if there was something to restore.\n * При старте приложения: поднимает документ из автосохранения. Возвращает true, если было что поднимать.\n */\n function restoreSaved(): boolean {\n const text = storage.read();\n if (text === null) return false;\n\n const result = codec.parse(text);\n if (!result.ok) {\n storage.backupBroken(text);\n showNotice('error', keys.restoreFailed);\n return false;\n }\n\n load(result.doc, result.view, true);\n return true;\n }\n\n return {\n notice,\n showNotice,\n canUndo,\n canRedo,\n dirty,\n markSaved,\n commit,\n undo,\n redo,\n recorded,\n load,\n exportText,\n importText,\n newDocument,\n restoreSaved,\n startAutosave,\n flushSave,\n };\n}\n\nexport type DocumentSession<D, K extends string> = ReturnType<typeof createDocumentSession<D, K>>;\n"],"mappings":";;;;AAwGA,IAAM,oBA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,WAAW,MAAgC;EAChD,MAAM,SAAS,MAAM,MAAM,IAAI;EAC/B,IAAI,CAAC,OAAO,IAAI;GACZ,MAAM,EAAE,MAAM,WAAW,OAAO;GAChC,WAAW,SAAS,KAAK,UAAU,IAAI,GAAG,WAAW,KAAA,IAAY,KAAA,IAAY,CAAC,MAAM,CAAC;GACrF,OAAO,OAAO;EAClB;EAEA,KAAK,OAAO,KAAK,OAAO,IAAI;EAC5B,MAAM,QAAQ,MAAM,OAAO,GAAG;EAC9B,IAAI,OAAO,UAAU,GAAG,WAAW,SAAS,KAAK,mBAAmB,CAAC,OAAO,OAAO,OAAO,CAAC;OACtF,WAAW,QAAQ,KAAK,QAAQ,CAAC,KAAK,CAAC;EAC5C,OAAO;CACX;CAEA,SAAS,cAAc;EACnB,KAAK,QAAQ,MAAM,GAAG;GAAE,GAAG;GAAG,GAAG;GAAG,GAAG;EAAE,CAAC;EAC1C,WAAW,QAAQ,KAAK,WAAW;CACvC;;;;;CAMA,SAAS,eAAwB;EAC7B,MAAM,OAAO,QAAQ,KAAK;EAC1B,IAAI,SAAS,MAAM,OAAO;EAE1B,MAAM,SAAS,MAAM,MAAM,IAAI;EAC/B,IAAI,CAAC,OAAO,IAAI;GACZ,QAAQ,aAAa,IAAI;GACzB,WAAW,SAAS,KAAK,aAAa;GACtC,OAAO;EACX;EAEA,KAAK,OAAO,KAAK,OAAO,MAAM,IAAI;EAClC,OAAO;CACX;CAEA,OAAO;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ;AACJ"}
1
+ {"version":3,"file":"session.js","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { ref } from 'vue';\nimport { clampZoom, zoomLimits, type Camera, type ZoomLimits } from './camera';\nimport { History, type HistoryState } from './history';\nimport type { SavedStorage } from './storage';\n\nexport type NoticeArgs = readonly (string | number)[];\n\n/**\n * A short message to the user. Holds a translation key: the interface builds the text.\n * Короткое сообщение пользователю. Хранит ключ перевода: текст собирает интерфейс.\n */\nexport interface SessionNotice<K extends string = string> {\n kind: 'info' | 'error';\n key: K;\n args?: NoticeArgs;\n}\n\n/**\n * Why opening a file was refused; the interface builds the user text from `code`.\n * Причина отказа открыть файл; текст для пользователя собирает интерфейс по `code`.\n */\nexport interface LoadError {\n code: string;\n detail?: string | number;\n}\n\nexport type LoadResult<D> =\n | { ok: true; doc: D; view?: Camera; dropped: number }\n | { ok: false; error: LoadError };\n\n/**\n * Message keys the session shows by itself. The app dictionary must contain them.\n * Ключи сообщений, которые сессия показывает сама. Словарь приложения обязан их содержать.\n */\nexport interface SessionKeys<K extends string> {\n loaded: K; // {0} is the number of items (`countItems`) / {0} — число элементов (`countItems`)\n loadedWithDropped: K; // {0} is the number of items, {1} how many entries the codec dropped / {0} — число элементов, {1} — сколько записей отбросил кодек\n newDocument: K;\n saveFailed: K;\n restoreFailed: K;\n /**\n * The key for the reason a file was refused.\n * Ключ для причины отказа открыть файл.\n */\n loadError(code: string): K;\n}\n\nexport interface SessionOptions<D, K extends string> {\n /**\n * The document in the app store.\n * Документ в сторе приложения.\n */\n document: { get(): D; set(doc: D): void };\n /**\n * The view of a canvas editor: saved with the document and brought back on open. Leave it out for a document\n * without one (a list of notes): `serialize` then gets `undefined`, and a `view` from `parse` is ignored.\n * Вид редактора-холста: сохраняется с документом и возвращается при открытии. Не задавайте для документа без него\n * (список заметок): тогда `serialize` получает `undefined`, а `view` из `parse` пропускается.\n */\n camera?: { get(): Camera; set(camera: Camera): void };\n storage: SavedStorage;\n codec: {\n serialize(doc: D, view: Camera | undefined, pretty: boolean): string;\n parse(text: string): LoadResult<D>;\n };\n empty(): D;\n /**\n * How many items are in the document (nodes, notes): substituted into the message about opening a file.\n * Сколько элементов в документе (узлов, заметок): подставляется в сообщение об открытии файла.\n */\n countItems?(doc: D): number;\n /**\n * @deprecated The old name of `countItems`; still read when `countItems` is not given.\n * Старое имя `countItems`; читается, если `countItems` не задан.\n */\n countNodes?(doc: D): number;\n keys: SessionKeys<K>;\n /**\n * The document was replaced as a whole (open, new, restore): reset the selection, the drag, the palette.\n * Документ подменён целиком (открытие, новый, восстановление): сбросить выделение, протягивание, палитру.\n */\n onReset?(): void;\n /**\n * The state was restored from history (undo/redo): drop references to what is gone.\n * Состояние восстановлено из истории (undo/redo): убрать ссылки на то, чего больше нет.\n */\n onRestore?(doc: D): void;\n /**\n * The pause before autosave, ms.\n * Пауза перед автосохранением, мс.\n */\n autosaveDelay?: number;\n /**\n * How long to show a notice, ms.\n * Сколько секунд показывать уведомление, мс.\n */\n noticeMs?: number;\n /**\n * The zoom range a loaded view is clamped to: the same as the canvas `zoom` option (default 0.2…2).\n * Диапазон, в который зажимается масштаб загруженного вида: тот же, что у опции холста `zoom` (по умолчанию 0.2…2).\n */\n zoom?: Partial<ZoomLimits>;\n}\n\nconst DEFAULT_NOTICE_MS = 5000;\nconst DEFAULT_AUTOSAVE_MS = 400;\n\n/**\n * The lifecycle of an editor document: history (undo/redo with merged edits), autosave guarded against storage\n * failures, opening and saving a file, restore after a reload, notices.\n * The document, the camera and the file format belong to the app, only the mechanics are here.\n * Жизненный цикл документа редактора: история (undo/redo со склейкой правок), автосохранение с защитой от сбоев\n * хранилища, открытие и сохранение файла, восстановление после перезагрузки, уведомления.\n * Документ, камера и формат файла принадлежат приложению, здесь только механика.\n */\nexport function createDocumentSession<D, K extends string>(options: SessionOptions<D, K>) {\n const { document: doc, camera, storage, codec, keys } = options;\n const noticeMs = options.noticeMs ?? DEFAULT_NOTICE_MS;\n const count = (d: D) => (options.countItems ?? options.countNodes)?.(d) ?? 0;\n const autosaveDelay = options.autosaveDelay ?? DEFAULT_AUTOSAVE_MS;\n\n //---]>\n // notices\n // уведомления\n\n const notice = ref<SessionNotice<K> | null>(null);\n let noticeTimer: ReturnType<typeof setTimeout> | undefined;\n\n function showNotice(kind: SessionNotice<K>['kind'], key: K, args?: NoticeArgs) {\n notice.value = { kind, key, args };\n clearTimeout(noticeTimer);\n noticeTimer = setTimeout(() => (notice.value = null), noticeMs);\n }\n\n //---]>\n // autosave\n // автосохранение\n\n let autosaveOn = false;\n let saveTimer: ReturnType<typeof setTimeout> | undefined;\n let saveFailedShown = false;\n\n /**\n * Writes the document and the camera position to storage.\n * Записывает документ и положение камеры в хранилище.\n */\n function flushSave() {\n clearTimeout(saveTimer);\n saveTimer = undefined;\n if (!autosaveOn) return;\n\n if (storage.write(codec.serialize(doc.get(), camera?.get(), false))) {\n saveFailedShown = false;\n } else if (!saveFailedShown) {\n saveFailedShown = true; // tell once, not on every edit / сообщаем один раз, а не при каждой правке\n showNotice('error', keys.saveFailed);\n }\n }\n\n function scheduleSave() {\n if (!autosaveOn) return;\n clearTimeout(saveTimer);\n saveTimer = setTimeout(flushSave, autosaveDelay);\n }\n\n /**\n * Turns autosave on. Off by default (nothing is written in tests and before restore).\n * Edits are saved with a small delay, and at once when the tab is hidden or closed.\n * Returns a function that turns everything off.\n * Включает автосохранение. Выключено по умолчанию (в тестах и до восстановления ничего не пишется).\n * Правки сохраняются с небольшой задержкой, а при скрытии вкладки и закрытии сразу.\n * Возвращает функцию, которая всё отключает.\n */\n function startAutosave(): () => void {\n autosaveOn = true;\n const onHide = () => {\n if (document.visibilityState === 'hidden') flushSave();\n };\n window.addEventListener('pagehide', flushSave);\n document.addEventListener('visibilitychange', onHide);\n\n return () => {\n autosaveOn = false;\n clearTimeout(saveTimer);\n window.removeEventListener('pagehide', flushSave);\n document.removeEventListener('visibilitychange', onHide);\n };\n }\n\n //---]>\n // history\n // история\n\n const snapshot = () => JSON.stringify(doc.get());\n const history = new History(snapshot());\n const canUndo = ref(false);\n const canRedo = ref(false);\n /**\n * The document changed since it was opened or last marked saved (an edit, undo, redo, or a replacement by `load`).\n * Undoing back to the saved state does not clear it: only `markSaved` or a `load` with `resetHistory` does.\n * Документ изменился с момента открытия или последнего `markSaved` (правка, undo, redo, подмена через `load`).\n * Откат назад к сохранённому состоянию флаг не снимает: его снимает только `markSaved` или `load` с `resetHistory`.\n */\n const dirty = ref(false);\n\n function syncHistory() {\n canUndo.value = history.canUndo;\n canRedo.value = history.canRedo;\n dirty.value = true;\n scheduleSave(); // the document changed (an edit, undo or redo): autosave will pick it up / документ изменился (правка, undo или redo): автосохранение подхватит\n }\n\n /**\n * The history of this document, to keep while another one is shown (`restoreHistory` puts it back). The `dirty` flag\n * is not part of it: keep it with the history if the app wants it back too.\n * История этого документа, чтобы хранить её, пока показан другой (`restoreHistory` возвращает её). Флаг `dirty` в неё\n * не входит: если приложению нужен и он, хранить его надо вместе с историей.\n */\n const saveHistory = (): HistoryState => history.save();\n\n /**\n * Puts a saved history back, for a document that was just put on the screen (`load` with `resetHistory`, then this).\n * The history decides `canUndo` / `canRedo`; `dirty` and the document are not touched, nothing is autosaved.\n * Возвращает сохранённую историю документу, который только что выставлен на экран (`load` с `resetHistory`, потом это).\n * История решает `canUndo` / `canRedo`; `dirty` и сам документ не трогаются, автосохранения нет.\n */\n function restoreHistory(state: HistoryState) {\n history.restore(state);\n canUndo.value = history.canUndo;\n canRedo.value = history.canRedo;\n }\n\n /**\n * Remembers the current state as a history step. The same `key` in a row merges edits (typing text).\n * Запоминает текущее состояние как шаг истории. Одинаковый `key` подряд склеивает правки (набор текста).\n */\n function commit(key?: string) {\n history.commit(snapshot(), key);\n syncHistory();\n }\n\n function restore(state: string | null): boolean {\n if (state === null) return false;\n\n doc.set(JSON.parse(state) as D);\n options.onRestore?.(doc.get());\n syncHistory();\n return true;\n }\n\n const undo = () => restore(history.undo());\n const redo = () => restore(history.redo());\n\n /**\n * An action that changes the document: afterwards the state goes into history.\n * Действие, меняющее документ: после него состояние попадает в историю.\n */\n function recorded<A extends unknown[], R>(fn: (...args: A) => R, key?: (...args: A) => string): (...args: A) => R {\n return (...args) => {\n const result = fn(...args);\n commit(key?.(...args));\n return result;\n };\n }\n\n //---]>\n // opening, files, restore\n // открытие, файлы, восстановление\n\n /**\n * Replaces the document as a whole. Without `resetHistory` it is an ordinary edit: it can be undone.\n * Подменяет документ целиком. Без `resetHistory` это обычная правка: её можно отменить.\n */\n function load(next: D, view?: Camera, resetHistory = false) {\n doc.set(next);\n options.onReset?.();\n if (view && camera) camera.set({ x: view.x, y: view.y, z: clampZoom(view.z, zoomLimits(options.zoom)) });\n\n if (resetHistory) {\n history.reset(snapshot());\n syncHistory();\n dirty.value = false; // a fresh start: nothing to lose yet / чистый старт: терять пока нечего\n } else {\n commit();\n }\n }\n\n /**\n * The app has written the document somewhere (a file, a disk): `dirty` goes off until the next change.\n * Приложение записало документ куда-то (файл, диск): `dirty` снимается до следующей правки.\n */\n const markSaved = () => {\n dirty.value = false;\n };\n\n /**\n * The file text for download.\n * Текст файла для скачивания.\n */\n const exportText = () => codec.serialize(doc.get(), camera?.get(), true);\n\n /**\n * Opens a document from file text. On an error the document is unchanged. The result is shown as a notice.\n * Открывает документ из текста файла. При ошибке документ не меняется. Результат показывается уведомлением.\n */\n function importText(text: string): LoadError | null {\n const result = codec.parse(text);\n if (!result.ok) {\n const { code, detail } = result.error;\n showNotice('error', keys.loadError(code), detail === undefined ? undefined : [detail]);\n return result.error;\n }\n\n load(result.doc, result.view);\n const items = count(result.doc);\n if (result.dropped > 0) showNotice('error', keys.loadedWithDropped, [items, result.dropped]);\n else showNotice('info', keys.loaded, [items]);\n return null;\n }\n\n function newDocument() {\n load(options.empty(), { x: 0, y: 0, z: 1 });\n showNotice('info', keys.newDocument);\n }\n\n /**\n * At app start: brings the document back from autosave. Returns true if there was something to restore.\n * При старте приложения: поднимает документ из автосохранения. Возвращает true, если было что поднимать.\n */\n function restoreSaved(): boolean {\n const text = storage.read();\n if (text === null) return false;\n\n const result = codec.parse(text);\n if (!result.ok) {\n storage.backupBroken(text);\n showNotice('error', keys.restoreFailed);\n return false;\n }\n\n load(result.doc, result.view, true);\n return true;\n }\n\n return {\n notice,\n showNotice,\n canUndo,\n canRedo,\n dirty,\n markSaved,\n commit,\n undo,\n redo,\n saveHistory,\n restoreHistory,\n recorded,\n load,\n exportText,\n importText,\n newDocument,\n restoreSaved,\n startAutosave,\n flushSave,\n };\n}\n\nexport type DocumentSession<D, K extends string> = ReturnType<typeof createDocumentSession<D, K>>;\n"],"mappings":";;;;AAwGA,IAAM,oBAAoB;AAC1B,IAAM,sBAAsB;;;;;;;;;AAU5B,SAAgB,sBAA2C,SAA+B;CACtF,MAAM,EAAE,UAAU,KAAK,QAAQ,SAAS,OAAO,SAAS;CACxD,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,SAAS,OAAU,QAAQ,cAAc,QAAQ,WAAA,GAAc,CAAC,KAAK;CAC3E,MAAM,gBAAgB,QAAQ,iBAAiB;CAM/C,MAAM,SAAS,IAA6B,IAAI;CAChD,IAAI;CAEJ,SAAS,WAAW,MAAgC,KAAQ,MAAmB;EAC3E,OAAO,QAAQ;GAAE;GAAM;GAAK;EAAK;EACjC,aAAa,WAAW;EACxB,cAAc,iBAAkB,OAAO,QAAQ,MAAO,QAAQ;CAClE;CAMA,IAAI,aAAa;CACjB,IAAI;CACJ,IAAI,kBAAkB;;;;;CAMtB,SAAS,YAAY;EACjB,aAAa,SAAS;EACtB,YAAY,KAAA;EACZ,IAAI,CAAC,YAAY;EAEjB,IAAI,QAAQ,MAAM,MAAM,UAAU,IAAI,IAAI,GAAG,QAAQ,IAAI,GAAG,KAAK,CAAC,GAC9D,kBAAkB;OACf,IAAI,CAAC,iBAAiB;GACzB,kBAAkB;GAClB,WAAW,SAAS,KAAK,UAAU;EACvC;CACJ;CAEA,SAAS,eAAe;EACpB,IAAI,CAAC,YAAY;EACjB,aAAa,SAAS;EACtB,YAAY,WAAW,WAAW,aAAa;CACnD;;;;;;;;;CAUA,SAAS,gBAA4B;EACjC,aAAa;EACb,MAAM,eAAe;GACjB,IAAI,SAAS,oBAAoB,UAAU,UAAU;EACzD;EACA,OAAO,iBAAiB,YAAY,SAAS;EAC7C,SAAS,iBAAiB,oBAAoB,MAAM;EAEpD,aAAa;GACT,aAAa;GACb,aAAa,SAAS;GAC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;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ;AACJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@1337exp/taoux",
3
- "version": "0.12.1",
3
+ "version": "0.13.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",
@@ -26,11 +26,11 @@ controls, or with your own design.
26
26
  | Import | What for |
27
27
  |---|---|
28
28
  | `camera` | pan, zoom around the cursor, screen ↔ world (`zoomAt`; the range is 0.2…2 unless you pass `ZoomLimits`), `fitCamera(rect, size, padding?, limits?)` for "zoom to fit" |
29
- | `history` | `new History(snapshot)`: undo / redo on string snapshots, rapid edits with one `key` merged into one step |
29
+ | `history` | `new History(snapshot)`: undo / redo on string snapshots, rapid edits with one `key` merged into one step; `save()` / `restore(state)` take a whole history out and put it back (one per document in a tabbed editor) |
30
30
  | `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 |
31
31
  | `swiperow` | `<TaoxSwipeRow :start="{ id, label, icon, tone }" :end="[{ id, label, icon, tone }]" v-model:open @action="run">` around a list row: a pull to the start runs `start` past a threshold, to the end opens the actions, a long pull runs the last one (`fullSwipe`, on by default); a mouse drags only with `mouse`; `:tabbable="false"` takes the actions out of the Tab order when the app has its own keys for them; an open row closes on a click on it or a press outside, and that click does not go on (once; `:swallow-outside-click="false"` lets the outside one through); `--tx-swipe-bg` for a row right on the page (see docs/swiperow.md); import `@1337exp/taoux/swiperow.css`. Needs TaoUI (tier 2) |
32
32
  | `sortable` | `useSortable(listRef, { onMove: (from, to) => (list.value = moveItem(list.value, from, to)) })`; mark each item `data-sortable-item` and a focusable grip inside it `data-sortable-handle` (a TaoButton with `icon="tao-grip"` and an aria-label); style `[data-sortable-dragging]` / `[data-sortable-lifted]`. Keyboard: Space lifts, arrows move, Space drops, Esc returns; `texts: sortableTextsRu` for Russian; works inside a zoomed (scaled) canvas too |
33
- | `session` | `createDocumentSession(...)`: history + autosave + files + restore + notices for one document; `canUndo` / `canRedo` refs; `dirty` ref + `markSaved()` for an "unsaved" mark (a flag, not a history position). `camera` is optional (a list, not a canvas); count with `countItems` (`countNodes` is its old name); `zoom` clamps a loaded view to the canvas range |
33
+ | `session` | `createDocumentSession(...)`: history + autosave + files + restore + notices for one document; `canUndo` / `canRedo` refs; `dirty` ref + `markSaved()` for an "unsaved" mark (a flag, not a history position); `saveHistory()` / `restoreHistory(state)` give each of several documents its own undo (`load` the next with `resetHistory`, then restore its history). `camera` is optional (a list, not a canvas); count with `countItems` (`countNodes` is its old name); `zoom` clamps a loaded view to the canvas range |
34
34
  | `commands` | `createCommands([...])`: one registry for menus, shortcuts and palettes (see below) |
35
35
  | `hotkeys` | `parseHotkey('Mod+Shift+Z')`, `matchHotkey`, `formatHotkey` (`Ctrl+Shift+Z` / `⇧⌘Z`), `isReservedHotkey`, `bindHotkeys(element, map)` |
36
36
  | `storage` | autosave to localStorage that never throws; `tryWrite` gives the reason (`quota` / `denied`), `remove`, `subscribe` for changes from other tabs |