@1337exp/taoux 0.11.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +3 -2
- package/README.ru.md +3 -2
- package/dist/file.d.ts +19 -0
- package/dist/file.js +29 -1
- package/dist/file.js.map +1 -1
- package/dist/session.d.ts +2 -0
- package/dist/session.js +18 -0
- package/dist/session.js.map +1 -1
- package/dist/zip.d.ts +67 -0
- package/dist/zip.js +257 -0
- package/dist/zip.js.map +1 -0
- package/package.json +5 -1
- package/skills/taoux/SKILL.md +3 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.12.1
|
|
4
|
+
|
|
5
|
+
Nothing to migrate; the behaviour of `zip` does not change.
|
|
6
|
+
|
|
7
|
+
- **`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.
|
|
8
|
+
|
|
9
|
+
## 0.12.0
|
|
10
|
+
|
|
11
|
+
Nothing to migrate: a new module and new optional members.
|
|
12
|
+
|
|
13
|
+
- **New module `zip`: ZIP without libraries.** `createZip(entries, { date?, compress? })` writes an archive and `readZip(bytes, limits?)` reads one; both are async because the deflate is the browser's `CompressionStream` / `DecompressionStream` (`deflate-raw`). A project that is a folder of files (an editor with textures and documents) goes in one file this way, as a docx does. Writing: UTF-8 names; a file is deflated unless its name says it is already compressed (PNG, JPEG, WebP, audio, video, archives) and only when that makes it smaller (`compress: 'store'` keeps everything as it is); no ZIP64 (up to 65 535 files and 4 GiB). Reading goes by the central directory, so archives of any tool open, including those with sizes after the data; folders are skipped, names without the UTF-8 flag are read as Latin-1. An archive comes from outside, so reading is defensive: a name that would leave the folder it is unpacked into (`../x`, `/x`, a backslash, a control character, an empty part) is refused, the same name twice is refused, the CRC and the sizes are checked, and the limits (`maxEntries` 10 000, `maxEntryBytes` 512 MiB, `maxTotalBytes` 1 GiB, all overridable) are applied to the declared sizes before unpacking and to the real ones while unpacking, so a few KB that unpack into gigabytes are stopped. Every refusal is a `ZipError` with a `code` (`notZip`, `unsupported`, `corrupt`, `unsafeName`, `duplicate`, `tooMany`, `tooLarge`) for the interface to turn into text; encryption, ZIP64 and several disks are `unsupported`. `looksLikeZip(bytes)` tells an archive from a text file before opening it. Tested against an archive made by Python's `zipfile`.
|
|
14
|
+
- **`file`: `readBytesFile(file, limit?)`.** Reads a picked file as bytes (an archive, an image) with a size limit (`MAX_BINARY_FILE_BYTES`, 512 MiB), as `readTextFile` does for text: too large is refused before reading, a failed read is a result.
|
|
15
|
+
- **`session`: `dirty` and `markSaved()`.** A ref that tells whether the document changed since it was opened or last saved (an edit, undo, redo, a replacement by `load`); `markSaved()` clears it after the app wrote the document somewhere, and `load` with `resetHistory` starts clean. For an "unsaved" mark and a "leave the page?" guard. Undoing back to the saved state does not clear it (it is a flag, not a position in the history).
|
|
16
|
+
|
|
3
17
|
## 0.11.0
|
|
4
18
|
|
|
5
19
|
Nothing to migrate: one optional prop; without it the editor writes the same numbers as before.
|
package/README.md
CHANGED
|
@@ -86,7 +86,8 @@ import { History } from '@1337exp/taoux/history';
|
|
|
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 |
|
|
89
|
-
| `file` | download bytes or text as a file (`downloadBlob`, `downloadText`, any `mime`), read a picked file as text with a size limit | DOM |
|
|
89
|
+
| `file` | download bytes or text as a file (`downloadBlob`, `downloadText`, any `mime`), read a picked file as text or as bytes with a size limit | DOM |
|
|
90
|
+
| `zip` | ZIP without libraries: `createZip(entries)` (deflates what is not already compressed) and `readZip(bytes, limits?)` (central directory, CRC, size limits that hold against zip bombs, names that leave the folder refused; `ZipError` with a `code`), `looksLikeZip` | nothing (needs `CompressionStream`) |
|
|
90
91
|
| `snap` | soft snapping to a grid with a threshold that follows the camera zoom | nothing |
|
|
91
92
|
| `wheel` | wheel/trackpad → pan or zoom (like Figma) | nothing |
|
|
92
93
|
| `guides` | smart guides for dragging (as in Figma): `snapToGuides(rect, others, threshold)` compares edges and centres with the other rectangles and returns the shift that puts them together and the lines to draw | nothing |
|
|
@@ -98,7 +99,7 @@ import { History } from '@1337exp/taoux/history';
|
|
|
98
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 |
|
|
99
100
|
| `num` | small numeric helpers: `clamp`, `roundTo`, `snapTo`, `niceStep`, `ticks` (shared by the curve, gradient and playback modules) | nothing |
|
|
100
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) |
|
|
101
|
-
| `session` | document lifecycle: history, autosave, files, restore, notices
|
|
102
|
+
| `session` | document lifecycle: history, autosave, files, restore, notices, `dirty` / `markSaved()`; a canvas camera is optional (`countItems`) | vue (peer) |
|
|
102
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`) |
|
|
103
104
|
| `palette` | search and groups of nodes for a palette | nothing |
|
|
104
105
|
| `links` (Vue) | links layer: SVG from ready geometry, `--tx-link-*` | vue (peer) |
|
package/README.ru.md
CHANGED
|
@@ -86,9 +86,10 @@ import { History } from '@1337exp/taoux/history';
|
|
|
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` (ключ изменила другая вкладка) | нет |
|
|
89
|
-
| `file` | скачивание байтов или текста как файла (`downloadBlob`, `downloadText`, любой `mime`), чтение выбранного файла как текста с лимитом размера | DOM |
|
|
89
|
+
| `file` | скачивание байтов или текста как файла (`downloadBlob`, `downloadText`, любой `mime`), чтение выбранного файла как текста или как байтов с лимитом размера | DOM |
|
|
90
90
|
| `snap` | мягкая привязка к сетке с порогом по масштабу камеры | нет |
|
|
91
91
|
| `wheel` | колесо/тачпад → pan или zoom (как в Figma) | нет |
|
|
92
|
+
| `zip` | ZIP без библиотек: `createZip(entries)` (сжимает то, что ещё не сжато) и `readZip(bytes, limits?)` (центральный каталог, CRC, пределы размера против зип-бомб, имена, выходящие из папки, отклоняются; `ZipError` с `code`), `looksLikeZip` | нет (нужен `CompressionStream`) |
|
|
92
93
|
| `guides` | умные направляющие при перетаскивании (как в Figma): `snapToGuides(rect, others, threshold)` сравнивает края и центры с другими прямоугольниками и возвращает сдвиг, который их совмещает, и линии для отрисовки | нет |
|
|
93
94
|
| `edgescroll` | скорость автопрокрутки у края и готовый цикл `createEdgeScroller` (холст, редакторы кривых и любое перетаскивание) | нет |
|
|
94
95
|
| `gestures` | сенсорные жесты: тап, двойной тап, долгое нажатие, щипок, свайп (`SwipeTracker` + `settleOpen` для строки, которая отъезжает); `listenFocusLoss` завершает удерживаемый жест, когда окно теряет фокус | нет |
|
|
@@ -98,7 +99,7 @@ import { History } from '@1337exp/taoux/history';
|
|
|
98
99
|
| `ease` | функции движения между точками кривой: 8 семейств × in / out / in-out, `linear`, `step`, кубический Безье; `easeValue`, `isEase` (редактор рисует ими, рантайм считает ими же) | нет |
|
|
99
100
|
| `num` | мелкая числовая математика: `clamp`, `roundTo`, `snapTo`, `niceStep`, `ticks` (общая для кривой, градиента и воспроизведения) | нет |
|
|
100
101
|
| `sortable` (Vue) | перестановка списка за ручку и с клавиатуры: `useSortable(listRef, { onMove })`, `data-sortable-item` / `data-sortable-handle`; остальные расступаются, у края список прокручивается, Esc возвращает, живой регион сообщает скринридеру; `moveItem` | vue (peer) |
|
|
101
|
-
| `session` | жизненный цикл документа: история, автосохранение, файлы, восстановление,
|
|
102
|
+
| `session` | жизненный цикл документа: история, автосохранение, файлы, восстановление, уведомления, `dirty` / `markSaved()`; камера холста необязательна (`countItems`) | vue (peer) |
|
|
102
103
|
| `commands` | реестр команд (подпись, сочетание, `enabled`, `checked`, `run`): `toMenu(layout)` строит дерево `TaoMenuItem[]` для `TaoMenubar` / `TaoContextMenu`, `bind` слушает те же сочетания, `historyCommands` даёт Undo / Redo, которые сами становятся недоступными, `check` находит занятые браузером и повторённые сочетания | DOM (для `bind`) |
|
|
103
104
|
| `palette` | поиск и группы нод для палитры | нет |
|
|
104
105
|
| `links` (Vue) | слой связей: SVG из готовой геометрии, `--tx-link-*` | vue (peer) |
|
package/dist/file.d.ts
CHANGED
|
@@ -28,3 +28,22 @@ export type ReadTextResult = {
|
|
|
28
28
|
* Читает выбранный файл как текст. Файл больше `limit` байт отклоняется до чтения; сбой чтения — результат, а не исключение.
|
|
29
29
|
*/
|
|
30
30
|
export declare function readTextFile(file: Blob, limit?: number): Promise<ReadTextResult>;
|
|
31
|
+
/**
|
|
32
|
+
* Size above which a picked archive or image is not read into memory. Default 512 MiB.
|
|
33
|
+
* Размер, больше которого выбранный архив или картинку не читаем в память. По умолчанию 512 МиБ.
|
|
34
|
+
*/
|
|
35
|
+
export declare const MAX_BINARY_FILE_BYTES: number;
|
|
36
|
+
export type ReadBytesResult = {
|
|
37
|
+
ok: true;
|
|
38
|
+
data: Uint8Array;
|
|
39
|
+
} | {
|
|
40
|
+
ok: false;
|
|
41
|
+
error: 'tooLarge' | 'unreadable';
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Reads a picked file as bytes (an archive, an image). A file above `limit` bytes is refused before it is read; a failed
|
|
45
|
+
* read is a result, not an exception.
|
|
46
|
+
* Читает выбранный файл как байты (архив, картинка). Файл больше `limit` байт отклоняется до чтения; сбой чтения —
|
|
47
|
+
* результат, а не исключение.
|
|
48
|
+
*/
|
|
49
|
+
export declare function readBytesFile(file: Blob, limit?: number): Promise<ReadBytesResult>;
|
package/dist/file.js
CHANGED
|
@@ -50,7 +50,35 @@ async function readTextFile(file, limit = MAX_FILE_BYTES) {
|
|
|
50
50
|
};
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
|
+
/**
|
|
54
|
+
* Size above which a picked archive or image is not read into memory. Default 512 MiB.
|
|
55
|
+
* Размер, больше которого выбранный архив или картинку не читаем в память. По умолчанию 512 МиБ.
|
|
56
|
+
*/
|
|
57
|
+
var MAX_BINARY_FILE_BYTES = 536870912;
|
|
58
|
+
/**
|
|
59
|
+
* Reads a picked file as bytes (an archive, an image). A file above `limit` bytes is refused before it is read; a failed
|
|
60
|
+
* read is a result, not an exception.
|
|
61
|
+
* Читает выбранный файл как байты (архив, картинка). Файл больше `limit` байт отклоняется до чтения; сбой чтения —
|
|
62
|
+
* результат, а не исключение.
|
|
63
|
+
*/
|
|
64
|
+
async function readBytesFile(file, limit = MAX_BINARY_FILE_BYTES) {
|
|
65
|
+
if (file.size > limit) return {
|
|
66
|
+
ok: false,
|
|
67
|
+
error: "tooLarge"
|
|
68
|
+
};
|
|
69
|
+
try {
|
|
70
|
+
return {
|
|
71
|
+
ok: true,
|
|
72
|
+
data: new Uint8Array(await file.arrayBuffer())
|
|
73
|
+
};
|
|
74
|
+
} catch {
|
|
75
|
+
return {
|
|
76
|
+
ok: false,
|
|
77
|
+
error: "unreadable"
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
}
|
|
53
81
|
//#endregion
|
|
54
|
-
export { MAX_FILE_BYTES, downloadBlob, downloadText, readTextFile };
|
|
82
|
+
export { MAX_BINARY_FILE_BYTES, MAX_FILE_BYTES, downloadBlob, downloadText, readBytesFile, readTextFile };
|
|
55
83
|
|
|
56
84
|
//# sourceMappingURL=file.js.map
|
package/dist/file.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file.js","names":[],"sources":["../src/file.ts"],"sourcesContent":["/**\n * Size above which a file is not opened: a project of hundreds of nodes weighs tens of KB.\n * Размер файла, больше которого не открываем: проект на сотни нод весит десятки КБ.\n */\nexport const MAX_FILE_BYTES = 5_000_000;\n\n/**\n * Downloads bytes (or any `BlobPart`: a `Blob`, a string) as a file through a temporary link. `mime` is the type\n * of the file; without it a `Blob` keeps its own type and anything else is `application/octet-stream`.\n * Скачивание байтов (или любого `BlobPart`: `Blob`, строки) как файла через временную ссылку. `mime` — тип файла;\n * без него `Blob` сохраняет свой тип, а всё остальное идёт как `application/octet-stream`.\n */\nexport function downloadBlob(filename: string, data: BlobPart, mime?: string): void {\n const type = mime ?? (data instanceof Blob && data.type ? data.type : 'application/octet-stream');\n const url = URL.createObjectURL(new Blob([data], { type }));\n const link = document.createElement('a');\n link.href = url;\n link.download = filename;\n // Some browsers only follow a link that is in the document.\n // Часть браузеров идёт только по ссылке, которая есть в документе.\n document.body.append(link);\n link.click();\n link.remove();\n // The browser must get time to start the download, so the link is not released at once.\n // Браузер должен успеть начать скачивание, поэтому освобождаем ссылку не сразу.\n setTimeout(() => URL.revokeObjectURL(url), 1000);\n}\n\n/**\n * Downloads text as a file through a temporary link. `mime` is the type of the file (JSON by default).\n * Скачивание текста как файла через временную ссылку. `mime` — тип файла (по умолчанию JSON).\n */\nexport function downloadText(filename: string, text: string, mime = 'application/json'): void {\n downloadBlob(filename, text, mime);\n}\n\nexport type ReadTextResult = { ok: true; text: string } | { ok: false; error: 'tooLarge' | 'unreadable' };\n\n/**\n * Reads a picked file as text. A file above `limit` bytes is refused before it is read; a failed read is a result,\n * not an exception.\n * Читает выбранный файл как текст. Файл больше `limit` байт отклоняется до чтения; сбой чтения — результат, а не исключение.\n */\nexport async function readTextFile(file: Blob, limit = MAX_FILE_BYTES): Promise<ReadTextResult> {\n if (file.size > limit) return { ok: false, error: 'tooLarge' };\n try {\n return { ok: true, text: await file.text() };\n } catch {\n return { ok: false, error: 'unreadable' };\n }\n}\n"],"mappings":";;;;;AAIA,IAAa,iBAAiB;;;;;;;AAQ9B,SAAgB,aAAa,UAAkB,MAAgB,MAAqB;CAChF,MAAM,OAAO,SAAS,gBAAgB,QAAQ,KAAK,OAAO,KAAK,OAAO;CACtE,MAAM,MAAM,IAAI,gBAAgB,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,KAAK,CAAC,CAAC;CAC1D,MAAM,OAAO,SAAS,cAAc,GAAG;CACvC,KAAK,OAAO;CACZ,KAAK,WAAW;CAGhB,SAAS,KAAK,OAAO,IAAI;CACzB,KAAK,MAAM;CACX,KAAK,OAAO;CAGZ,iBAAiB,IAAI,gBAAgB,GAAG,GAAG,GAAI;AACnD;;;;;AAMA,SAAgB,aAAa,UAAkB,MAAc,OAAO,oBAA0B;CAC1F,aAAa,UAAU,MAAM,IAAI;AACrC;;;;;;AASA,eAAsB,aAAa,MAAY,QAAQ,gBAAyC;CAC5F,IAAI,KAAK,OAAO,OAAO,OAAO;EAAE,IAAI;EAAO,OAAO;CAAW;CAC7D,IAAI;EACA,OAAO;GAAE,IAAI;GAAM,MAAM,MAAM,KAAK,KAAK;EAAE;CAC/C,QAAQ;EACJ,OAAO;GAAE,IAAI;GAAO,OAAO;EAAa;CAC5C;AACJ"}
|
|
1
|
+
{"version":3,"file":"file.js","names":[],"sources":["../src/file.ts"],"sourcesContent":["/**\n * Size above which a file is not opened: a project of hundreds of nodes weighs tens of KB.\n * Размер файла, больше которого не открываем: проект на сотни нод весит десятки КБ.\n */\nexport const MAX_FILE_BYTES = 5_000_000;\n\n/**\n * Downloads bytes (or any `BlobPart`: a `Blob`, a string) as a file through a temporary link. `mime` is the type\n * of the file; without it a `Blob` keeps its own type and anything else is `application/octet-stream`.\n * Скачивание байтов (или любого `BlobPart`: `Blob`, строки) как файла через временную ссылку. `mime` — тип файла;\n * без него `Blob` сохраняет свой тип, а всё остальное идёт как `application/octet-stream`.\n */\nexport function downloadBlob(filename: string, data: BlobPart, mime?: string): void {\n const type = mime ?? (data instanceof Blob && data.type ? data.type : 'application/octet-stream');\n const url = URL.createObjectURL(new Blob([data], { type }));\n const link = document.createElement('a');\n link.href = url;\n link.download = filename;\n // Some browsers only follow a link that is in the document.\n // Часть браузеров идёт только по ссылке, которая есть в документе.\n document.body.append(link);\n link.click();\n link.remove();\n // The browser must get time to start the download, so the link is not released at once.\n // Браузер должен успеть начать скачивание, поэтому освобождаем ссылку не сразу.\n setTimeout(() => URL.revokeObjectURL(url), 1000);\n}\n\n/**\n * Downloads text as a file through a temporary link. `mime` is the type of the file (JSON by default).\n * Скачивание текста как файла через временную ссылку. `mime` — тип файла (по умолчанию JSON).\n */\nexport function downloadText(filename: string, text: string, mime = 'application/json'): void {\n downloadBlob(filename, text, mime);\n}\n\nexport type ReadTextResult = { ok: true; text: string } | { ok: false; error: 'tooLarge' | 'unreadable' };\n\n/**\n * Reads a picked file as text. A file above `limit` bytes is refused before it is read; a failed read is a result,\n * not an exception.\n * Читает выбранный файл как текст. Файл больше `limit` байт отклоняется до чтения; сбой чтения — результат, а не исключение.\n */\nexport async function readTextFile(file: Blob, limit = MAX_FILE_BYTES): Promise<ReadTextResult> {\n if (file.size > limit) return { ok: false, error: 'tooLarge' };\n try {\n return { ok: true, text: await file.text() };\n } catch {\n return { ok: false, error: 'unreadable' };\n }\n}\n\n/**\n * Size above which a picked archive or image is not read into memory. Default 512 MiB.\n * Размер, больше которого выбранный архив или картинку не читаем в память. По умолчанию 512 МиБ.\n */\nexport const MAX_BINARY_FILE_BYTES = 512 * 1024 * 1024;\n\nexport type ReadBytesResult = { ok: true; data: Uint8Array } | { ok: false; error: 'tooLarge' | 'unreadable' };\n\n/**\n * Reads a picked file as bytes (an archive, an image). A file above `limit` bytes is refused before it is read; a failed\n * read is a result, not an exception.\n * Читает выбранный файл как байты (архив, картинка). Файл больше `limit` байт отклоняется до чтения; сбой чтения —\n * результат, а не исключение.\n */\nexport async function readBytesFile(file: Blob, limit = MAX_BINARY_FILE_BYTES): Promise<ReadBytesResult> {\n if (file.size > limit) return { ok: false, error: 'tooLarge' };\n try {\n return { ok: true, data: new Uint8Array(await file.arrayBuffer()) };\n } catch {\n return { ok: false, error: 'unreadable' };\n }\n}\n"],"mappings":";;;;;AAIA,IAAa,iBAAiB;;;;;;;AAQ9B,SAAgB,aAAa,UAAkB,MAAgB,MAAqB;CAChF,MAAM,OAAO,SAAS,gBAAgB,QAAQ,KAAK,OAAO,KAAK,OAAO;CACtE,MAAM,MAAM,IAAI,gBAAgB,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,KAAK,CAAC,CAAC;CAC1D,MAAM,OAAO,SAAS,cAAc,GAAG;CACvC,KAAK,OAAO;CACZ,KAAK,WAAW;CAGhB,SAAS,KAAK,OAAO,IAAI;CACzB,KAAK,MAAM;CACX,KAAK,OAAO;CAGZ,iBAAiB,IAAI,gBAAgB,GAAG,GAAG,GAAI;AACnD;;;;;AAMA,SAAgB,aAAa,UAAkB,MAAc,OAAO,oBAA0B;CAC1F,aAAa,UAAU,MAAM,IAAI;AACrC;;;;;;AASA,eAAsB,aAAa,MAAY,QAAQ,gBAAyC;CAC5F,IAAI,KAAK,OAAO,OAAO,OAAO;EAAE,IAAI;EAAO,OAAO;CAAW;CAC7D,IAAI;EACA,OAAO;GAAE,IAAI;GAAM,MAAM,MAAM,KAAK,KAAK;EAAE;CAC/C,QAAQ;EACJ,OAAO;GAAE,IAAI;GAAO,OAAO;EAAa;CAC5C;AACJ;;;;;AAMA,IAAa,wBAAwB;;;;;;;AAUrC,eAAsB,cAAc,MAAY,QAAQ,uBAAiD;CACrG,IAAI,KAAK,OAAO,OAAO,OAAO;EAAE,IAAI;EAAO,OAAO;CAAW;CAC7D,IAAI;EACA,OAAO;GAAE,IAAI;GAAM,MAAM,IAAI,WAAW,MAAM,KAAK,YAAY,CAAC;EAAE;CACtE,QAAQ;EACJ,OAAO;GAAE,IAAI;GAAO,OAAO;EAAa;CAC5C;AACJ"}
|
package/dist/session.d.ts
CHANGED
|
@@ -126,6 +126,8 @@ export declare function createDocumentSession<D, K extends string>(options: Sess
|
|
|
126
126
|
showNotice: (kind: SessionNotice<K>["kind"], key: K, args?: NoticeArgs) => void;
|
|
127
127
|
canUndo: import("vue").Ref<boolean, boolean>;
|
|
128
128
|
canRedo: import("vue").Ref<boolean, boolean>;
|
|
129
|
+
dirty: import("vue").Ref<boolean, boolean>;
|
|
130
|
+
markSaved: () => void;
|
|
129
131
|
commit: (key?: string) => void;
|
|
130
132
|
undo: () => boolean;
|
|
131
133
|
redo: () => boolean;
|
package/dist/session.js
CHANGED
|
@@ -76,9 +76,17 @@ function createDocumentSession(options) {
|
|
|
76
76
|
const history = new History(snapshot());
|
|
77
77
|
const canUndo = ref(false);
|
|
78
78
|
const canRedo = ref(false);
|
|
79
|
+
/**
|
|
80
|
+
* The document changed since it was opened or last marked saved (an edit, undo, redo, or a replacement by `load`).
|
|
81
|
+
* Undoing back to the saved state does not clear it: only `markSaved` or a `load` with `resetHistory` does.
|
|
82
|
+
* Документ изменился с момента открытия или последнего `markSaved` (правка, undo, redo, подмена через `load`).
|
|
83
|
+
* Откат назад к сохранённому состоянию флаг не снимает: его снимает только `markSaved` или `load` с `resetHistory`.
|
|
84
|
+
*/
|
|
85
|
+
const dirty = ref(false);
|
|
79
86
|
function syncHistory() {
|
|
80
87
|
canUndo.value = history.canUndo;
|
|
81
88
|
canRedo.value = history.canRedo;
|
|
89
|
+
dirty.value = true;
|
|
82
90
|
scheduleSave();
|
|
83
91
|
}
|
|
84
92
|
/**
|
|
@@ -124,9 +132,17 @@ function createDocumentSession(options) {
|
|
|
124
132
|
if (resetHistory) {
|
|
125
133
|
history.reset(snapshot());
|
|
126
134
|
syncHistory();
|
|
135
|
+
dirty.value = false;
|
|
127
136
|
} else commit();
|
|
128
137
|
}
|
|
129
138
|
/**
|
|
139
|
+
* The app has written the document somewhere (a file, a disk): `dirty` goes off until the next change.
|
|
140
|
+
* Приложение записало документ куда-то (файл, диск): `dirty` снимается до следующей правки.
|
|
141
|
+
*/
|
|
142
|
+
const markSaved = () => {
|
|
143
|
+
dirty.value = false;
|
|
144
|
+
};
|
|
145
|
+
/**
|
|
130
146
|
* The file text for download.
|
|
131
147
|
* Текст файла для скачивания.
|
|
132
148
|
*/
|
|
@@ -177,6 +193,8 @@ function createDocumentSession(options) {
|
|
|
177
193
|
showNotice,
|
|
178
194
|
canUndo,
|
|
179
195
|
canRedo,
|
|
196
|
+
dirty,
|
|
197
|
+
markSaved,
|
|
180
198
|
commit,
|
|
181
199
|
undo,
|
|
182
200
|
redo,
|
package/dist/session.js.map
CHANGED
|
@@ -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 function syncHistory() {\n canUndo.value = history.canUndo;\n canRedo.value = history.canRedo;\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 } else {\n commit();\n }\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 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;EA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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;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 } 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 restoreS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|
3
|
+
* Файл в архиве: путь с разделителем `/` (`assets/hero.png`) и его байты.
|
|
4
|
+
*/
|
|
5
|
+
export interface ZipEntry {
|
|
6
|
+
name: string;
|
|
7
|
+
data: Uint8Array;
|
|
8
|
+
}
|
|
9
|
+
export type ZipErrorCode = 'notZip' | 'unsupported' | 'corrupt' | 'unsafeName' | 'duplicate' | 'tooMany' | 'tooLarge';
|
|
10
|
+
/**
|
|
11
|
+
* Why an archive was refused or could not be written. The interface builds the user text from `code`.
|
|
12
|
+
* Почему архив отклонён или не записан. Текст для пользователя собирает интерфейс по `code`.
|
|
13
|
+
*/
|
|
14
|
+
export declare class ZipError extends Error {
|
|
15
|
+
readonly code: ZipErrorCode;
|
|
16
|
+
readonly detail?: string | undefined;
|
|
17
|
+
constructor(code: ZipErrorCode, detail?: string | undefined);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Limits of reading. An archive comes from outside, and a few KB can unpack into gigabytes, so the sizes are checked
|
|
21
|
+
* twice: the declared ones before unpacking and the real ones while unpacking.
|
|
22
|
+
* Пределы чтения. Архив приходит извне, а несколько КБ могут распаковаться в гигабайты, поэтому размеры проверяются
|
|
23
|
+
* дважды: объявленные до распаковки и настоящие во время неё.
|
|
24
|
+
*/
|
|
25
|
+
export interface ZipReadLimits {
|
|
26
|
+
/** Files in the archive. Default 10 000. / Файлов в архиве. По умолчанию 10 000. */
|
|
27
|
+
maxEntries?: number;
|
|
28
|
+
/** Bytes of one unpacked file. Default 512 MiB. / Байт в одном распакованном файле. По умолчанию 512 МиБ. */
|
|
29
|
+
maxEntryBytes?: number;
|
|
30
|
+
/** Bytes of all unpacked files together. Default 1 GiB. / Байт во всех файлах вместе. По умолчанию 1 ГиБ. */
|
|
31
|
+
maxTotalBytes?: number;
|
|
32
|
+
}
|
|
33
|
+
export declare const ZIP_LIMITS: Required<ZipReadLimits>;
|
|
34
|
+
export interface ZipWriteOptions {
|
|
35
|
+
/** Modification time written for every file. Now by default. / Время изменения у всех файлов. По умолчанию сейчас. */
|
|
36
|
+
date?: Date;
|
|
37
|
+
/**
|
|
38
|
+
* `auto` (default): a file is deflated unless it is already compressed (PNG, JPEG, WebP, audio, video, archives) and
|
|
39
|
+
* only when that makes it smaller; `store`: everything as it is.
|
|
40
|
+
* `auto` (по умолчанию): файл сжимается, если он ещё не сжат (PNG, JPEG, WebP, звук, видео, архивы) и только когда
|
|
41
|
+
* от этого становится меньше; `store`: всё как есть.
|
|
42
|
+
*/
|
|
43
|
+
compress?: 'auto' | 'store';
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Writes a ZIP archive. Names are UTF-8; no ZIP64, so up to 65 535 files and 4 GiB. Files already compressed are stored
|
|
47
|
+
* as they are (see `compress`), the rest are deflated.
|
|
48
|
+
* Пишет ZIP-архив. Имена в UTF-8; без ZIP64: до 65 535 файлов и 4 ГиБ. Уже сжатые файлы кладутся как есть
|
|
49
|
+
* (см. `compress`), остальные сжимаются.
|
|
50
|
+
*/
|
|
51
|
+
export declare function createZip(entries: readonly ZipEntry[], options?: ZipWriteOptions): Promise<Uint8Array<ArrayBuffer>>;
|
|
52
|
+
/**
|
|
53
|
+
* Whether the bytes start like a ZIP (a file or an empty archive). A quick check to tell an archive from a text file
|
|
54
|
+
* before opening it; `readZip` does the real checking.
|
|
55
|
+
* Начинаются ли байты как ZIP (файл или пустой архив). Быстрая проверка, чтобы отличить архив от текстового файла
|
|
56
|
+
* до открытия; настоящую проверку делает `readZip`.
|
|
57
|
+
*/
|
|
58
|
+
export declare function looksLikeZip(data: Uint8Array): boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Reads a ZIP archive into its files (folders are skipped). Throws `ZipError`. Never writes anywhere: the names are
|
|
61
|
+
* checked (no `..`, no absolute paths, no backslashes) and the sizes are limited (`limits`), CRC is verified.
|
|
62
|
+
* Reads the central directory, so archives written by any tool open, including those with sizes after the data.
|
|
63
|
+
* Читает ZIP-архив в файлы (папки пропускаются). Бросает `ZipError`. Никуда ничего не пишет: имена проверяются
|
|
64
|
+
* (без `..`, абсолютных путей и обратных косых), размеры ограничены (`limits`), CRC сверяется.
|
|
65
|
+
* Читает центральный каталог, поэтому открываются архивы любой программы, в том числе с размерами после данных.
|
|
66
|
+
*/
|
|
67
|
+
export declare function readZip(data: Uint8Array, limits?: ZipReadLimits): Promise<ZipEntry[]>;
|
package/dist/zip.js
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
//#region src/zip.ts
|
|
2
|
+
/**
|
|
3
|
+
* Why an archive was refused or could not be written. The interface builds the user text from `code`.
|
|
4
|
+
* Почему архив отклонён или не записан. Текст для пользователя собирает интерфейс по `code`.
|
|
5
|
+
*/
|
|
6
|
+
var ZipError = class extends Error {
|
|
7
|
+
code;
|
|
8
|
+
detail;
|
|
9
|
+
constructor(code, detail) {
|
|
10
|
+
super(detail === void 0 ? code : `${code}: ${detail}`);
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.detail = detail;
|
|
13
|
+
this.name = "ZipError";
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
var ZIP_LIMITS = {
|
|
17
|
+
maxEntries: 1e4,
|
|
18
|
+
maxEntryBytes: 536870912,
|
|
19
|
+
maxTotalBytes: 1073741824
|
|
20
|
+
};
|
|
21
|
+
var LOCAL = 67324752;
|
|
22
|
+
var CENTRAL = 33639248;
|
|
23
|
+
var END = 101010256;
|
|
24
|
+
var VERSION = 20;
|
|
25
|
+
var UTF8_NAMES = 2048;
|
|
26
|
+
var ENCRYPTED = 65;
|
|
27
|
+
var STORED = 0;
|
|
28
|
+
var DEFLATED = 8;
|
|
29
|
+
var MAX32 = 4294967295;
|
|
30
|
+
var MAX16 = 65535;
|
|
31
|
+
var ALREADY_COMPRESSED = /\.(png|jpe?g|gif|webp|avif|zip|gz|bz2|7z|rar|mp3|ogg|opus|m4a|aac|mp4|webm|mov|woff2?)$/i;
|
|
32
|
+
var encoder = new TextEncoder();
|
|
33
|
+
/**
|
|
34
|
+
* A path that would climb out of the folder it is unpacked into (`../x`, `/etc/x`, `a\..\x`) is how a ZIP overwrites
|
|
35
|
+
* files it should not touch, so such names never get in or out.
|
|
36
|
+
* Путь, который выбрался бы из папки распаковки (`../x`, `/etc/x`, `a\..\x`), — это способ ZIP затереть то, что ему
|
|
37
|
+
* трогать нельзя, поэтому такие имена ни входят, ни выходят.
|
|
38
|
+
*/
|
|
39
|
+
function assertName(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
|
+
}
|
|
42
|
+
var crcTable = Array.from({ length: 256 }, (_, n) => {
|
|
43
|
+
let c = n;
|
|
44
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
45
|
+
return c >>> 0;
|
|
46
|
+
});
|
|
47
|
+
function crc32(data) {
|
|
48
|
+
let c = 4294967295;
|
|
49
|
+
for (let i = 0; i < data.length; i++) c = crcTable[(c ^ data[i]) & 255] ^ c >>> 8;
|
|
50
|
+
return (c ^ 4294967295) >>> 0;
|
|
51
|
+
}
|
|
52
|
+
/** Local time as DOS date and time (2 s resolution, from 1980). / Местное время как DOS-дата и время (шаг 2 с, с 1980). */
|
|
53
|
+
function dosTime(date) {
|
|
54
|
+
const year = Math.max(1980, date.getFullYear());
|
|
55
|
+
return {
|
|
56
|
+
time: date.getHours() << 11 | date.getMinutes() << 5 | date.getSeconds() >> 1,
|
|
57
|
+
day: year - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate()
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/** Passes the bytes through a (de)compression stream. `max` stops a result that grows past what is expected. */
|
|
61
|
+
async function through(data, transform, max = Infinity) {
|
|
62
|
+
const reader = new ReadableStream({ start(controller) {
|
|
63
|
+
controller.enqueue(data);
|
|
64
|
+
controller.close();
|
|
65
|
+
} }).pipeThrough(transform).getReader();
|
|
66
|
+
const chunks = [];
|
|
67
|
+
let total = 0;
|
|
68
|
+
for (;;) {
|
|
69
|
+
const { done, value } = await reader.read();
|
|
70
|
+
if (done) break;
|
|
71
|
+
total += value.length;
|
|
72
|
+
if (total > max) {
|
|
73
|
+
await reader.cancel();
|
|
74
|
+
throw new ZipError("corrupt", "size");
|
|
75
|
+
}
|
|
76
|
+
chunks.push(value);
|
|
77
|
+
}
|
|
78
|
+
return concat(chunks, total);
|
|
79
|
+
}
|
|
80
|
+
function concat(chunks, total = chunks.reduce((n, c) => n + c.length, 0)) {
|
|
81
|
+
const out = new Uint8Array(total);
|
|
82
|
+
let at = 0;
|
|
83
|
+
for (const c of chunks) {
|
|
84
|
+
out.set(c, at);
|
|
85
|
+
at += c.length;
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Writes a ZIP archive. Names are UTF-8; no ZIP64, so up to 65 535 files and 4 GiB. Files already compressed are stored
|
|
91
|
+
* as they are (see `compress`), the rest are deflated.
|
|
92
|
+
* Пишет ZIP-архив. Имена в UTF-8; без ZIP64: до 65 535 файлов и 4 ГиБ. Уже сжатые файлы кладутся как есть
|
|
93
|
+
* (см. `compress`), остальные сжимаются.
|
|
94
|
+
*/
|
|
95
|
+
async function createZip(entries, options = {}) {
|
|
96
|
+
if (entries.length > MAX16) throw new ZipError("tooMany", `${entries.length} files do not fit into a ZIP without ZIP64`);
|
|
97
|
+
const { time, day } = dosTime(options.date ?? /* @__PURE__ */ new Date());
|
|
98
|
+
const seen = /* @__PURE__ */ new Set();
|
|
99
|
+
const body = [];
|
|
100
|
+
const central = [];
|
|
101
|
+
let offset = 0;
|
|
102
|
+
for (const entry of entries) {
|
|
103
|
+
assertName(entry.name);
|
|
104
|
+
if (seen.has(entry.name)) throw new ZipError("duplicate", entry.name);
|
|
105
|
+
seen.add(entry.name);
|
|
106
|
+
const name = encoder.encode(entry.name);
|
|
107
|
+
const crc = crc32(entry.data);
|
|
108
|
+
let method = STORED;
|
|
109
|
+
let stored = entry.data;
|
|
110
|
+
if (options.compress !== "store" && !ALREADY_COMPRESSED.test(entry.name)) {
|
|
111
|
+
const packed = await through(entry.data, new CompressionStream("deflate-raw"));
|
|
112
|
+
if (packed.length < entry.data.length) {
|
|
113
|
+
method = DEFLATED;
|
|
114
|
+
stored = packed;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (entry.data.length > MAX32 || offset > MAX32) throw new ZipError("tooLarge", entry.name);
|
|
118
|
+
const local = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(30));
|
|
119
|
+
local.setUint32(0, LOCAL, true);
|
|
120
|
+
local.setUint16(4, VERSION, true);
|
|
121
|
+
local.setUint16(6, UTF8_NAMES, true);
|
|
122
|
+
local.setUint16(8, method, true);
|
|
123
|
+
local.setUint16(10, time, true);
|
|
124
|
+
local.setUint16(12, day, true);
|
|
125
|
+
local.setUint32(14, crc, true);
|
|
126
|
+
local.setUint32(18, stored.length, true);
|
|
127
|
+
local.setUint32(22, entry.data.length, true);
|
|
128
|
+
local.setUint16(26, name.length, true);
|
|
129
|
+
local.setUint16(28, 0, true);
|
|
130
|
+
const head = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(46));
|
|
131
|
+
head.setUint32(0, CENTRAL, true);
|
|
132
|
+
head.setUint16(4, VERSION, true);
|
|
133
|
+
head.setUint16(6, VERSION, true);
|
|
134
|
+
head.setUint16(8, UTF8_NAMES, true);
|
|
135
|
+
head.setUint16(10, method, true);
|
|
136
|
+
head.setUint16(12, time, true);
|
|
137
|
+
head.setUint16(14, day, true);
|
|
138
|
+
head.setUint32(16, crc, true);
|
|
139
|
+
head.setUint32(20, stored.length, true);
|
|
140
|
+
head.setUint32(24, entry.data.length, true);
|
|
141
|
+
head.setUint16(28, name.length, true);
|
|
142
|
+
head.setUint32(42, offset, true);
|
|
143
|
+
body.push(new Uint8Array(local.buffer), name, stored);
|
|
144
|
+
central.push(new Uint8Array(head.buffer), name);
|
|
145
|
+
offset += 30 + name.length + stored.length;
|
|
146
|
+
}
|
|
147
|
+
const directory = concat(central);
|
|
148
|
+
if (offset + directory.length > MAX32) throw new ZipError("tooLarge");
|
|
149
|
+
const end = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(22));
|
|
150
|
+
end.setUint32(0, END, true);
|
|
151
|
+
end.setUint16(8, entries.length, true);
|
|
152
|
+
end.setUint16(10, entries.length, true);
|
|
153
|
+
end.setUint32(12, directory.length, true);
|
|
154
|
+
end.setUint32(16, offset, true);
|
|
155
|
+
return concat([
|
|
156
|
+
...body,
|
|
157
|
+
directory,
|
|
158
|
+
new Uint8Array(end.buffer)
|
|
159
|
+
]);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Whether the bytes start like a ZIP (a file or an empty archive). A quick check to tell an archive from a text file
|
|
163
|
+
* before opening it; `readZip` does the real checking.
|
|
164
|
+
* Начинаются ли байты как ZIP (файл или пустой архив). Быстрая проверка, чтобы отличить архив от текстового файла
|
|
165
|
+
* до открытия; настоящую проверку делает `readZip`.
|
|
166
|
+
*/
|
|
167
|
+
function looksLikeZip(data) {
|
|
168
|
+
return data.length >= 4 && data[0] === 80 && data[1] === 75 && (data[2] === 3 && data[3] === 4 || data[2] === 5 && data[3] === 6);
|
|
169
|
+
}
|
|
170
|
+
function decodeName(bytes, utf8) {
|
|
171
|
+
try {
|
|
172
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
173
|
+
} catch {
|
|
174
|
+
if (utf8) throw new ZipError("corrupt", "name");
|
|
175
|
+
return String.fromCharCode(...bytes);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Reads a ZIP archive into its files (folders are skipped). Throws `ZipError`. Never writes anywhere: the names are
|
|
180
|
+
* checked (no `..`, no absolute paths, no backslashes) and the sizes are limited (`limits`), CRC is verified.
|
|
181
|
+
* Reads the central directory, so archives written by any tool open, including those with sizes after the data.
|
|
182
|
+
* Читает ZIP-архив в файлы (папки пропускаются). Бросает `ZipError`. Никуда ничего не пишет: имена проверяются
|
|
183
|
+
* (без `..`, абсолютных путей и обратных косых), размеры ограничены (`limits`), CRC сверяется.
|
|
184
|
+
* Читает центральный каталог, поэтому открываются архивы любой программы, в том числе с размерами после данных.
|
|
185
|
+
*/
|
|
186
|
+
async function readZip(data, limits = {}) {
|
|
187
|
+
const { maxEntries, maxEntryBytes, maxTotalBytes } = {
|
|
188
|
+
...ZIP_LIMITS,
|
|
189
|
+
...limits
|
|
190
|
+
};
|
|
191
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
192
|
+
let end = -1;
|
|
193
|
+
for (let i = data.length - 22; i >= Math.max(0, data.length - 22 - MAX16); i--) if (view.getUint32(i, true) === END && i + 22 + view.getUint16(i + 20, true) === data.length) {
|
|
194
|
+
end = i;
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
if (end < 0) throw new ZipError("notZip");
|
|
198
|
+
const count = view.getUint16(end + 10, true);
|
|
199
|
+
const directorySize = view.getUint32(end + 12, true);
|
|
200
|
+
const directoryOffset = view.getUint32(end + 16, true);
|
|
201
|
+
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");
|
|
202
|
+
if (count === MAX16 || directorySize === MAX32 || directoryOffset === MAX32) throw new ZipError("unsupported", "ZIP64");
|
|
203
|
+
if (count > maxEntries) throw new ZipError("tooMany", String(count));
|
|
204
|
+
if (directoryOffset + directorySize > end) throw new ZipError("corrupt", "directory");
|
|
205
|
+
const result = [];
|
|
206
|
+
const seen = /* @__PURE__ */ new Set();
|
|
207
|
+
let at = directoryOffset;
|
|
208
|
+
let declaredTotal = 0;
|
|
209
|
+
for (let n = 0; n < count; n++) {
|
|
210
|
+
if (at + 46 > end || view.getUint32(at, true) !== CENTRAL) throw new ZipError("corrupt", "directory");
|
|
211
|
+
const flags = view.getUint16(at + 8, true);
|
|
212
|
+
const method = view.getUint16(at + 10, true);
|
|
213
|
+
const crc = view.getUint32(at + 16, true);
|
|
214
|
+
const packedSize = view.getUint32(at + 20, true);
|
|
215
|
+
const size = view.getUint32(at + 24, true);
|
|
216
|
+
const nameLength = view.getUint16(at + 28, true);
|
|
217
|
+
const extraLength = view.getUint16(at + 30, true);
|
|
218
|
+
const commentLength = view.getUint16(at + 32, true);
|
|
219
|
+
const localOffset = view.getUint32(at + 42, true);
|
|
220
|
+
if (at + 46 + nameLength + extraLength + commentLength > end) throw new ZipError("corrupt", "directory");
|
|
221
|
+
const name = decodeName(data.subarray(at + 46, at + 46 + nameLength), (flags & UTF8_NAMES) !== 0);
|
|
222
|
+
at += 46 + nameLength + extraLength + commentLength;
|
|
223
|
+
if (name.endsWith("/")) {
|
|
224
|
+
assertName(name.slice(0, -1));
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
assertName(name);
|
|
228
|
+
if (seen.has(name)) throw new ZipError("duplicate", name);
|
|
229
|
+
seen.add(name);
|
|
230
|
+
if (flags & ENCRYPTED) throw new ZipError("unsupported", "encrypted");
|
|
231
|
+
if (method !== STORED && method !== DEFLATED) throw new ZipError("unsupported", `method ${method}`);
|
|
232
|
+
if (packedSize === MAX32 || size === MAX32 || localOffset === MAX32) throw new ZipError("unsupported", "ZIP64");
|
|
233
|
+
declaredTotal += size;
|
|
234
|
+
if (size > maxEntryBytes || declaredTotal > maxTotalBytes) throw new ZipError("tooLarge", name);
|
|
235
|
+
if (localOffset + 30 > directoryOffset || view.getUint32(localOffset, true) !== LOCAL) throw new ZipError("corrupt", name);
|
|
236
|
+
const start = localOffset + 30 + view.getUint16(localOffset + 26, true) + view.getUint16(localOffset + 28, true);
|
|
237
|
+
if (start + packedSize > directoryOffset) throw new ZipError("corrupt", name);
|
|
238
|
+
const packed = data.subarray(start, start + packedSize);
|
|
239
|
+
let bytes;
|
|
240
|
+
if (method === STORED) bytes = packed.slice();
|
|
241
|
+
else try {
|
|
242
|
+
bytes = await through(packed, new DecompressionStream("deflate-raw"), size);
|
|
243
|
+
} catch {
|
|
244
|
+
throw new ZipError("corrupt", name);
|
|
245
|
+
}
|
|
246
|
+
if (bytes.length !== size || crc32(bytes) !== crc) throw new ZipError("corrupt", name);
|
|
247
|
+
result.push({
|
|
248
|
+
name,
|
|
249
|
+
data: bytes
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
return result;
|
|
253
|
+
}
|
|
254
|
+
//#endregion
|
|
255
|
+
export { ZIP_LIMITS, ZipError, createZip, looksLikeZip, readZip };
|
|
256
|
+
|
|
257
|
+
//# sourceMappingURL=zip.js.map
|
package/dist/zip.js.map
ADDED
|
@@ -0,0 +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.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,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,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,QACX,QAAQ,OAAO,MAAM;OAErB,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,OAAO,KAAK;GAAE;GAAM,MAAM;EAAM,CAAC;CACrC;CACA,OAAO;AACX"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@1337exp/taoux",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.1",
|
|
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",
|
|
@@ -168,6 +168,10 @@
|
|
|
168
168
|
"types": "./dist/wheel.d.ts",
|
|
169
169
|
"import": "./dist/wheel.js"
|
|
170
170
|
},
|
|
171
|
+
"./zip": {
|
|
172
|
+
"types": "./dist/zip.d.ts",
|
|
173
|
+
"import": "./dist/zip.js"
|
|
174
|
+
},
|
|
171
175
|
"./taoui.css": "./theme/taoui.css",
|
|
172
176
|
"./package.json": "./package.json"
|
|
173
177
|
},
|
package/skills/taoux/SKILL.md
CHANGED
|
@@ -30,14 +30,15 @@ controls, or with your own design.
|
|
|
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. `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). `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 |
|
|
37
|
-
| `file` | `downloadBlob(name, data, mime?)` saves bytes or a `Blob`; `downloadText(name, text, mime?)`; `readTextFile(file, limit?)` reads a picked file, refusing a big one |
|
|
37
|
+
| `file` | `downloadBlob(name, data, mime?)` saves bytes or a `Blob`; `downloadText(name, text, mime?)`; `readTextFile(file, limit?)` reads a picked file, refusing a big one; `readBytesFile(file, limit?)` the same as bytes (an archive, an image) |
|
|
38
38
|
| `guides` | `snapToGuides(movingRect, otherRects, thresholdInWorldUnits)` → `{ dx, dy, lines }`: smart guides while dragging (edges and centres of the other nodes); you apply the shift and draw the lines; divide a screen threshold by the zoom |
|
|
39
39
|
| `snap` | soft snapping to a grid, threshold follows the zoom |
|
|
40
40
|
| `wheel` | wheel / trackpad → pan or zoom, like Figma (zoom only with Ctrl / ⌘ or a pinch) |
|
|
41
|
+
| `zip` | `await createZip([{ name: 'a/b.png', data }])` and `await readZip(bytes, limits?)`: a project of several files in one `.zip`. Reading an archive from outside is defensive (unsafe names, CRC, size limits against zip bombs); catch `ZipError` and show text by its `code`. `looksLikeZip(bytes)` tells an archive from JSON. Needs `CompressionStream` (any current browser, Node 18+) |
|
|
41
42
|
| `edgescroll` | auto-scroll near an edge while dragging (`createEdgeScroller`) |
|
|
42
43
|
| `gestures` | tap, double tap, long press, pinch; `SwipeTracker` (swipe vs scroll) + `settleOpen` (where a released row rests); `listenFocusLoss(cancel)` while a press is held, as Alt-Tab swallows the pointerup |
|
|
43
44
|
| `touch` | `coarse`: is the pointer a finger |
|