@1337exp/taoux 0.12.0 → 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,18 @@
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
+
10
+ ## 0.12.1
11
+
12
+ Nothing to migrate; the behaviour of `zip` does not change.
13
+
14
+ - **`zip`: checks that other checks already cover are gone, and the tests hold the rest.** The reader no longer repeats an absolute-path test (an empty first part of the path already refuses it), a stored-size test and a running total (the size of every file is verified against its declared one, so the total is the declared total, which is judged before unpacking). New tests pin what a mutation check showed to be unguarded: an end record that sits inside the archive comment, the file count of the record, a total-size refusal that comes before the rest of the archive is touched, a declared size bigger than the data with a matching CRC, a packed size running past the data, names that are not UTF-8 (refused with the UTF-8 flag, read as Latin-1 without it) and a date before 1980.
15
+
3
16
  ## 0.12.0
4
17
 
5
18
  Nothing to migrate: a new module and new optional members.
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 re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,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,I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AAK,MAAM;GAAG,OAAO,KAAK;EAAM;CACzD;;;;;;;;CASA,QAAQ,OAA2B;EAC/B,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,KAAK,MAAM,QAAQ,KAAK,MAAM,SAAS,MAAM,OAAO,QACjF,MAAM,IAAI,WAAW,8DAA8D;EAEvF,KAAK,SAAS,CAAC,GAAG,MAAM,MAAM;EAC9B,KAAK,QAAQ,MAAM;EACnB,KAAK,UAAU,KAAA;CACnB;;;;;CAMA,MAAM,OAAqB;EACvB,KAAK,SAAS,CAAC,KAAK;EACpB,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,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;;;;;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;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;G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AAQ,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;EACA;EACA;CACJ;AACJ"}
package/dist/zip.js CHANGED
@@ -37,7 +37,7 @@ var encoder = new TextEncoder();
37
37
  * трогать нельзя, поэтому такие имена ни входят, ни выходят.
38
38
  */
39
39
  function assertName(name) {
40
- if (name === "" || name.startsWith("/") || name.includes("\\") || /[\x00-\x1f\x7f]/.test(name) || name.split("/").some((part) => part === "" || part === "." || part === "..")) throw new ZipError("unsafeName", JSON.stringify(name));
40
+ if (name === "" || name.includes("\\") || /[\x00-\x1f\x7f]/.test(name) || name.split("/").some((part) => part === "" || part === "." || part === "..")) throw new ZipError("unsafeName", JSON.stringify(name));
41
41
  }
42
42
  var crcTable = Array.from({ length: 256 }, (_, n) => {
43
43
  let c = n;
@@ -107,7 +107,7 @@ async function createZip(entries, options = {}) {
107
107
  const crc = crc32(entry.data);
108
108
  let method = STORED;
109
109
  let stored = entry.data;
110
- if (options.compress !== "store" && entry.data.length > 0 && !ALREADY_COMPRESSED.test(entry.name)) {
110
+ if (options.compress !== "store" && !ALREADY_COMPRESSED.test(entry.name)) {
111
111
  const packed = await through(entry.data, new CompressionStream("deflate-raw"));
112
112
  if (packed.length < entry.data.length) {
113
113
  method = DEFLATED;
@@ -206,7 +206,6 @@ async function readZip(data, limits = {}) {
206
206
  const seen = /* @__PURE__ */ new Set();
207
207
  let at = directoryOffset;
208
208
  let declaredTotal = 0;
209
- let total = 0;
210
209
  for (let n = 0; n < count; n++) {
211
210
  if (at + 46 > end || view.getUint32(at, true) !== CENTRAL) throw new ZipError("corrupt", "directory");
212
211
  const flags = view.getUint16(at + 8, true);
@@ -238,17 +237,13 @@ async function readZip(data, limits = {}) {
238
237
  if (start + packedSize > directoryOffset) throw new ZipError("corrupt", name);
239
238
  const packed = data.subarray(start, start + packedSize);
240
239
  let bytes;
241
- if (method === STORED) {
242
- if (packedSize !== size) throw new ZipError("corrupt", name);
243
- bytes = packed.slice();
244
- } else try {
240
+ if (method === STORED) bytes = packed.slice();
241
+ else try {
245
242
  bytes = await through(packed, new DecompressionStream("deflate-raw"), size);
246
243
  } catch {
247
244
  throw new ZipError("corrupt", name);
248
245
  }
249
246
  if (bytes.length !== size || crc32(bytes) !== crc) throw new ZipError("corrupt", name);
250
- total += bytes.length;
251
- if (total > maxTotalBytes) throw new ZipError("tooLarge", name);
252
247
  result.push({
253
248
  name,
254
249
  data: bytes
package/dist/zip.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"zip.js","names":[],"sources":["../src/zip.ts"],"sourcesContent":["// ZIP without libraries: the browser's CompressionStream does the deflate. No DOM, no Vue.\n// ZIP без библиотек: deflate делает CompressionStream браузера. Без DOM и Vue.\n\n/**\n * A file in an archive: the path with `/` as the separator (`assets/hero.png`) and its bytes.\n * Файл в архиве: путь с разделителем `/` (`assets/hero.png`) и его байты.\n */\nexport interface ZipEntry {\n name: string;\n data: Uint8Array;\n}\n\nexport type ZipErrorCode =\n | 'notZip' // not an archive at all / это вообще не архив\n | 'unsupported' // encrypted, ZIP64, several disks, an unknown method / шифрование, ZIP64, несколько дисков, незнакомый метод\n | 'corrupt' // damaged: bounds, size, CRC, a failed inflate / повреждён: границы, размер, CRC, сбой распаковки\n | 'unsafeName' // a path that would leave the folder it is unpacked into / путь, который выбрался бы из папки распаковки\n | 'duplicate' // the same name twice / одно имя дважды\n | 'tooMany' // more files than allowed / файлов больше, чем разрешено\n | 'tooLarge'; // a file or the whole archive unpacks bigger than allowed / файл или весь архив распакуется больше, чем разрешено\n\n/**\n * Why an archive was refused or could not be written. The interface builds the user text from `code`.\n * Почему архив отклонён или не записан. Текст для пользователя собирает интерфейс по `code`.\n */\nexport class ZipError extends Error {\n constructor(\n readonly code: ZipErrorCode,\n readonly detail?: string,\n ) {\n super(detail === undefined ? code : `${code}: ${detail}`);\n this.name = 'ZipError';\n }\n}\n\n/**\n * Limits of reading. An archive comes from outside, and a few KB can unpack into gigabytes, so the sizes are checked\n * twice: the declared ones before unpacking and the real ones while unpacking.\n * Пределы чтения. Архив приходит извне, а несколько КБ могут распаковаться в гигабайты, поэтому размеры проверяются\n * дважды: объявленные до распаковки и настоящие во время неё.\n */\nexport interface ZipReadLimits {\n /** Files in the archive. Default 10 000. / Файлов в архиве. По умолчанию 10 000. */\n maxEntries?: number;\n /** Bytes of one unpacked file. Default 512 MiB. / Байт в одном распакованном файле. По умолчанию 512 МиБ. */\n maxEntryBytes?: number;\n /** Bytes of all unpacked files together. Default 1 GiB. / Байт во всех файлах вместе. По умолчанию 1 ГиБ. */\n maxTotalBytes?: number;\n}\n\nexport const ZIP_LIMITS: Required<ZipReadLimits> = { maxEntries: 10_000, maxEntryBytes: 512 * 1024 * 1024, maxTotalBytes: 1024 * 1024 * 1024 };\n\nexport interface ZipWriteOptions {\n /** Modification time written for every file. Now by default. / Время изменения у всех файлов. По умолчанию сейчас. */\n date?: Date;\n /**\n * `auto` (default): a file is deflated unless it is already compressed (PNG, JPEG, WebP, audio, video, archives) and\n * only when that makes it smaller; `store`: everything as it is.\n * `auto` (по умолчанию): файл сжимается, если он ещё не сжат (PNG, JPEG, WebP, звук, видео, архивы) и только когда\n * от этого становится меньше; `store`: всё как есть.\n */\n compress?: 'auto' | 'store';\n}\n\nconst LOCAL = 0x04034b50;\nconst CENTRAL = 0x02014b50;\nconst END = 0x06054b50;\nconst VERSION = 20; // 2.0: the lowest that every unzip tool understands / 2.0: ниже все распаковщики понимают\nconst UTF8_NAMES = 0x0800;\nconst ENCRYPTED = 0x0001 | 0x0040;\nconst STORED = 0;\nconst DEFLATED = 8;\nconst MAX32 = 0xffffffff;\nconst MAX16 = 0xffff;\nconst ALREADY_COMPRESSED = /\\.(png|jpe?g|gif|webp|avif|zip|gz|bz2|7z|rar|mp3|ogg|opus|m4a|aac|mp4|webm|mov|woff2?)$/i;\n\nconst encoder = new TextEncoder();\n\n/**\n * A path that would climb out of the folder it is unpacked into (`../x`, `/etc/x`, `a\\..\\x`) is how a ZIP overwrites\n * files it should not touch, so such names never get in or out.\n * Путь, который выбрался бы из папки распаковки (`../x`, `/etc/x`, `a\\..\\x`), — это способ ZIP затереть то, что ему\n * трогать нельзя, поэтому такие имена ни входят, ни выходят.\n */\nfunction assertName(name: string): void {\n const unsafe =\n name === '' ||\n name.startsWith('/') ||\n name.includes('\\\\') ||\n /[\\x00-\\x1f\\x7f]/.test(name) ||\n name.split('/').some((part) => part === '' || part === '.' || part === '..');\n if (unsafe) throw new ZipError('unsafeName', JSON.stringify(name));\n}\n\nconst crcTable = Array.from({ length: 256 }, (_, n) => {\n let c = n;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n return c >>> 0;\n});\n\nfunction crc32(data: Uint8Array): number {\n let c = 0xffffffff;\n for (let i = 0; i < data.length; i++) c = crcTable[(c ^ data[i]!) & 0xff]! ^ (c >>> 8);\n return (c ^ 0xffffffff) >>> 0;\n}\n\n/** Local time as DOS date and time (2 s resolution, from 1980). / Местное время как DOS-дата и время (шаг 2 с, с 1980). */\nfunction dosTime(date: Date): { time: number; day: number } {\n const year = Math.max(1980, date.getFullYear());\n return {\n time: (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1),\n day: ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate(),\n };\n}\n\n/** Passes the bytes through a (de)compression stream. `max` stops a result that grows past what is expected. */\nasync function through(data: Uint8Array, transform: CompressionStream | DecompressionStream, max = Infinity): Promise<Uint8Array> {\n const source = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(data);\n controller.close();\n },\n });\n const reader = source.pipeThrough(transform as unknown as ReadableWritablePair<Uint8Array, Uint8Array>).getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > max) {\n await reader.cancel();\n throw new ZipError('corrupt', 'size');\n }\n chunks.push(value);\n }\n return concat(chunks, total);\n}\n\nfunction concat(chunks: readonly Uint8Array[], total = chunks.reduce((n, c) => n + c.length, 0)): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(total);\n let at = 0;\n for (const c of chunks) {\n out.set(c, at);\n at += c.length;\n }\n return out;\n}\n\n//--------------------------------------------------\n// writing / запись\n\n/**\n * Writes a ZIP archive. Names are UTF-8; no ZIP64, so up to 65 535 files and 4 GiB. Files already compressed are stored\n * as they are (see `compress`), the rest are deflated.\n * Пишет ZIP-архив. Имена в UTF-8; без ZIP64: до 65 535 файлов и 4 ГиБ. Уже сжатые файлы кладутся как есть\n * (см. `compress`), остальные сжимаются.\n */\nexport async function createZip(entries: readonly ZipEntry[], options: ZipWriteOptions = {}): Promise<Uint8Array<ArrayBuffer>> {\n if (entries.length > MAX16) throw new ZipError('tooMany', `${entries.length} files do not fit into a ZIP without ZIP64`);\n const { time, day } = dosTime(options.date ?? new Date());\n const seen = new Set<string>();\n const body: Uint8Array[] = [];\n const central: Uint8Array[] = [];\n let offset = 0;\n\n for (const entry of entries) {\n assertName(entry.name);\n if (seen.has(entry.name)) throw new ZipError('duplicate', entry.name);\n seen.add(entry.name);\n\n const name = encoder.encode(entry.name);\n const crc = crc32(entry.data);\n let method = STORED;\n let stored = entry.data;\n if (options.compress !== 'store' && entry.data.length > 0 && !ALREADY_COMPRESSED.test(entry.name)) {\n const packed = await through(entry.data, new CompressionStream('deflate-raw'));\n if (packed.length < entry.data.length) {\n method = DEFLATED;\n stored = packed;\n }\n }\n if (entry.data.length > MAX32 || offset > MAX32) throw new ZipError('tooLarge', entry.name);\n\n const local = new DataView(new ArrayBuffer(30));\n local.setUint32(0, LOCAL, true);\n local.setUint16(4, VERSION, true);\n local.setUint16(6, UTF8_NAMES, true);\n local.setUint16(8, method, true);\n local.setUint16(10, time, true);\n local.setUint16(12, day, true);\n local.setUint32(14, crc, true);\n local.setUint32(18, stored.length, true);\n local.setUint32(22, entry.data.length, true);\n local.setUint16(26, name.length, true);\n local.setUint16(28, 0, true);\n\n const head = new DataView(new ArrayBuffer(46));\n head.setUint32(0, CENTRAL, true);\n head.setUint16(4, VERSION, true);\n head.setUint16(6, VERSION, true);\n head.setUint16(8, UTF8_NAMES, true);\n head.setUint16(10, method, true);\n head.setUint16(12, time, true);\n head.setUint16(14, day, true);\n head.setUint32(16, crc, true);\n head.setUint32(20, stored.length, true);\n head.setUint32(24, entry.data.length, true);\n head.setUint16(28, name.length, true);\n head.setUint32(42, offset, true);\n\n body.push(new Uint8Array(local.buffer), name, stored);\n central.push(new Uint8Array(head.buffer), name);\n offset += 30 + name.length + stored.length;\n }\n\n const directory = concat(central);\n if (offset + directory.length > MAX32) throw new ZipError('tooLarge');\n const end = new DataView(new ArrayBuffer(22));\n end.setUint32(0, END, true);\n end.setUint16(8, entries.length, true);\n end.setUint16(10, entries.length, true);\n end.setUint32(12, directory.length, true);\n end.setUint32(16, offset, true);\n return concat([...body, directory, new Uint8Array(end.buffer)]);\n}\n\n//--------------------------------------------------\n// reading / чтение\n\n/**\n * Whether the bytes start like a ZIP (a file or an empty archive). A quick check to tell an archive from a text file\n * before opening it; `readZip` does the real checking.\n * Начинаются ли байты как ZIP (файл или пустой архив). Быстрая проверка, чтобы отличить архив от текстового файла\n * до открытия; настоящую проверку делает `readZip`.\n */\nexport function looksLikeZip(data: Uint8Array): boolean {\n return data.length >= 4 && data[0] === 0x50 && data[1] === 0x4b && ((data[2] === 3 && data[3] === 4) || (data[2] === 5 && data[3] === 6));\n}\n\nfunction decodeName(bytes: Uint8Array, utf8: boolean): string {\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch {\n if (utf8) throw new ZipError('corrupt', 'name');\n return String.fromCharCode(...bytes); // an old tool without the UTF-8 flag: Latin-1 at least keeps the letters apart\n }\n}\n\n/**\n * Reads a ZIP archive into its files (folders are skipped). Throws `ZipError`. Never writes anywhere: the names are\n * checked (no `..`, no absolute paths, no backslashes) and the sizes are limited (`limits`), CRC is verified.\n * Reads the central directory, so archives written by any tool open, including those with sizes after the data.\n * Читает ZIP-архив в файлы (папки пропускаются). Бросает `ZipError`. Никуда ничего не пишет: имена проверяются\n * (без `..`, абсолютных путей и обратных косых), размеры ограничены (`limits`), CRC сверяется.\n * Читает центральный каталог, поэтому открываются архивы любой программы, в том числе с размерами после данных.\n */\nexport async function readZip(data: Uint8Array, limits: ZipReadLimits = {}): Promise<ZipEntry[]> {\n const { maxEntries, maxEntryBytes, maxTotalBytes } = { ...ZIP_LIMITS, ...limits };\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n // the end record: the last 22 bytes, or before a comment of up to 65 535 bytes\n let end = -1;\n for (let i = data.length - 22; i >= Math.max(0, data.length - 22 - MAX16); i--) {\n if (view.getUint32(i, true) === END && i + 22 + view.getUint16(i + 20, true) === data.length) {\n end = i;\n break;\n }\n }\n if (end < 0) throw new ZipError('notZip');\n\n const count = view.getUint16(end + 10, true);\n const directorySize = view.getUint32(end + 12, true);\n const directoryOffset = view.getUint32(end + 16, true);\n if (view.getUint16(end + 4, true) !== 0 || view.getUint16(end + 6, true) !== 0 || view.getUint16(end + 8, true) !== count) throw new ZipError('unsupported', 'several disks');\n if (count === MAX16 || directorySize === MAX32 || directoryOffset === MAX32) throw new ZipError('unsupported', 'ZIP64');\n if (count > maxEntries) throw new ZipError('tooMany', String(count));\n if (directoryOffset + directorySize > end) throw new ZipError('corrupt', 'directory');\n\n const result: ZipEntry[] = [];\n const seen = new Set<string>();\n let at = directoryOffset;\n let declaredTotal = 0;\n let total = 0;\n\n for (let n = 0; n < count; n++) {\n if (at + 46 > end || view.getUint32(at, true) !== CENTRAL) throw new ZipError('corrupt', 'directory');\n const flags = view.getUint16(at + 8, true);\n const method = view.getUint16(at + 10, true);\n const crc = view.getUint32(at + 16, true);\n const packedSize = view.getUint32(at + 20, true);\n const size = view.getUint32(at + 24, true);\n const nameLength = view.getUint16(at + 28, true);\n const extraLength = view.getUint16(at + 30, true);\n const commentLength = view.getUint16(at + 32, true);\n const localOffset = view.getUint32(at + 42, true);\n if (at + 46 + nameLength + extraLength + commentLength > end) throw new ZipError('corrupt', 'directory');\n const name = decodeName(data.subarray(at + 46, at + 46 + nameLength), (flags & UTF8_NAMES) !== 0);\n at += 46 + nameLength + extraLength + commentLength;\n\n if (name.endsWith('/')) {\n assertName(name.slice(0, -1));\n continue; // a folder: folders follow from the paths / папка: папки следуют из путей\n }\n assertName(name);\n if (seen.has(name)) throw new ZipError('duplicate', name);\n seen.add(name);\n\n if (flags & ENCRYPTED) throw new ZipError('unsupported', 'encrypted');\n if (method !== STORED && method !== DEFLATED) throw new ZipError('unsupported', `method ${method}`);\n if (packedSize === MAX32 || size === MAX32 || localOffset === MAX32) throw new ZipError('unsupported', 'ZIP64');\n declaredTotal += size;\n if (size > maxEntryBytes || declaredTotal > maxTotalBytes) throw new ZipError('tooLarge', name);\n\n if (localOffset + 30 > directoryOffset || view.getUint32(localOffset, true) !== LOCAL) throw new ZipError('corrupt', name);\n const start = localOffset + 30 + view.getUint16(localOffset + 26, true) + view.getUint16(localOffset + 28, true);\n if (start + packedSize > directoryOffset) throw new ZipError('corrupt', name);\n const packed = data.subarray(start, start + packedSize);\n\n let bytes: Uint8Array;\n if (method === STORED) {\n if (packedSize !== size) throw new ZipError('corrupt', name);\n bytes = packed.slice();\n } else {\n try {\n bytes = await through(packed, new DecompressionStream('deflate-raw'), size);\n } catch {\n throw new ZipError('corrupt', name); // bad deflate data, or more than the declared size / плохие данные или больше заявленного размера\n }\n }\n if (bytes.length !== size || crc32(bytes) !== crc) throw new ZipError('corrupt', name);\n total += bytes.length;\n if (total > maxTotalBytes) throw new ZipError('tooLarge', name);\n result.push({ name, data: bytes });\n }\n return result;\n}\n"],"mappings":";;;;;AAyBA,IAAa,WAAb,cAA8B,MAAM;CAEnB;CACA;CAFb,YACI,MACA,QACF;EACE,MAAM,WAAW,KAAA,IAAY,OAAO,GAAG,KAAK,IAAI,QAAQ;EAH/C,KAAA,OAAA;EACA,KAAA,SAAA;EAGT,KAAK,OAAO;CAChB;AACJ;AAiBA,IAAa,aAAsC;CAAE,YAAY;CAAQ,eAAe;CAAmB,eAAe;AAAmB;AAc7I,IAAM,QAAQ;AACd,IAAM,UAAU;AAChB,IAAM,MAAM;AACZ,IAAM,UAAU;AAChB,IAAM,aAAa;AACnB,IAAM,YAAY;AAClB,IAAM,SAAS;AACf,IAAM,WAAW;AACjB,IAAM,QAAQ;AACd,IAAM,QAAQ;AACd,IAAM,qBAAqB;AAE3B,IAAM,UAAU,IAAI,YAAY;;;;;;;AAQhC,SAAS,WAAW,MAAoB;CAOpC,IALI,SAAS,MACT,KAAK,WAAW,GAAG,KACnB,KAAK,SAAS,IAAI,KAClB,kBAAkB,KAAK,IAAI,KAC3B,KAAK,MAAM,GAAG,CAAC,CAAC,MAAM,SAAS,SAAS,MAAM,SAAS,OAAO,SAAS,IAAI,GACnE,MAAM,IAAI,SAAS,cAAc,KAAK,UAAU,IAAI,CAAC;AACrE;AAEA,IAAM,WAAW,MAAM,KAAK,EAAE,QAAQ,IAAI,IAAI,GAAG,MAAM;CACnD,IAAI,IAAI;CACR,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK,IAAI,IAAI,IAAI,aAAc,MAAM,IAAK,MAAM;CACvE,OAAO,MAAM;AACjB,CAAC;AAED,SAAS,MAAM,MAA0B;CACrC,IAAI,IAAI;CACR,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,IAAI,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AI;EAEb,IAAI,QAAQ,WAAW,MAAM,IAAI,SAAS,eAAe,WAAW;EACpE,IAAI,WAAW,UAAU,WAAW,UAAU,MAAM,IAAI,SAAS,eAAe,UAAU,QAAQ;EAClG,IAAI,eAAe,SAAS,SAAS,SAAS,gBAAgB,OAAO,MAAM,IAAI,SAAS,eAAe,OAAO;EAC9G,iBAAiB;EACjB,IAAI,OAAO,iBAAiB,gBAAgB,eAAe,MAAM,IAAI,SAAS,YAAY,IAAI;EAE9F,IAAI,cAAc,KAAK,mBAAmB,KAAK,UAAU,aAAa,IAAI,MAAM,OAAO,MAAM,IAAI,SAAS,WAAW,IAAI;EACzH,MAAM,QAAQ,cAAc,KAAK,KAAK,UAAU,cAAc,IAAI,IAAI,IAAI,KAAK,UAAU,cAAc,IAAI,IAAI;EAC/G,IAAI,QAAQ,aAAa,iBAAiB,MAAM,IAAI,SAAS,WAAW,IAAI;EAC5E,MAAM,SAAS,KAAK,SAAS,OAAO,QAAQ,UAAU;EAEtD,IAAI;EACJ,IAAI,WAAW,QAAQ;GACnB,IAAI,eAAe,MAAM,MAAM,IAAI,SAAS,WAAW,IAAI;GAC3D,QAAQ,OAAO,MAAM;EACzB,OACI,IAAI;GACA,QAAQ,MAAM,QAAQ,QAAQ,IAAI,oBAAoB,aAAa,GAAG,IAAI;EAC9E,QAAQ;GACJ,MAAM,IAAI,SAAS,WAAW,IAAI;EACtC;EAEJ,IAAI,MAAM,WAAW,QAAQ,MAAM,KAAK,MAAM,KAAK,MAAM,IAAI,SAAS,WAAW,IAAI;EACrF,SAAS,MAAM;EACf,IAAI,QAAQ,eAAe,MAAM,IAAI,SAAS,YAAY,IAAI;EAC9D,OAAO,KAAK;GAAE;GAAM,MAAM;EAAM,CAAC;CACrC;CACA,OAAO;AACX"}
1
+ {"version":3,"file":"zip.js","names":[],"sources":["../src/zip.ts"],"sourcesContent":["// ZIP without libraries: the browser's CompressionStream does the deflate. No DOM, no Vue.\n// ZIP без библиотек: deflate делает CompressionStream браузера. Без DOM и Vue.\n\n/**\n * A file in an archive: the path with `/` as the separator (`assets/hero.png`) and its bytes.\n * Файл в архиве: путь с разделителем `/` (`assets/hero.png`) и его байты.\n */\nexport interface ZipEntry {\n name: string;\n data: Uint8Array;\n}\n\nexport type ZipErrorCode =\n | 'notZip' // not an archive at all / это вообще не архив\n | 'unsupported' // encrypted, ZIP64, several disks, an unknown method / шифрование, ZIP64, несколько дисков, незнакомый метод\n | 'corrupt' // damaged: bounds, size, CRC, a failed inflate / повреждён: границы, размер, CRC, сбой распаковки\n | 'unsafeName' // a path that would leave the folder it is unpacked into / путь, который выбрался бы из папки распаковки\n | 'duplicate' // the same name twice / одно имя дважды\n | 'tooMany' // more files than allowed / файлов больше, чем разрешено\n | 'tooLarge'; // a file or the whole archive unpacks bigger than allowed / файл или весь архив распакуется больше, чем разрешено\n\n/**\n * Why an archive was refused or could not be written. The interface builds the user text from `code`.\n * Почему архив отклонён или не записан. Текст для пользователя собирает интерфейс по `code`.\n */\nexport class ZipError extends Error {\n constructor(\n readonly code: ZipErrorCode,\n readonly detail?: string,\n ) {\n super(detail === undefined ? code : `${code}: ${detail}`);\n this.name = 'ZipError';\n }\n}\n\n/**\n * Limits of reading. An archive comes from outside, and a few KB can unpack into gigabytes, so the sizes are checked\n * twice: the declared ones before unpacking and the real ones while unpacking.\n * Пределы чтения. Архив приходит извне, а несколько КБ могут распаковаться в гигабайты, поэтому размеры проверяются\n * дважды: объявленные до распаковки и настоящие во время неё.\n */\nexport interface ZipReadLimits {\n /** Files in the archive. Default 10 000. / Файлов в архиве. По умолчанию 10 000. */\n maxEntries?: number;\n /** Bytes of one unpacked file. Default 512 MiB. / Байт в одном распакованном файле. По умолчанию 512 МиБ. */\n maxEntryBytes?: number;\n /** Bytes of all unpacked files together. Default 1 GiB. / Байт во всех файлах вместе. По умолчанию 1 ГиБ. */\n maxTotalBytes?: number;\n}\n\nexport const ZIP_LIMITS: Required<ZipReadLimits> = { maxEntries: 10_000, maxEntryBytes: 512 * 1024 * 1024, maxTotalBytes: 1024 * 1024 * 1024 };\n\nexport interface ZipWriteOptions {\n /** Modification time written for every file. Now by default. / Время изменения у всех файлов. По умолчанию сейчас. */\n date?: Date;\n /**\n * `auto` (default): a file is deflated unless it is already compressed (PNG, JPEG, WebP, audio, video, archives) and\n * only when that makes it smaller; `store`: everything as it is.\n * `auto` (по умолчанию): файл сжимается, если он ещё не сжат (PNG, JPEG, WebP, звук, видео, архивы) и только когда\n * от этого становится меньше; `store`: всё как есть.\n */\n compress?: 'auto' | 'store';\n}\n\nconst LOCAL = 0x04034b50;\nconst CENTRAL = 0x02014b50;\nconst END = 0x06054b50;\nconst VERSION = 20; // 2.0: the lowest that every unzip tool understands / 2.0: ниже все распаковщики понимают\nconst UTF8_NAMES = 0x0800;\nconst ENCRYPTED = 0x0001 | 0x0040;\nconst STORED = 0;\nconst DEFLATED = 8;\nconst MAX32 = 0xffffffff;\nconst MAX16 = 0xffff;\nconst ALREADY_COMPRESSED = /\\.(png|jpe?g|gif|webp|avif|zip|gz|bz2|7z|rar|mp3|ogg|opus|m4a|aac|mp4|webm|mov|woff2?)$/i;\n\nconst encoder = new TextEncoder();\n\n/**\n * A path that would climb out of the folder it is unpacked into (`../x`, `/etc/x`, `a\\..\\x`) is how a ZIP overwrites\n * files it should not touch, so such names never get in or out.\n * Путь, который выбрался бы из папки распаковки (`../x`, `/etc/x`, `a\\..\\x`), — это способ ZIP затереть то, что ему\n * трогать нельзя, поэтому такие имена ни входят, ни выходят.\n */\nfunction assertName(name: string): void {\n const unsafe =\n name === '' ||\n name.includes('\\\\') ||\n /[\\x00-\\x1f\\x7f]/.test(name) ||\n name.split('/').some((part) => part === '' || part === '.' || part === '..');\n if (unsafe) throw new ZipError('unsafeName', JSON.stringify(name));\n}\n\nconst crcTable = Array.from({ length: 256 }, (_, n) => {\n let c = n;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n return c >>> 0;\n});\n\nfunction crc32(data: Uint8Array): number {\n let c = 0xffffffff;\n for (let i = 0; i < data.length; i++) c = crcTable[(c ^ data[i]!) & 0xff]! ^ (c >>> 8);\n return (c ^ 0xffffffff) >>> 0;\n}\n\n/** Local time as DOS date and time (2 s resolution, from 1980). / Местное время как DOS-дата и время (шаг 2 с, с 1980). */\nfunction dosTime(date: Date): { time: number; day: number } {\n const year = Math.max(1980, date.getFullYear());\n return {\n time: (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1),\n day: ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate(),\n };\n}\n\n/** Passes the bytes through a (de)compression stream. `max` stops a result that grows past what is expected. */\nasync function through(data: Uint8Array, transform: CompressionStream | DecompressionStream, max = Infinity): Promise<Uint8Array> {\n const source = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(data);\n controller.close();\n },\n });\n const reader = source.pipeThrough(transform as unknown as ReadableWritablePair<Uint8Array, Uint8Array>).getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > max) {\n await reader.cancel();\n throw new ZipError('corrupt', 'size');\n }\n chunks.push(value);\n }\n return concat(chunks, total);\n}\n\nfunction concat(chunks: readonly Uint8Array[], total = chunks.reduce((n, c) => n + c.length, 0)): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(total);\n let at = 0;\n for (const c of chunks) {\n out.set(c, at);\n at += c.length;\n }\n return out;\n}\n\n//--------------------------------------------------\n// writing / запись\n\n/**\n * Writes a ZIP archive. Names are UTF-8; no ZIP64, so up to 65 535 files and 4 GiB. Files already compressed are stored\n * as they are (see `compress`), the rest are deflated.\n * Пишет ZIP-архив. Имена в UTF-8; без ZIP64: до 65 535 файлов и 4 ГиБ. Уже сжатые файлы кладутся как есть\n * (см. `compress`), остальные сжимаются.\n */\nexport async function createZip(entries: readonly ZipEntry[], options: ZipWriteOptions = {}): Promise<Uint8Array<ArrayBuffer>> {\n if (entries.length > MAX16) throw new ZipError('tooMany', `${entries.length} files do not fit into a ZIP without ZIP64`);\n const { time, day } = dosTime(options.date ?? new Date());\n const seen = new Set<string>();\n const body: Uint8Array[] = [];\n const central: Uint8Array[] = [];\n let offset = 0;\n\n for (const entry of entries) {\n assertName(entry.name);\n if (seen.has(entry.name)) throw new ZipError('duplicate', entry.name);\n seen.add(entry.name);\n\n const name = encoder.encode(entry.name);\n const crc = crc32(entry.data);\n let method = STORED;\n let stored = entry.data;\n if (options.compress !== 'store' && !ALREADY_COMPRESSED.test(entry.name)) {\n const packed = await through(entry.data, new CompressionStream('deflate-raw'));\n if (packed.length < entry.data.length) {\n method = DEFLATED;\n stored = packed;\n }\n }\n if (entry.data.length > MAX32 || offset > MAX32) throw new ZipError('tooLarge', entry.name);\n\n const local = new DataView(new ArrayBuffer(30));\n local.setUint32(0, LOCAL, true);\n local.setUint16(4, VERSION, true);\n local.setUint16(6, UTF8_NAMES, true);\n local.setUint16(8, method, true);\n local.setUint16(10, time, true);\n local.setUint16(12, day, true);\n local.setUint32(14, crc, true);\n local.setUint32(18, stored.length, true);\n local.setUint32(22, entry.data.length, true);\n local.setUint16(26, name.length, true);\n local.setUint16(28, 0, true);\n\n const head = new DataView(new ArrayBuffer(46));\n head.setUint32(0, CENTRAL, true);\n head.setUint16(4, VERSION, true);\n head.setUint16(6, VERSION, true);\n head.setUint16(8, UTF8_NAMES, true);\n head.setUint16(10, method, true);\n head.setUint16(12, time, true);\n head.setUint16(14, day, true);\n head.setUint32(16, crc, true);\n head.setUint32(20, stored.length, true);\n head.setUint32(24, entry.data.length, true);\n head.setUint16(28, name.length, true);\n head.setUint32(42, offset, true);\n\n body.push(new Uint8Array(local.buffer), name, stored);\n central.push(new Uint8Array(head.buffer), name);\n offset += 30 + name.length + stored.length;\n }\n\n const directory = concat(central);\n if (offset + directory.length > MAX32) throw new ZipError('tooLarge');\n const end = new DataView(new ArrayBuffer(22));\n end.setUint32(0, END, true);\n end.setUint16(8, entries.length, true);\n end.setUint16(10, entries.length, true);\n end.setUint32(12, directory.length, true);\n end.setUint32(16, offset, true);\n return concat([...body, directory, new Uint8Array(end.buffer)]);\n}\n\n//--------------------------------------------------\n// reading / чтение\n\n/**\n * Whether the bytes start like a ZIP (a file or an empty archive). A quick check to tell an archive from a text file\n * before opening it; `readZip` does the real checking.\n * Начинаются ли байты как ZIP (файл или пустой архив). Быстрая проверка, чтобы отличить архив от текстового файла\n * до открытия; настоящую проверку делает `readZip`.\n */\nexport function looksLikeZip(data: Uint8Array): boolean {\n return data.length >= 4 && data[0] === 0x50 && data[1] === 0x4b && ((data[2] === 3 && data[3] === 4) || (data[2] === 5 && data[3] === 6));\n}\n\nfunction decodeName(bytes: Uint8Array, utf8: boolean): string {\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch {\n if (utf8) throw new ZipError('corrupt', 'name');\n return String.fromCharCode(...bytes); // an old tool without the UTF-8 flag: Latin-1 at least keeps the letters apart\n }\n}\n\n/**\n * Reads a ZIP archive into its files (folders are skipped). Throws `ZipError`. Never writes anywhere: the names are\n * checked (no `..`, no absolute paths, no backslashes) and the sizes are limited (`limits`), CRC is verified.\n * Reads the central directory, so archives written by any tool open, including those with sizes after the data.\n * Читает ZIP-архив в файлы (папки пропускаются). Бросает `ZipError`. Никуда ничего не пишет: имена проверяются\n * (без `..`, абсолютных путей и обратных косых), размеры ограничены (`limits`), CRC сверяется.\n * Читает центральный каталог, поэтому открываются архивы любой программы, в том числе с размерами после данных.\n */\nexport async function readZip(data: Uint8Array, limits: ZipReadLimits = {}): Promise<ZipEntry[]> {\n const { maxEntries, maxEntryBytes, maxTotalBytes } = { ...ZIP_LIMITS, ...limits };\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n // the end record: the last 22 bytes, or before a comment of up to 65 535 bytes\n let end = -1;\n for (let i = data.length - 22; i >= Math.max(0, data.length - 22 - MAX16); i--) {\n if (view.getUint32(i, true) === END && i + 22 + view.getUint16(i + 20, true) === data.length) {\n end = i;\n break;\n }\n }\n if (end < 0) throw new ZipError('notZip');\n\n const count = view.getUint16(end + 10, true);\n const directorySize = view.getUint32(end + 12, true);\n const directoryOffset = view.getUint32(end + 16, true);\n if (view.getUint16(end + 4, true) !== 0 || view.getUint16(end + 6, true) !== 0 || view.getUint16(end + 8, true) !== count) throw new ZipError('unsupported', 'several disks');\n if (count === MAX16 || directorySize === MAX32 || directoryOffset === MAX32) throw new ZipError('unsupported', 'ZIP64');\n if (count > maxEntries) throw new ZipError('tooMany', String(count));\n if (directoryOffset + directorySize > end) throw new ZipError('corrupt', 'directory');\n\n const result: ZipEntry[] = [];\n const seen = new Set<string>();\n let at = directoryOffset;\n let declaredTotal = 0;\n\n for (let n = 0; n < count; n++) {\n if (at + 46 > end || view.getUint32(at, true) !== CENTRAL) throw new ZipError('corrupt', 'directory');\n const flags = view.getUint16(at + 8, true);\n const method = view.getUint16(at + 10, true);\n const crc = view.getUint32(at + 16, true);\n const packedSize = view.getUint32(at + 20, true);\n const size = view.getUint32(at + 24, true);\n const nameLength = view.getUint16(at + 28, true);\n const extraLength = view.getUint16(at + 30, true);\n const commentLength = view.getUint16(at + 32, true);\n const localOffset = view.getUint32(at + 42, true);\n if (at + 46 + nameLength + extraLength + commentLength > end) throw new ZipError('corrupt', 'directory');\n const name = decodeName(data.subarray(at + 46, at + 46 + nameLength), (flags & UTF8_NAMES) !== 0);\n at += 46 + nameLength + extraLength + commentLength;\n\n if (name.endsWith('/')) {\n assertName(name.slice(0, -1));\n continue; // a folder: folders follow from the paths / папка: папки следуют из путей\n }\n assertName(name);\n if (seen.has(name)) throw new ZipError('duplicate', name);\n seen.add(name);\n\n if (flags & ENCRYPTED) throw new ZipError('unsupported', 'encrypted');\n if (method !== STORED && method !== DEFLATED) throw new ZipError('unsupported', `method ${method}`);\n if (packedSize === MAX32 || size === MAX32 || localOffset === MAX32) throw new ZipError('unsupported', 'ZIP64');\n declaredTotal += size;\n if (size > maxEntryBytes || declaredTotal > maxTotalBytes) throw new ZipError('tooLarge', name);\n\n if (localOffset + 30 > directoryOffset || view.getUint32(localOffset, true) !== LOCAL) throw new ZipError('corrupt', name);\n const start = localOffset + 30 + view.getUint16(localOffset + 26, true) + view.getUint16(localOffset + 28, true);\n if (start + packedSize > directoryOffset) throw new ZipError('corrupt', name);\n const packed = data.subarray(start, start + packedSize);\n\n let bytes: Uint8Array;\n if (method === STORED) {\n bytes = packed.slice();\n } else {\n try {\n bytes = await through(packed, new DecompressionStream('deflate-raw'), size);\n } catch {\n throw new ZipError('corrupt', name); // bad deflate data, or more than the declared size / плохие данные или больше заявленного размера\n }\n }\n if (bytes.length !== size || crc32(bytes) !== crc) throw new ZipError('corrupt', name);\n result.push({ name, data: bytes });\n }\n return result;\n}\n"],"mappings":";;;;;AAyBA,IAAa,WAAb,cAA8B,MAAM;CAEnB;CACA;CAFb,YACI,MACA,QACF;EACE,MAAM,WAAW,KAAA,IAAY,OAAO,GAAG,KAAK,IAAI,QAAQ;EAH/C,KAAA,OAAA;EACA,KAAA,SAAA;EAGT,KAAK,OAAO;CAChB;AACJ;AAiBA,IAAa,aAAsC;CAAE,YAAY;CAAQ,eAAe;CAAmB,eAAe;AAAmB;AAc7I,IAAM,QAAQ;AACd,IAAM,UAAU;AAChB,IAAM,MAAM;AACZ,IAAM,UAAU;AAChB,IAAM,aAAa;AACnB,IAAM,YAAY;AAClB,IAAM,SAAS;AACf,IAAM,WAAW;AACjB,IAAM,QAAQ;AACd,IAAM,QAAQ;AACd,IAAM,qBAAqB;AAE3B,IAAM,UAAU,IAAI,YAAY;;;;;;;AAQhC,SAAS,WAAW,MAAoB;CAMpC,IAJI,SAAS,MACT,KAAK,SAAS,IAAI,KAClB,kBAAkB,KAAK,IAAI,KAC3B,KAAK,MAAM,GAAG,CAAC,CAAC,MAAM,SAAS,SAAS,MAAM,SAAS,OAAO,SAAS,IAAI,GACnE,MAAM,IAAI,SAAS,cAAc,KAAK,UAAU,IAAI,CAAC;AACr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HANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@1337exp/taoux",
3
- "version": "0.12.0",
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 |