@1337exp/taoux 0.2.0 → 0.3.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 +13 -0
- package/README.md +5 -5
- package/README.ru.md +5 -5
- package/dist/file.d.ts +16 -3
- package/dist/file.js +27 -5
- package/dist/file.js.map +1 -1
- package/dist/gestures.d.ts +79 -0
- package/dist/gestures.js +121 -1
- package/dist/gestures.js.map +1 -1
- package/dist/ids.d.ts +13 -0
- package/dist/ids.js +25 -1
- package/dist/ids.js.map +1 -1
- package/dist/session.d.ts +15 -4
- package/dist/session.js +7 -6
- package/dist/session.js.map +1 -1
- package/dist/storage.d.ts +39 -1
- package/dist/storage.js +44 -3
- package/dist/storage.js.map +1 -1
- package/package.json +1 -1
- package/skills/taoux/SKILL.md +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
Additions for apps that are not canvas editors (a list of notes); everything that was there works as before, nothing to migrate.
|
|
6
|
+
|
|
7
|
+
- **`ids`: `uuid()`** — a random UUID v4 for records that are stored or synced. `crypto.randomUUID` where there is one; outside a secure context (plain http on a LAN address) the same v4 from `crypto.getRandomValues`. `uid()` stays for ids inside one document: its counter restarts on every load, which its comment now says.
|
|
8
|
+
- **`storage`:** `createSavedStorage` returns a `KeyStorage`, still a `SavedStorage` (it fits `createDocumentSession` as before), with `tryWrite(text)` → `{ ok: false, reason: 'quota' | 'denied' | 'unknown' }` (`write` stays a boolean), `remove()`, and `subscribe(listener)`: another tab of the site changed, removed or cleared the key. `storageFailure(error)` is exported too.
|
|
9
|
+
- **`session`:** `camera` is optional — a document without a canvas view (a list) gets `undefined` in `serialize`, and a `view` from `parse` is ignored. `countItems` is the new name of `countNodes`; the old name is still read.
|
|
10
|
+
- **`gestures`: `SwipeTracker` and `settleOpen`.** The tracker tells a swipe along its axis from a scroll across it (inside `SWIPE_SLOP_PX` nothing is decided, a diagonal goes to the page), follows the offset from where the row already stands without a jump by the slop, and measures the release speed over the last 100 ms. `settleOpen(release, { start?, end? })` says where a released row rests: a fling goes on one stop in its direction (an open row flung back closes rather than flying to the other side), otherwise the nearest stop.
|
|
11
|
+
|
|
12
|
+
## 0.2.2
|
|
13
|
+
|
|
14
|
+
- **`file`:** `downloadText(filename, text, mime?)` takes the type of the file (it was always `application/json`), and the new `readTextFile(file, limit?)` is its pair: it reads a picked file as text, refuses a file above `MAX_FILE_BYTES` before reading it, and returns `{ ok: false, error: 'tooLarge' | 'unreadable' }` instead of throwing. Nothing to migrate.
|
|
15
|
+
|
|
3
16
|
## 0.2.0
|
|
4
17
|
|
|
5
18
|
TaoUI 5.0 is out, and TaoUX follows it, with two new modules for the TaoUI menu bar.
|
package/README.md
CHANGED
|
@@ -82,18 +82,18 @@ import { History } from '@1337exp/taoux/history';
|
|
|
82
82
|
| `camera` | canvas camera: pan, zoom around the cursor, screen ↔ world | nothing |
|
|
83
83
|
| `history` | undo/redo on string snapshots, rapid edits merged into one step | nothing |
|
|
84
84
|
| `hotkeys` | shortcuts: `parseHotkey('Mod+Shift+Z')`, `matchHotkey` (Mod = ⌘ / Ctrl, non-Latin layouts by the physical key), `formatHotkey` (`Ctrl+Shift+Z` / `⇧⌘Z`), `isReservedHotkey` (⌘W, ⌘T, ⌘Q…), `bindHotkeys` on an element | DOM (for `bindHotkeys`) |
|
|
85
|
-
| `storage` | autosave to localStorage without exceptions | nothing |
|
|
86
|
-
| `file` | download text as a file, size limit | DOM |
|
|
85
|
+
| `storage` | autosave to localStorage without exceptions; `tryWrite` (why it failed: quota / denied), `remove`, `subscribe` (another tab changed the key) | nothing |
|
|
86
|
+
| `file` | download text as a file (any `mime`), read a picked file as text with a size limit | DOM |
|
|
87
87
|
| `snap` | soft snapping to a grid with a threshold that follows the camera zoom | nothing |
|
|
88
88
|
| `wheel` | wheel/trackpad → pan or zoom (like Figma) | nothing |
|
|
89
89
|
| `edgescroll` | auto-scroll speed near an edge and a ready loop, `createEdgeScroller` (canvas, curve editors, any drag) | nothing |
|
|
90
|
-
| `gestures` | touch gestures: tap, double tap, long press, pinch | nothing |
|
|
90
|
+
| `gestures` | touch gestures: tap, double tap, long press, pinch, swipe (`SwipeTracker` + `settleOpen` for a row that slides open) | nothing |
|
|
91
91
|
| `touch` | `coarse`: is there a coarse pointer (a finger) | vue (peer) |
|
|
92
92
|
| `curve` | link paths: bezier between pins, arrowheads of constant screen size | nothing |
|
|
93
|
-
| `ids` | `uid(prefix, taken)` | nothing |
|
|
93
|
+
| `ids` | `uuid()` for records that are stored or synced; `uid(prefix, taken)` for ids inside one document | nothing |
|
|
94
94
|
| `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 |
|
|
95
95
|
| `num` | small numeric helpers: `clamp`, `roundTo`, `snapTo`, `niceStep`, `ticks` (shared by the curve, gradient and playback modules) | nothing |
|
|
96
|
-
| `session` | document lifecycle: history, autosave, files, restore, notices | vue (peer) |
|
|
96
|
+
| `session` | document lifecycle: history, autosave, files, restore, notices; a canvas camera is optional (`countItems`) | vue (peer) |
|
|
97
97
|
| `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`) |
|
|
98
98
|
| `palette` | search and groups of nodes for a palette | nothing |
|
|
99
99
|
| `links` (Vue) | links layer: SVG from ready geometry, `--tx-link-*` | vue (peer) |
|
package/README.ru.md
CHANGED
|
@@ -82,18 +82,18 @@ import { History } from '@1337exp/taoux/history';
|
|
|
82
82
|
| `camera` | камера холста: pan, zoom вокруг курсора, экран ↔ мир | нет |
|
|
83
83
|
| `history` | undo/redo на снимках-строках со склейкой частых правок | нет |
|
|
84
84
|
| `hotkeys` | сочетания клавиш: `parseHotkey('Mod+Shift+Z')`, `matchHotkey` (Mod = ⌘ / Ctrl, нелатинские раскладки по физической клавише), `formatHotkey` (`Ctrl+Shift+Z` / `⇧⌘Z`), `isReservedHotkey` (⌘W, ⌘T, ⌘Q…), `bindHotkeys` на элементе | DOM (для `bindHotkeys`) |
|
|
85
|
-
| `storage` | автосохранение в localStorage без
|
|
86
|
-
| `file` | скачивание текста как
|
|
85
|
+
| `storage` | автосохранение в localStorage без исключений; `tryWrite` (почему не вышло: квота / запрет), `remove`, `subscribe` (ключ изменила другая вкладка) | нет |
|
|
86
|
+
| `file` | скачивание текста как файла (любой `mime`), чтение выбранного файла как текста с лимитом размера | DOM |
|
|
87
87
|
| `snap` | мягкая привязка к сетке с порогом по масштабу камеры | нет |
|
|
88
88
|
| `wheel` | колесо/тачпад → pan или zoom (как в Figma) | нет |
|
|
89
89
|
| `edgescroll` | скорость автопрокрутки у края и готовый цикл `createEdgeScroller` (холст, редакторы кривых и любое перетаскивание) | нет |
|
|
90
|
-
| `gestures` | сенсорные жесты: тап, двойной тап, долгое нажатие,
|
|
90
|
+
| `gestures` | сенсорные жесты: тап, двойной тап, долгое нажатие, щипок, свайп (`SwipeTracker` + `settleOpen` для строки, которая отъезжает) | нет |
|
|
91
91
|
| `touch` | `coarse` — есть ли грубый указатель (палец) | vue (peer) |
|
|
92
92
|
| `curve` | пути связей: безье между пинами, стрелки постоянного экранного размера | нет |
|
|
93
|
-
| `ids` | `uid(prefix, taken)` | нет |
|
|
93
|
+
| `ids` | `uuid()` для записей, которые хранятся или синхронизируются; `uid(prefix, taken)` для id внутри одного документа | нет |
|
|
94
94
|
| `ease` | функции движения между точками кривой: 8 семейств × in / out / in-out, `linear`, `step`, кубический Безье; `easeValue`, `isEase` (редактор рисует ими, рантайм считает ими же) | нет |
|
|
95
95
|
| `num` | мелкая числовая математика: `clamp`, `roundTo`, `snapTo`, `niceStep`, `ticks` (общая для кривой, градиента и воспроизведения) | нет |
|
|
96
|
-
| `session` | жизненный цикл документа: история, автосохранение, файлы, восстановление,
|
|
96
|
+
| `session` | жизненный цикл документа: история, автосохранение, файлы, восстановление, уведомления; камера холста необязательна (`countItems`) | vue (peer) |
|
|
97
97
|
| `commands` | реестр команд (подпись, сочетание, `enabled`, `checked`, `run`): `toMenu(layout)` строит дерево `TaoMenuItem[]` для `TaoMenubar` / `TaoContextMenu`, `bind` слушает те же сочетания, `historyCommands` даёт Undo / Redo, которые сами становятся недоступными, `check` находит занятые браузером и повторённые сочетания | DOM (для `bind`) |
|
|
98
98
|
| `palette` | поиск и группы нод для палитры | нет |
|
|
99
99
|
| `links` (Vue) | слой связей: SVG из готовой геометрии, `--tx-link-*` | vue (peer) |
|
package/dist/file.d.ts
CHANGED
|
@@ -4,7 +4,20 @@
|
|
|
4
4
|
*/
|
|
5
5
|
export declare const MAX_FILE_BYTES = 5000000;
|
|
6
6
|
/**
|
|
7
|
-
* Downloads text as a file through a temporary link.
|
|
8
|
-
* Скачивание текста как файла через временную ссылку.
|
|
7
|
+
* Downloads text as a file through a temporary link. `mime` is the type of the file (JSON by default).
|
|
8
|
+
* Скачивание текста как файла через временную ссылку. `mime` — тип файла (по умолчанию JSON).
|
|
9
9
|
*/
|
|
10
|
-
export declare function downloadText(filename: string, text: string): void;
|
|
10
|
+
export declare function downloadText(filename: string, text: string, mime?: string): void;
|
|
11
|
+
export type ReadTextResult = {
|
|
12
|
+
ok: true;
|
|
13
|
+
text: string;
|
|
14
|
+
} | {
|
|
15
|
+
ok: false;
|
|
16
|
+
error: 'tooLarge' | 'unreadable';
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Reads a picked file as text. A file above `limit` bytes is refused before it is read; a failed read is a result,
|
|
20
|
+
* not an exception.
|
|
21
|
+
* Читает выбранный файл как текст. Файл больше `limit` байт отклоняется до чтения; сбой чтения — результат, а не исключение.
|
|
22
|
+
*/
|
|
23
|
+
export declare function readTextFile(file: Blob, limit?: number): Promise<ReadTextResult>;
|
package/dist/file.js
CHANGED
|
@@ -5,18 +5,40 @@
|
|
|
5
5
|
*/
|
|
6
6
|
var MAX_FILE_BYTES = 5e6;
|
|
7
7
|
/**
|
|
8
|
-
* Downloads text as a file through a temporary link.
|
|
9
|
-
* Скачивание текста как файла через временную ссылку.
|
|
8
|
+
* Downloads text as a file through a temporary link. `mime` is the type of the file (JSON by default).
|
|
9
|
+
* Скачивание текста как файла через временную ссылку. `mime` — тип файла (по умолчанию JSON).
|
|
10
10
|
*/
|
|
11
|
-
function downloadText(filename, text) {
|
|
12
|
-
const url = URL.createObjectURL(new Blob([text], { type:
|
|
11
|
+
function downloadText(filename, text, mime = "application/json") {
|
|
12
|
+
const url = URL.createObjectURL(new Blob([text], { type: mime }));
|
|
13
13
|
const link = document.createElement("a");
|
|
14
14
|
link.href = url;
|
|
15
15
|
link.download = filename;
|
|
16
16
|
link.click();
|
|
17
17
|
setTimeout(() => URL.revokeObjectURL(url), 1e3);
|
|
18
18
|
}
|
|
19
|
+
/**
|
|
20
|
+
* Reads a picked file as text. A file above `limit` bytes is refused before it is read; a failed read is a result,
|
|
21
|
+
* not an exception.
|
|
22
|
+
* Читает выбранный файл как текст. Файл больше `limit` байт отклоняется до чтения; сбой чтения — результат, а не исключение.
|
|
23
|
+
*/
|
|
24
|
+
async function readTextFile(file, limit = MAX_FILE_BYTES) {
|
|
25
|
+
if (file.size > limit) return {
|
|
26
|
+
ok: false,
|
|
27
|
+
error: "tooLarge"
|
|
28
|
+
};
|
|
29
|
+
try {
|
|
30
|
+
return {
|
|
31
|
+
ok: true,
|
|
32
|
+
text: await file.text()
|
|
33
|
+
};
|
|
34
|
+
} catch {
|
|
35
|
+
return {
|
|
36
|
+
ok: false,
|
|
37
|
+
error: "unreadable"
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
}
|
|
19
41
|
//#endregion
|
|
20
|
-
export { MAX_FILE_BYTES, downloadText };
|
|
42
|
+
export { MAX_FILE_BYTES, downloadText, readTextFile };
|
|
21
43
|
|
|
22
44
|
//# 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 text as a file through a temporary link.\n * Скачивание текста как файла через временную
|
|
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 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 const url = URL.createObjectURL(new Blob([text], { type: mime }));\n const link = document.createElement('a');\n link.href = url;\n link.download = filename;\n link.click();\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\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;;;;;AAM9B,SAAgB,aAAa,UAAkB,MAAc,OAAO,oBAA0B;CAC1F,MAAM,MAAM,IAAI,gBAAgB,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,MAAM,KAAK,CAAC,CAAC;CAChE,MAAM,OAAO,SAAS,cAAc,GAAG;CACvC,KAAK,OAAO;CACZ,KAAK,WAAW;CAChB,KAAK,MAAM;CAGX,iBAAiB,IAAI,gBAAgB,GAAG,GAAG,GAAI;AACnD;;;;;;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"}
|
package/dist/gestures.d.ts
CHANGED
|
@@ -171,4 +171,83 @@ export declare class PinchTracker {
|
|
|
171
171
|
get isZooming(): boolean;
|
|
172
172
|
update(next: Pinch): PinchStep;
|
|
173
173
|
}
|
|
174
|
+
/**
|
|
175
|
+
* How far the finger moves before the intent is decided: a swipe along the axis, or a scroll across it.
|
|
176
|
+
* Сколько палец проходит, прежде чем решается намерение: свайп вдоль оси или прокрутка поперёк.
|
|
177
|
+
*/
|
|
178
|
+
export declare const SWIPE_SLOP_PX = 10;
|
|
179
|
+
/**
|
|
180
|
+
* A release faster than this (px/ms) is a fling: it goes on in its direction whatever the offset.
|
|
181
|
+
* Отпускание быстрее этого (px/мс) — бросок: он продолжается в своём направлении при любом сдвиге.
|
|
182
|
+
*/
|
|
183
|
+
export declare const SWIPE_FLING_PX_PER_MS = 0.4;
|
|
184
|
+
/**
|
|
185
|
+
* The release speed is measured over this last stretch of the gesture, ms.
|
|
186
|
+
* Скорость отпускания меряется на этом последнем отрезке жеста, мс.
|
|
187
|
+
*/
|
|
188
|
+
export declare const SWIPE_VELOCITY_WINDOW_MS = 100;
|
|
189
|
+
/**
|
|
190
|
+
* `pending` — not decided yet (inside the slop); `swipe` — along the axis, the app moves the row; `scroll` — across,
|
|
191
|
+
* the gesture belongs to the page and the tracker ignores it until the next `down`.
|
|
192
|
+
* `pending` — ещё не решено (в пределах допуска); `swipe` — вдоль оси, приложение двигает строку; `scroll` — поперёк,
|
|
193
|
+
* жест принадлежит странице, и трекер его игнорирует до следующего `down`.
|
|
194
|
+
*/
|
|
195
|
+
export type SwipeIntent = 'pending' | 'swipe' | 'scroll';
|
|
196
|
+
export interface SwipeStep {
|
|
197
|
+
intent: SwipeIntent;
|
|
198
|
+
/**
|
|
199
|
+
* Where the row stands now: the offset it had at `down` plus the travel since the swipe engaged (so it does not
|
|
200
|
+
* jump by the slop).
|
|
201
|
+
* Где строка сейчас: сдвиг на момент `down` плюс путь с момента, как свайп включился (поэтому без скачка на допуск).
|
|
202
|
+
*/
|
|
203
|
+
offset: number;
|
|
204
|
+
}
|
|
205
|
+
export interface SwipeRelease {
|
|
206
|
+
offset: number;
|
|
207
|
+
/** px/ms along the axis, + to the right / down. / px/мс вдоль оси, + вправо / вниз. */
|
|
208
|
+
velocity: number;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Tells a swipe from a scroll and follows it. Pure logic, as the other recognizers: the app feeds it pointer samples,
|
|
212
|
+
* moves the element by `offset` and, on release, asks `settleOpen` where the element should come to rest.
|
|
213
|
+
* Отличает свайп от прокрутки и ведёт его. Чистая логика, как остальные распознаватели: приложение подаёт отсчёты
|
|
214
|
+
* указателя, двигает элемент на `offset`, а при отпускании спрашивает `settleOpen`, где элементу остановиться.
|
|
215
|
+
*/
|
|
216
|
+
export declare class SwipeTracker {
|
|
217
|
+
private readonly axis;
|
|
218
|
+
private readonly slop;
|
|
219
|
+
private start;
|
|
220
|
+
private from;
|
|
221
|
+
private engage;
|
|
222
|
+
private intent;
|
|
223
|
+
private trail;
|
|
224
|
+
constructor(axis?: 'x' | 'y', slop?: number);
|
|
225
|
+
private along;
|
|
226
|
+
private across;
|
|
227
|
+
/**
|
|
228
|
+
* The finger landed. `from` is where the row already stands (0 closed, or its open offset).
|
|
229
|
+
* Палец лёг. `from` — где строка уже стоит (0 — закрыта, или её открытый сдвиг).
|
|
230
|
+
*/
|
|
231
|
+
down(s: Sample, from?: number): void;
|
|
232
|
+
move(s: Sample): SwipeStep;
|
|
233
|
+
/**
|
|
234
|
+
* The finger was lifted. Null unless it was a swipe.
|
|
235
|
+
* Палец поднят. Null, если это был не свайп.
|
|
236
|
+
*/
|
|
237
|
+
up(s: Sample): SwipeRelease | null;
|
|
238
|
+
cancel(): void;
|
|
239
|
+
get current(): SwipeIntent;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Where a released row comes to rest: closed (0), open at the start (`start`, > 0, actions on the left) or open at
|
|
243
|
+
* the end (`-end`, actions on the right). A fling goes on in its direction, one stop at a time (an open row flung
|
|
244
|
+
* back closes, it does not fly to the other side); otherwise the nearest stop wins.
|
|
245
|
+
* Где отпущенная строка останавливается: закрыта (0), открыта в начале (`start`, > 0, действия слева) или в конце
|
|
246
|
+
* (`-end`, действия справа). Бросок продолжается в своём направлении на одну остановку (открытая строка, брошенная
|
|
247
|
+
* обратно, закрывается, а не улетает на другую сторону); иначе побеждает ближайшая остановка.
|
|
248
|
+
*/
|
|
249
|
+
export declare function settleOpen(release: SwipeRelease, open: {
|
|
250
|
+
start?: number;
|
|
251
|
+
end?: number;
|
|
252
|
+
}, fling?: number): number;
|
|
174
253
|
export {};
|
package/dist/gestures.js
CHANGED
|
@@ -223,7 +223,127 @@ var PinchTracker = class {
|
|
|
223
223
|
return step;
|
|
224
224
|
}
|
|
225
225
|
};
|
|
226
|
+
/**
|
|
227
|
+
* How far the finger moves before the intent is decided: a swipe along the axis, or a scroll across it.
|
|
228
|
+
* Сколько палец проходит, прежде чем решается намерение: свайп вдоль оси или прокрутка поперёк.
|
|
229
|
+
*/
|
|
230
|
+
var SWIPE_SLOP_PX = 10;
|
|
231
|
+
/**
|
|
232
|
+
* A release faster than this (px/ms) is a fling: it goes on in its direction whatever the offset.
|
|
233
|
+
* Отпускание быстрее этого (px/мс) — бросок: он продолжается в своём направлении при любом сдвиге.
|
|
234
|
+
*/
|
|
235
|
+
var SWIPE_FLING_PX_PER_MS = .4;
|
|
236
|
+
/**
|
|
237
|
+
* The release speed is measured over this last stretch of the gesture, ms.
|
|
238
|
+
* Скорость отпускания меряется на этом последнем отрезке жеста, мс.
|
|
239
|
+
*/
|
|
240
|
+
var SWIPE_VELOCITY_WINDOW_MS = 100;
|
|
241
|
+
/**
|
|
242
|
+
* Tells a swipe from a scroll and follows it. Pure logic, as the other recognizers: the app feeds it pointer samples,
|
|
243
|
+
* moves the element by `offset` and, on release, asks `settleOpen` where the element should come to rest.
|
|
244
|
+
* Отличает свайп от прокрутки и ведёт его. Чистая логика, как остальные распознаватели: приложение подаёт отсчёты
|
|
245
|
+
* указателя, двигает элемент на `offset`, а при отпускании спрашивает `settleOpen`, где элементу остановиться.
|
|
246
|
+
*/
|
|
247
|
+
var SwipeTracker = class {
|
|
248
|
+
axis;
|
|
249
|
+
slop;
|
|
250
|
+
start = null;
|
|
251
|
+
from = 0;
|
|
252
|
+
engage = null;
|
|
253
|
+
intent = "pending";
|
|
254
|
+
trail = [];
|
|
255
|
+
constructor(axis = "x", slop = 10) {
|
|
256
|
+
this.axis = axis;
|
|
257
|
+
this.slop = slop;
|
|
258
|
+
}
|
|
259
|
+
along(s) {
|
|
260
|
+
return this.axis === "x" ? s.x : s.y;
|
|
261
|
+
}
|
|
262
|
+
across(s) {
|
|
263
|
+
return this.axis === "x" ? s.y : s.x;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* The finger landed. `from` is where the row already stands (0 closed, or its open offset).
|
|
267
|
+
* Палец лёг. `from` — где строка уже стоит (0 — закрыта, или её открытый сдвиг).
|
|
268
|
+
*/
|
|
269
|
+
down(s, from = 0) {
|
|
270
|
+
this.start = s;
|
|
271
|
+
this.from = from;
|
|
272
|
+
this.engage = null;
|
|
273
|
+
this.intent = "pending";
|
|
274
|
+
this.trail = [s];
|
|
275
|
+
}
|
|
276
|
+
move(s) {
|
|
277
|
+
const start = this.start;
|
|
278
|
+
if (!start || this.intent === "scroll") return {
|
|
279
|
+
intent: this.intent,
|
|
280
|
+
offset: this.from
|
|
281
|
+
};
|
|
282
|
+
if (this.intent === "pending") {
|
|
283
|
+
const da = Math.abs(this.along(s) - this.along(start));
|
|
284
|
+
const dc = Math.abs(this.across(s) - this.across(start));
|
|
285
|
+
if (Math.max(da, dc) <= this.slop) return {
|
|
286
|
+
intent: "pending",
|
|
287
|
+
offset: this.from
|
|
288
|
+
};
|
|
289
|
+
this.intent = da > dc ? "swipe" : "scroll";
|
|
290
|
+
if (this.intent === "scroll") return {
|
|
291
|
+
intent: "scroll",
|
|
292
|
+
offset: this.from
|
|
293
|
+
};
|
|
294
|
+
this.engage = s;
|
|
295
|
+
}
|
|
296
|
+
this.trail.push(s);
|
|
297
|
+
while (this.trail.length > 2 && s.t - this.trail[0].t > 100) this.trail.shift();
|
|
298
|
+
return {
|
|
299
|
+
intent: "swipe",
|
|
300
|
+
offset: this.from + this.along(s) - this.along(this.engage)
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* The finger was lifted. Null unless it was a swipe.
|
|
305
|
+
* Палец поднят. Null, если это был не свайп.
|
|
306
|
+
*/
|
|
307
|
+
up(s) {
|
|
308
|
+
const step = this.move(s);
|
|
309
|
+
const swiped = this.intent === "swipe";
|
|
310
|
+
const first = this.trail[0];
|
|
311
|
+
this.start = null;
|
|
312
|
+
if (!swiped || !first) return null;
|
|
313
|
+
const dt = s.t - first.t;
|
|
314
|
+
const velocity = dt > 0 ? (this.along(s) - this.along(first)) / dt : 0;
|
|
315
|
+
return {
|
|
316
|
+
offset: step.offset,
|
|
317
|
+
velocity
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
cancel() {
|
|
321
|
+
this.start = null;
|
|
322
|
+
this.intent = "pending";
|
|
323
|
+
this.trail = [];
|
|
324
|
+
}
|
|
325
|
+
get current() {
|
|
326
|
+
return this.intent;
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
/**
|
|
330
|
+
* Where a released row comes to rest: closed (0), open at the start (`start`, > 0, actions on the left) or open at
|
|
331
|
+
* the end (`-end`, actions on the right). A fling goes on in its direction, one stop at a time (an open row flung
|
|
332
|
+
* back closes, it does not fly to the other side); otherwise the nearest stop wins.
|
|
333
|
+
* Где отпущенная строка останавливается: закрыта (0), открыта в начале (`start`, > 0, действия слева) или в конце
|
|
334
|
+
* (`-end`, действия справа). Бросок продолжается в своём направлении на одну остановку (открытая строка, брошенная
|
|
335
|
+
* обратно, закрывается, а не улетает на другую сторону); иначе побеждает ближайшая остановка.
|
|
336
|
+
*/
|
|
337
|
+
function settleOpen(release, open, fling = SWIPE_FLING_PX_PER_MS) {
|
|
338
|
+
const stops = [0];
|
|
339
|
+
if (open.start) stops.push(open.start);
|
|
340
|
+
if (open.end) stops.push(-open.end);
|
|
341
|
+
stops.sort((a, b) => a - b);
|
|
342
|
+
const { offset, velocity } = release;
|
|
343
|
+
if (Math.abs(velocity) >= fling) return (velocity > 0 ? stops.filter((p) => p > offset) : stops.filter((p) => p < offset).reverse())[0] ?? (velocity > 0 ? stops[stops.length - 1] : stops[0]);
|
|
344
|
+
return stops.reduce((best, p) => Math.abs(p - offset) < Math.abs(best - offset) ? p : best, 0);
|
|
345
|
+
}
|
|
226
346
|
//#endregion
|
|
227
|
-
export { DOUBLE_TAP_MS, DOUBLE_TAP_RADIUS_PX, LONG_PRESS_MS, PINCH_DEADBAND_PX, PINCH_DOMINANCE, PINCH_ENGAGE_PX, PINCH_MIN_NET_PX, PINCH_RELEASE_MIN_PX, PINCH_RELEASE_RATIO, PINCH_WINDOW, PinchTracker, TAP_MAX_MS, TAP_SLOP_PX, TapRecognizer, pinchOf };
|
|
347
|
+
export { DOUBLE_TAP_MS, DOUBLE_TAP_RADIUS_PX, LONG_PRESS_MS, PINCH_DEADBAND_PX, PINCH_DOMINANCE, PINCH_ENGAGE_PX, PINCH_MIN_NET_PX, PINCH_RELEASE_MIN_PX, PINCH_RELEASE_RATIO, PINCH_WINDOW, PinchTracker, SWIPE_FLING_PX_PER_MS, SWIPE_SLOP_PX, SWIPE_VELOCITY_WINDOW_MS, SwipeTracker, TAP_MAX_MS, TAP_SLOP_PX, TapRecognizer, pinchOf, settleOpen };
|
|
228
348
|
|
|
229
349
|
//# sourceMappingURL=gestures.js.map
|
package/dist/gestures.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gestures.js","names":[],"sources":["../src/gestures.ts"],"sourcesContent":["/**\n * Recognition of touch gestures. Pure logic with no DOM and no timers: time and coordinates come from outside,\n * so everything is covered by tests. Events and timers (long press) live in EditorCanvas.\n * Распознавание сенсорных жестов. Чистая логика без DOM и таймеров: время и координаты приходят снаружи,\n * поэтому всё проверяется тестами. События и таймеры (долгое нажатие) живут в EditorCanvas.\n */\n\n/**\n * By how many px a finger may move and still count as \"standing still\".\n * На сколько px палец может сместиться и всё ещё считаться «стоящим на месте».\n */\nexport const TAP_SLOP_PX = 8;\n/**\n * A touch longer than this is no longer a tap.\n * Дольше этого касание уже не тап.\n */\nexport const TAP_MAX_MS = 300;\n/**\n * How long the finger must be held still for a long press.\n * Сколько надо держать палец неподвижно для долгого нажатия.\n */\nexport const LONG_PRESS_MS = 500;\n/**\n * The second tap must come no later and no further than this from the first.\n * Второй тап должен прийти не позже и не дальше этого от первого.\n */\nexport const DOUBLE_TAP_MS = 300;\nexport const DOUBLE_TAP_RADIUS_PX = 30;\n\nexport interface Sample {\n x: number;\n y: number;\n /**\n * Time, ms (any monotonic scale).\n * Время, мс (любая монотонная шкала).\n */\n t: number;\n}\n\nconst dist = (a: { x: number; y: number }, b: { x: number; y: number }) => Math.hypot(a.x - b.x, a.y - b.y);\n\nexport type TapResult = 'tap' | 'double' | null;\n\n/**\n * Parses a one-finger touch: tap, double tap, movement, readiness of a long press.\n * Разбирает касание одним пальцем: тап, двойной тап, сдвиг, готовность долгого нажатия.\n */\nexport class TapRecognizer {\n private start: Sample | null = null;\n private moved = false;\n private lastTap: Sample | null = null;\n private doubleDown = false;\n\n /**\n * The finger landed. Returns true if this is the second touch of a double tap (it is not finished yet:\n * a drag may follow, as in \"double tap and drag\").\n * Палец лёг. Возвращает true, если это второе касание двойного тапа (оно ещё не закончено:\n * дальше может быть протяжка, как «двойной тап и тянуть»).\n */\n down(s: Sample): boolean {\n this.start = s;\n this.moved = false;\n const prev = this.lastTap;\n this.doubleDown = prev !== null && s.t - prev.t <= DOUBLE_TAP_MS && dist(s, prev) <= DOUBLE_TAP_RADIUS_PX;\n return this.doubleDown;\n }\n\n /**\n * The finger moved. Returns true if it already left the slop (neither a tap nor a long press).\n * Палец сдвинулся. Возвращает true, если он уже ушёл дальше допуска (не тап и не долгое нажатие).\n */\n move(s: Sample): boolean {\n if (this.start && !this.moved && dist(s, this.start) > TAP_SLOP_PX) this.moved = true;\n return this.moved;\n }\n\n get isMoved(): boolean {\n return this.moved;\n }\n\n /**\n * Whether it is time to count the touch as a long press: the finger lies still longer than `LONG_PRESS_MS`.\n * Пора ли считать касание долгим нажатием: палец лежит на месте дольше `LONG_PRESS_MS`.\n */\n longPressDue(now: number): boolean {\n return this.start !== null && !this.moved && now - this.start.t >= LONG_PRESS_MS;\n }\n\n /**\n * The finger was lifted: what that was. After `double` the next tap counts as single again.\n * Палец поднят: что это было. После `double` следующий тап снова считается одиночным.\n */\n up(s: Sample): TapResult {\n const start = this.start;\n this.start = null;\n if (!start) return null;\n\n this.move(s);\n if (this.moved || s.t - start.t > TAP_MAX_MS) {\n this.lastTap = null;\n return null;\n }\n if (this.doubleDown) {\n this.lastTap = null;\n return 'double';\n }\n this.lastTap = s;\n return 'tap';\n }\n\n /**\n * The gesture turned out to be something else (a long press, a pinch, an interruption): forget both the current touch and the previous tap.\n * Жест оказался чем-то другим (долгое нажатие, щипок, прерывание): забываем и текущее касание, и предыдущий тап.\n */\n cancel(): void {\n this.start = null;\n this.lastTap = null;\n this.doubleDown = false;\n }\n}\n\n//--------------------------------------------------\n// Pinch and a two-finger gesture\n// Щипок и жест двумя пальцами\n\ntype Point = { x: number; y: number };\n\nexport interface Pinch {\n /**\n * The centre between the fingers.\n * Центр между пальцами.\n */\n cx: number;\n cy: number;\n /**\n * The distance between the fingers; 0 if there is one finger (then only a shift).\n * Расстояние между пальцами; 0, если палец один (тогда только сдвиг).\n */\n dist: number;\n}\n\nexport function pinchOf(a: Point, b?: Point): Pinch {\n if (!b) return { cx: a.x, cy: a.y, dist: 0 };\n return { cx: (a.x + b.x) / 2, cy: (a.y + b.y) / 2, dist: dist(a, b) };\n}\n\nexport interface PinchStep {\n /**\n * By how many times to change the scale.\n * Во сколько раз изменить масштаб.\n */\n factor: number;\n /**\n * Around which point (the centre before the step).\n * Вокруг какой точки (центр до шага).\n */\n pivot: [number, number];\n /**\n * By how much to shift the camera after the scale.\n * На сколько сдвинуть камеру после масштаба.\n */\n pan: [number, number];\n}\n\n/**\n * Until the distance between the fingers has changed by this much, the gesture counts as a plain shift: the scale is not touched.\n * Пока расстояние между пальцами не изменилось на столько, жест считается просто сдвигом: масштаб не трогаем.\n */\nexport const PINCH_ENGAGE_PX = 20;\n/**\n * Distance changes smaller than this count as finger jitter and are ignored.\n * Изменения расстояния мельче этого считаем дрожанием пальцев и игнорируем.\n */\nexport const PINCH_DEADBAND_PX = 1.5;\n/**\n * How many last steps we look at when deciding \"shifting or scaling\".\n * Сколько последних шагов смотрим, решая «сдвигают или масштабируют».\n */\nexport const PINCH_WINDOW = 6;\n/**\n * To turn the scale on, the distance over the window must change at least as much as the centre moves, and at least this much.\n * Для включения масштаба расстояние за окно должно меняться не меньше, чем сдвигается центр, и не меньше этого.\n */\nexport const PINCH_DOMINANCE = 1;\nexport const PINCH_MIN_NET_PX = 4;\n/**\n * The scale turns off again when the centre moves this many times further than the distance changes over the window (and at least `PINCH_RELEASE_MIN_PX`).\n * Масштаб выключается обратно, когда центр за окно уходит в столько раз дальше, чем меняется расстояние (и не меньше `PINCH_RELEASE_MIN_PX`).\n */\nexport const PINCH_RELEASE_RATIO = 2;\nexport const PINCH_RELEASE_MIN_PX = 12;\n\ninterface PinchDelta {\n dx: number;\n dy: number;\n dd: number;\n}\n\n/**\n * A two-finger gesture: shift and/or scale. The scale is the ratio of distances, and the distance between the fingers\n * drifts during an ordinary two-finger shift too, so it cannot be applied just like that.\n * Жест двумя пальцами: сдвиг и/или масштаб. Масштаб считается как отношение расстояний, а расстояние между\n * пальцами при обычном сдвиге двумя пальцами тоже «плывёт», поэтому его нельзя применять просто так.\n *\n * - The distance must change deliberately (`PINCH_ENGAGE_PX`), not build up by drift.\n * - Over the last `PINCH_WINDOW` steps the distance must change more than the centre moves:\n * while the fingers are carried together, the scale does not turn on however the distance floats. We look at the signed sum:\n * the browser sends finger movement one at a time, and \"one moved, the other caught up\" cancels out.\n * - Once the scale is on there is no jump (counting is from the current distance), and small jitter is cut by a\n * dead zone. If the fingers are then carried together, the scale turns off again.\n * - Расстояние должно измениться осознанно (`PINCH_ENGAGE_PX`), а не накопиться дрейфом.\n * - При этом за последние `PINCH_WINDOW` шагов расстояние должно меняться сильнее, чем сдвигается центр:\n * пока пальцы везут вместе, масштаб не включается, как бы расстояние ни плавало. Смотрим на сумму со знаком:\n * браузер присылает движение пальцев по одному, и «один сдвинулся, второй догнал» взаимно сокращается.\n * - Когда масштаб включился, скачка нет (отсчёт идёт от текущего расстояния), а мелкое дрожание отсекается\n * мёртвой зоной. Если потом пальцы повезли вместе, масштаб выключается обратно.\n *\n * The centre shift always works.\n * Сдвиг центра работает всегда.\n */\nexport class PinchTracker {\n private prev: Pinch = { cx: 0, cy: 0, dist: 0 };\n private startDist = 0;\n private baseDist = 0;\n private engaged = false;\n private recent: PinchDelta[] = [];\n\n /**\n * A new set of fingers (a gesture began or the number of fingers changed): count from scratch, there will be no jump.\n * Новый набор пальцев (жест начался или число пальцев изменилось): отсчёт заново, скачка не будет.\n */\n begin(p: Pinch): void {\n this.prev = p;\n this.startDist = p.dist;\n this.baseDist = p.dist;\n this.engaged = false;\n this.recent = [];\n }\n\n get isZooming(): boolean {\n return this.engaged;\n }\n\n update(next: Pinch): PinchStep {\n const step: PinchStep = {\n factor: 1,\n pivot: [this.prev.cx, this.prev.cy],\n pan: [next.cx - this.prev.cx, next.cy - this.prev.cy],\n };\n\n // With one finger (the distance is 0 either way) there is no scale.\n // С одним пальцем (расстояние 0 с любой стороны) масштаба нет.\n const twoFingers = this.startDist > 0 && next.dist > 0 && this.prev.dist > 0;\n this.recent.push({ dx: step.pan[0], dy: step.pan[1], dd: twoFingers ? next.dist - this.prev.dist : 0 });\n if (this.recent.length > PINCH_WINDOW) this.recent.shift();\n this.prev = next;\n if (!twoFingers) return step;\n\n let sx = 0;\n let sy = 0;\n let sd = 0;\n for (const d of this.recent) {\n sx += d.dx;\n sy += d.dy;\n sd += d.dd;\n }\n const netCenter = Math.hypot(sx, sy);\n const netDist = Math.abs(sd);\n\n if (!this.engaged) {\n const intentional = Math.abs(next.dist - this.startDist) >= PINCH_ENGAGE_PX;\n if (intentional && netDist >= PINCH_MIN_NET_PX && netDist >= PINCH_DOMINANCE * netCenter) {\n this.engaged = true;\n this.baseDist = next.dist; // counted from this moment: no jump / отсчёт с этого момента: без скачка\n }\n } else if (netCenter >= PINCH_RELEASE_MIN_PX && netCenter >= PINCH_RELEASE_RATIO * netDist) {\n // The fingers were carried together: the scale turns off, the new threshold is counted from the current distance.\n // Пальцы повезли вместе: масштаб выключаем, новый порог отсчитываем от нынешнего расстояния.\n this.engaged = false;\n this.startDist = next.dist;\n this.baseDist = next.dist;\n } else if (Math.abs(next.dist - this.baseDist) >= PINCH_DEADBAND_PX) {\n step.factor = next.dist / this.baseDist;\n this.baseDist = next.dist;\n }\n return step;\n }\n}\n"],"mappings":";;;;;;;;;;;AAWA,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K;EACT,IAAI,KAAK;EACT,KAAK,MAAM,KAAK,KAAK,QAAQ;GACzB,MAAM,EAAE;GACR,MAAM,EAAE;GACR,MAAM,EAAE;EACZ;EACA,MAAM,YAAY,KAAK,MAAM,IAAI,EAAE;EACnC,MAAM,UAAU,KAAK,IAAI,EAAE;EAE3B,IAAI,CAAC,KAAK,SACc;OAAA,KAAK,IAAI,KAAK,OAAO,KAAK,SAAS,KAAA,MACpC,WAAA,KAA+B,WAAA,IAA6B,WAAW;IACtF,KAAK,UAAU;IACf,KAAK,WAAW,KAAK;GACzB;SACG,IAAI,aAAA,MAAqC,aAAA,IAAmC,SAAS;GAGxF,KAAK,UAAU;GACf,KAAK,YAAY,KAAK;GACtB,KAAK,WAAW,KAAK;EACzB,OAAO,IAAI,KAAK,IAAI,KAAK,OAAO,KAAK,QAAQ,KAAA,KAAwB;GACjE,KAAK,SAAS,KAAK,OAAO,KAAK;GAC/B,KAAK,WAAW,KAAK;EACzB;EACA,OAAO;CACX;AACJ"}
|
|
1
|
+
{"version":3,"file":"gestures.js","names":[],"sources":["../src/gestures.ts"],"sourcesContent":["/**\n * Recognition of touch gestures. Pure logic with no DOM and no timers: time and coordinates come from outside,\n * so everything is covered by tests. Events and timers (long press) live in EditorCanvas.\n * Распознавание сенсорных жестов. Чистая логика без DOM и таймеров: время и координаты приходят снаружи,\n * поэтому всё проверяется тестами. События и таймеры (долгое нажатие) живут в EditorCanvas.\n */\n\n/**\n * By how many px a finger may move and still count as \"standing still\".\n * На сколько px палец может сместиться и всё ещё считаться «стоящим на месте».\n */\nexport const TAP_SLOP_PX = 8;\n/**\n * A touch longer than this is no longer a tap.\n * Дольше этого касание уже не тап.\n */\nexport const TAP_MAX_MS = 300;\n/**\n * How long the finger must be held still for a long press.\n * Сколько надо держать палец неподвижно для долгого нажатия.\n */\nexport const LONG_PRESS_MS = 500;\n/**\n * The second tap must come no later and no further than this from the first.\n * Второй тап должен прийти не позже и не дальше этого от первого.\n */\nexport const DOUBLE_TAP_MS = 300;\nexport const DOUBLE_TAP_RADIUS_PX = 30;\n\nexport interface Sample {\n x: number;\n y: number;\n /**\n * Time, ms (any monotonic scale).\n * Время, мс (любая монотонная шкала).\n */\n t: number;\n}\n\nconst dist = (a: { x: number; y: number }, b: { x: number; y: number }) => Math.hypot(a.x - b.x, a.y - b.y);\n\nexport type TapResult = 'tap' | 'double' | null;\n\n/**\n * Parses a one-finger touch: tap, double tap, movement, readiness of a long press.\n * Разбирает касание одним пальцем: тап, двойной тап, сдвиг, готовность долгого нажатия.\n */\nexport class TapRecognizer {\n private start: Sample | null = null;\n private moved = false;\n private lastTap: Sample | null = null;\n private doubleDown = false;\n\n /**\n * The finger landed. Returns true if this is the second touch of a double tap (it is not finished yet:\n * a drag may follow, as in \"double tap and drag\").\n * Палец лёг. Возвращает true, если это второе касание двойного тапа (оно ещё не закончено:\n * дальше может быть протяжка, как «двойной тап и тянуть»).\n */\n down(s: Sample): boolean {\n this.start = s;\n this.moved = false;\n const prev = this.lastTap;\n this.doubleDown = prev !== null && s.t - prev.t <= DOUBLE_TAP_MS && dist(s, prev) <= DOUBLE_TAP_RADIUS_PX;\n return this.doubleDown;\n }\n\n /**\n * The finger moved. Returns true if it already left the slop (neither a tap nor a long press).\n * Палец сдвинулся. Возвращает true, если он уже ушёл дальше допуска (не тап и не долгое нажатие).\n */\n move(s: Sample): boolean {\n if (this.start && !this.moved && dist(s, this.start) > TAP_SLOP_PX) this.moved = true;\n return this.moved;\n }\n\n get isMoved(): boolean {\n return this.moved;\n }\n\n /**\n * Whether it is time to count the touch as a long press: the finger lies still longer than `LONG_PRESS_MS`.\n * Пора ли считать касание долгим нажатием: палец лежит на месте дольше `LONG_PRESS_MS`.\n */\n longPressDue(now: number): boolean {\n return this.start !== null && !this.moved && now - this.start.t >= LONG_PRESS_MS;\n }\n\n /**\n * The finger was lifted: what that was. After `double` the next tap counts as single again.\n * Палец поднят: что это было. После `double` следующий тап снова считается одиночным.\n */\n up(s: Sample): TapResult {\n const start = this.start;\n this.start = null;\n if (!start) return null;\n\n this.move(s);\n if (this.moved || s.t - start.t > TAP_MAX_MS) {\n this.lastTap = null;\n return null;\n }\n if (this.doubleDown) {\n this.lastTap = null;\n return 'double';\n }\n this.lastTap = s;\n return 'tap';\n }\n\n /**\n * The gesture turned out to be something else (a long press, a pinch, an interruption): forget both the current touch and the previous tap.\n * Жест оказался чем-то другим (долгое нажатие, щипок, прерывание): забываем и текущее касание, и предыдущий тап.\n */\n cancel(): void {\n this.start = null;\n this.lastTap = null;\n this.doubleDown = false;\n }\n}\n\n//--------------------------------------------------\n// Pinch and a two-finger gesture\n// Щипок и жест двумя пальцами\n\ntype Point = { x: number; y: number };\n\nexport interface Pinch {\n /**\n * The centre between the fingers.\n * Центр между пальцами.\n */\n cx: number;\n cy: number;\n /**\n * The distance between the fingers; 0 if there is one finger (then only a shift).\n * Расстояние между пальцами; 0, если палец один (тогда только сдвиг).\n */\n dist: number;\n}\n\nexport function pinchOf(a: Point, b?: Point): Pinch {\n if (!b) return { cx: a.x, cy: a.y, dist: 0 };\n return { cx: (a.x + b.x) / 2, cy: (a.y + b.y) / 2, dist: dist(a, b) };\n}\n\nexport interface PinchStep {\n /**\n * By how many times to change the scale.\n * Во сколько раз изменить масштаб.\n */\n factor: number;\n /**\n * Around which point (the centre before the step).\n * Вокруг какой точки (центр до шага).\n */\n pivot: [number, number];\n /**\n * By how much to shift the camera after the scale.\n * На сколько сдвинуть камеру после масштаба.\n */\n pan: [number, number];\n}\n\n/**\n * Until the distance between the fingers has changed by this much, the gesture counts as a plain shift: the scale is not touched.\n * Пока расстояние между пальцами не изменилось на столько, жест считается просто сдвигом: масштаб не трогаем.\n */\nexport const PINCH_ENGAGE_PX = 20;\n/**\n * Distance changes smaller than this count as finger jitter and are ignored.\n * Изменения расстояния мельче этого считаем дрожанием пальцев и игнорируем.\n */\nexport const PINCH_DEADBAND_PX = 1.5;\n/**\n * How many last steps we look at when deciding \"shifting or scaling\".\n * Сколько последних шагов смотрим, решая «сдвигают или масштабируют».\n */\nexport const PINCH_WINDOW = 6;\n/**\n * To turn the scale on, the distance over the window must change at least as much as the centre moves, and at least this much.\n * Для включения масштаба расстояние за окно должно меняться не меньше, чем сдвигается центр, и не меньше этого.\n */\nexport const PINCH_DOMINANCE = 1;\nexport const PINCH_MIN_NET_PX = 4;\n/**\n * The scale turns off again when the centre moves this many times further than the distance changes over the window (and at least `PINCH_RELEASE_MIN_PX`).\n * Масштаб выключается обратно, когда центр за окно уходит в столько раз дальше, чем меняется расстояние (и не меньше `PINCH_RELEASE_MIN_PX`).\n */\nexport const PINCH_RELEASE_RATIO = 2;\nexport const PINCH_RELEASE_MIN_PX = 12;\n\ninterface PinchDelta {\n dx: number;\n dy: number;\n dd: number;\n}\n\n/**\n * A two-finger gesture: shift and/or scale. The scale is the ratio of distances, and the distance between the fingers\n * drifts during an ordinary two-finger shift too, so it cannot be applied just like that.\n * Жест двумя пальцами: сдвиг и/или масштаб. Масштаб считается как отношение расстояний, а расстояние между\n * пальцами при обычном сдвиге двумя пальцами тоже «плывёт», поэтому его нельзя применять просто так.\n *\n * - The distance must change deliberately (`PINCH_ENGAGE_PX`), not build up by drift.\n * - Over the last `PINCH_WINDOW` steps the distance must change more than the centre moves:\n * while the fingers are carried together, the scale does not turn on however the distance floats. We look at the signed sum:\n * the browser sends finger movement one at a time, and \"one moved, the other caught up\" cancels out.\n * - Once the scale is on there is no jump (counting is from the current distance), and small jitter is cut by a\n * dead zone. If the fingers are then carried together, the scale turns off again.\n * - Расстояние должно измениться осознанно (`PINCH_ENGAGE_PX`), а не накопиться дрейфом.\n * - При этом за последние `PINCH_WINDOW` шагов расстояние должно меняться сильнее, чем сдвигается центр:\n * пока пальцы везут вместе, масштаб не включается, как бы расстояние ни плавало. Смотрим на сумму со знаком:\n * браузер присылает движение пальцев по одному, и «один сдвинулся, второй догнал» взаимно сокращается.\n * - Когда масштаб включился, скачка нет (отсчёт идёт от текущего расстояния), а мелкое дрожание отсекается\n * мёртвой зоной. Если потом пальцы повезли вместе, масштаб выключается обратно.\n *\n * The centre shift always works.\n * Сдвиг центра работает всегда.\n */\nexport class PinchTracker {\n private prev: Pinch = { cx: 0, cy: 0, dist: 0 };\n private startDist = 0;\n private baseDist = 0;\n private engaged = false;\n private recent: PinchDelta[] = [];\n\n /**\n * A new set of fingers (a gesture began or the number of fingers changed): count from scratch, there will be no jump.\n * Новый набор пальцев (жест начался или число пальцев изменилось): отсчёт заново, скачка не будет.\n */\n begin(p: Pinch): void {\n this.prev = p;\n this.startDist = p.dist;\n this.baseDist = p.dist;\n this.engaged = false;\n this.recent = [];\n }\n\n get isZooming(): boolean {\n return this.engaged;\n }\n\n update(next: Pinch): PinchStep {\n const step: PinchStep = {\n factor: 1,\n pivot: [this.prev.cx, this.prev.cy],\n pan: [next.cx - this.prev.cx, next.cy - this.prev.cy],\n };\n\n // With one finger (the distance is 0 either way) there is no scale.\n // С одним пальцем (расстояние 0 с любой стороны) масштаба нет.\n const twoFingers = this.startDist > 0 && next.dist > 0 && this.prev.dist > 0;\n this.recent.push({ dx: step.pan[0], dy: step.pan[1], dd: twoFingers ? next.dist - this.prev.dist : 0 });\n if (this.recent.length > PINCH_WINDOW) this.recent.shift();\n this.prev = next;\n if (!twoFingers) return step;\n\n let sx = 0;\n let sy = 0;\n let sd = 0;\n for (const d of this.recent) {\n sx += d.dx;\n sy += d.dy;\n sd += d.dd;\n }\n const netCenter = Math.hypot(sx, sy);\n const netDist = Math.abs(sd);\n\n if (!this.engaged) {\n const intentional = Math.abs(next.dist - this.startDist) >= PINCH_ENGAGE_PX;\n if (intentional && netDist >= PINCH_MIN_NET_PX && netDist >= PINCH_DOMINANCE * netCenter) {\n this.engaged = true;\n this.baseDist = next.dist; // counted from this moment: no jump / отсчёт с этого момента: без скачка\n }\n } else if (netCenter >= PINCH_RELEASE_MIN_PX && netCenter >= PINCH_RELEASE_RATIO * netDist) {\n // The fingers were carried together: the scale turns off, the new threshold is counted from the current distance.\n // Пальцы повезли вместе: масштаб выключаем, новый порог отсчитываем от нынешнего расстояния.\n this.engaged = false;\n this.startDist = next.dist;\n this.baseDist = next.dist;\n } else if (Math.abs(next.dist - this.baseDist) >= PINCH_DEADBAND_PX) {\n step.factor = next.dist / this.baseDist;\n this.baseDist = next.dist;\n }\n return step;\n }\n}\n\n//--------------------------------------------------\n// Swipe: a row that slides open to show its actions, a sheet pulled down\n// Свайп: строка, которая отъезжает и показывает действия, лист, который тянут вниз\n\n/**\n * How far the finger moves before the intent is decided: a swipe along the axis, or a scroll across it.\n * Сколько палец проходит, прежде чем решается намерение: свайп вдоль оси или прокрутка поперёк.\n */\nexport const SWIPE_SLOP_PX = 10;\n/**\n * A release faster than this (px/ms) is a fling: it goes on in its direction whatever the offset.\n * Отпускание быстрее этого (px/мс) — бросок: он продолжается в своём направлении при любом сдвиге.\n */\nexport const SWIPE_FLING_PX_PER_MS = 0.4;\n/**\n * The release speed is measured over this last stretch of the gesture, ms.\n * Скорость отпускания меряется на этом последнем отрезке жеста, мс.\n */\nexport const SWIPE_VELOCITY_WINDOW_MS = 100;\n\n/**\n * `pending` — not decided yet (inside the slop); `swipe` — along the axis, the app moves the row; `scroll` — across,\n * the gesture belongs to the page and the tracker ignores it until the next `down`.\n * `pending` — ещё не решено (в пределах допуска); `swipe` — вдоль оси, приложение двигает строку; `scroll` — поперёк,\n * жест принадлежит странице, и трекер его игнорирует до следующего `down`.\n */\nexport type SwipeIntent = 'pending' | 'swipe' | 'scroll';\n\nexport interface SwipeStep {\n intent: SwipeIntent;\n /**\n * Where the row stands now: the offset it had at `down` plus the travel since the swipe engaged (so it does not\n * jump by the slop).\n * Где строка сейчас: сдвиг на момент `down` плюс путь с момента, как свайп включился (поэтому без скачка на допуск).\n */\n offset: number;\n}\n\nexport interface SwipeRelease {\n offset: number;\n /** px/ms along the axis, + to the right / down. / px/мс вдоль оси, + вправо / вниз. */\n velocity: number;\n}\n\n/**\n * Tells a swipe from a scroll and follows it. Pure logic, as the other recognizers: the app feeds it pointer samples,\n * moves the element by `offset` and, on release, asks `settleOpen` where the element should come to rest.\n * Отличает свайп от прокрутки и ведёт его. Чистая логика, как остальные распознаватели: приложение подаёт отсчёты\n * указателя, двигает элемент на `offset`, а при отпускании спрашивает `settleOpen`, где элементу остановиться.\n */\nexport class SwipeTracker {\n private start: Sample | null = null;\n private from = 0;\n private engage: Sample | null = null;\n private intent: SwipeIntent = 'pending';\n private trail: Sample[] = [];\n\n constructor(\n private readonly axis: 'x' | 'y' = 'x',\n private readonly slop: number = SWIPE_SLOP_PX,\n ) {}\n\n private along(s: Sample): number {\n return this.axis === 'x' ? s.x : s.y;\n }\n\n private across(s: Sample): number {\n return this.axis === 'x' ? s.y : s.x;\n }\n\n /**\n * The finger landed. `from` is where the row already stands (0 closed, or its open offset).\n * Палец лёг. `from` — где строка уже стоит (0 — закрыта, или её открытый сдвиг).\n */\n down(s: Sample, from = 0): void {\n this.start = s;\n this.from = from;\n this.engage = null;\n this.intent = 'pending';\n this.trail = [s];\n }\n\n move(s: Sample): SwipeStep {\n const start = this.start;\n if (!start || this.intent === 'scroll') return { intent: this.intent, offset: this.from };\n\n if (this.intent === 'pending') {\n const da = Math.abs(this.along(s) - this.along(start));\n const dc = Math.abs(this.across(s) - this.across(start));\n if (Math.max(da, dc) <= this.slop) return { intent: 'pending', offset: this.from };\n // the axis wins only when it leads: a diagonal goes to the page / ось побеждает, только если ведёт: диагональ — странице\n this.intent = da > dc ? 'swipe' : 'scroll';\n if (this.intent === 'scroll') return { intent: 'scroll', offset: this.from };\n this.engage = s;\n }\n\n this.trail.push(s);\n while (this.trail.length > 2 && s.t - this.trail[0]!.t > SWIPE_VELOCITY_WINDOW_MS) this.trail.shift();\n return { intent: 'swipe', offset: this.from + this.along(s) - this.along(this.engage!) };\n }\n\n /**\n * The finger was lifted. Null unless it was a swipe.\n * Палец поднят. Null, если это был не свайп.\n */\n up(s: Sample): SwipeRelease | null {\n const step = this.move(s);\n const swiped = this.intent === 'swipe';\n const first = this.trail[0];\n this.start = null;\n if (!swiped || !first) return null;\n const dt = s.t - first.t;\n const velocity = dt > 0 ? (this.along(s) - this.along(first)) / dt : 0;\n return { offset: step.offset, velocity };\n }\n\n cancel(): void {\n this.start = null;\n this.intent = 'pending';\n this.trail = [];\n }\n\n get current(): SwipeIntent {\n return this.intent;\n }\n}\n\n/**\n * Where a released row comes to rest: closed (0), open at the start (`start`, > 0, actions on the left) or open at\n * the end (`-end`, actions on the right). A fling goes on in its direction, one stop at a time (an open row flung\n * back closes, it does not fly to the other side); otherwise the nearest stop wins.\n * Где отпущенная строка останавливается: закрыта (0), открыта в начале (`start`, > 0, действия слева) или в конце\n * (`-end`, действия справа). Бросок продолжается в своём направлении на одну остановку (открытая строка, брошенная\n * обратно, закрывается, а не улетает на другую сторону); иначе побеждает ближайшая остановка.\n */\nexport function settleOpen(\n release: SwipeRelease,\n open: { start?: number; end?: number },\n fling: number = SWIPE_FLING_PX_PER_MS,\n): number {\n const stops = [0];\n if (open.start) stops.push(open.start);\n if (open.end) stops.push(-open.end);\n stops.sort((a, b) => a - b);\n\n const { offset, velocity } = release;\n if (Math.abs(velocity) >= fling) {\n // the stop beyond the offset in the direction of the fling, or the last one / остановка за сдвигом по ходу броска\n const ahead = velocity > 0 ? stops.filter((p) => p > offset) : stops.filter((p) => p < offset).reverse();\n return ahead[0] ?? (velocity > 0 ? stops[stops.length - 1]! : stops[0]!);\n }\n return stops.reduce((best, p) => (Math.abs(p - offset) < Math.abs(best - offset) ? p : best), 0);\n}\n"],"mappings":";;;;;;;;;;;AAWA,IAAa,cAAc;;;;;AAK3B,IAAa,aAAa;;;;;AAK1B,IAAa,gBAAgB;;;;;AAK7B,IAAa,gBAAgB;AAC7B,IAAa,uBAAuB;AAYpC,IAAM,QAAQ,GAA6B,MAAgC,KAAK,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC;;;;;AAQ1G,IAAa,gBAAb,MAA2B;CACvB,QAA+B;CAC/B,QAAgB;CACh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a;CAC7B,IAAI,KAAK,IAAI,QAAQ,KAAK,OAGtB,QADc,WAAW,IAAI,MAAM,QAAQ,MAAM,IAAI,MAAM,IAAI,MAAM,QAAQ,MAAM,IAAI,MAAM,CAAC,CAAC,QAAQ,EAAA,CAC1F,OAAO,WAAW,IAAI,MAAM,MAAM,SAAS,KAAM,MAAM;CAExE,OAAO,MAAM,QAAQ,MAAM,MAAO,KAAK,IAAI,IAAI,MAAM,IAAI,KAAK,IAAI,OAAO,MAAM,IAAI,IAAI,MAAO,CAAC;AACnG"}
|
package/dist/ids.d.ts
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* A unique id with a prefix; `taken` lets you skip ids already in use (for example, loaded from a file).
|
|
3
|
+
* The counter starts from zero on every page load: good for ids that live inside one document (the nodes of a graph),
|
|
4
|
+
* not for records that are stored or synced. For those use `uuid()`.
|
|
3
5
|
* Уникальный id с префиксом; `taken` позволяет пропустить уже занятые (например, загруженные из файла).
|
|
6
|
+
* Счётчик начинается с нуля при каждой загрузке страницы: годится для id внутри одного документа (узлы графа), но не
|
|
7
|
+
* для записей, которые хранятся или синхронизируются. Для них — `uuid()`.
|
|
4
8
|
*/
|
|
5
9
|
export declare function uid(prefix: string, taken?: (id: string) => boolean): string;
|
|
10
|
+
/**
|
|
11
|
+
* A random UUID v4, unique across loads, tabs and devices: for records that are stored or synced.
|
|
12
|
+
* `crypto.randomUUID` where there is one; outside a secure context (plain http on a LAN address) it is missing, so the
|
|
13
|
+
* same v4 is built from `crypto.getRandomValues`, and only without Web Crypto at all from `Math.random`.
|
|
14
|
+
* Случайный UUID v4, уникальный между загрузками, вкладками и устройствами: для записей, которые хранятся или
|
|
15
|
+
* синхронизируются. `crypto.randomUUID`, где он есть; вне безопасного контекста (http по адресу в локальной сети) его
|
|
16
|
+
* нет, поэтому тот же v4 собирается из `crypto.getRandomValues`, а без Web Crypto совсем — из `Math.random`.
|
|
17
|
+
*/
|
|
18
|
+
export declare function uuid(): string;
|
package/dist/ids.js
CHANGED
|
@@ -2,7 +2,11 @@
|
|
|
2
2
|
var counter = 0;
|
|
3
3
|
/**
|
|
4
4
|
* A unique id with a prefix; `taken` lets you skip ids already in use (for example, loaded from a file).
|
|
5
|
+
* The counter starts from zero on every page load: good for ids that live inside one document (the nodes of a graph),
|
|
6
|
+
* not for records that are stored or synced. For those use `uuid()`.
|
|
5
7
|
* Уникальный id с префиксом; `taken` позволяет пропустить уже занятые (например, загруженные из файла).
|
|
8
|
+
* Счётчик начинается с нуля при каждой загрузке страницы: годится для id внутри одного документа (узлы графа), но не
|
|
9
|
+
* для записей, которые хранятся или синхронизируются. Для них — `uuid()`.
|
|
6
10
|
*/
|
|
7
11
|
function uid(prefix, taken = () => false) {
|
|
8
12
|
let id;
|
|
@@ -11,7 +15,27 @@ function uid(prefix, taken = () => false) {
|
|
|
11
15
|
while (taken(id));
|
|
12
16
|
return id;
|
|
13
17
|
}
|
|
18
|
+
var hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
19
|
+
/**
|
|
20
|
+
* A random UUID v4, unique across loads, tabs and devices: for records that are stored or synced.
|
|
21
|
+
* `crypto.randomUUID` where there is one; outside a secure context (plain http on a LAN address) it is missing, so the
|
|
22
|
+
* same v4 is built from `crypto.getRandomValues`, and only without Web Crypto at all from `Math.random`.
|
|
23
|
+
* Случайный UUID v4, уникальный между загрузками, вкладками и устройствами: для записей, которые хранятся или
|
|
24
|
+
* синхронизируются. `crypto.randomUUID`, где он есть; вне безопасного контекста (http по адресу в локальной сети) его
|
|
25
|
+
* нет, поэтому тот же v4 собирается из `crypto.getRandomValues`, а без Web Crypto совсем — из `Math.random`.
|
|
26
|
+
*/
|
|
27
|
+
function uuid() {
|
|
28
|
+
const c = globalThis.crypto;
|
|
29
|
+
if (typeof c?.randomUUID === "function") return c.randomUUID();
|
|
30
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
31
|
+
if (typeof c?.getRandomValues === "function") c.getRandomValues(bytes);
|
|
32
|
+
else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
33
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
34
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
35
|
+
const h = hex(bytes);
|
|
36
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
37
|
+
}
|
|
14
38
|
//#endregion
|
|
15
|
-
export { uid };
|
|
39
|
+
export { uid, uuid };
|
|
16
40
|
|
|
17
41
|
//# sourceMappingURL=ids.js.map
|
package/dist/ids.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ids.js","names":[],"sources":["../src/ids.ts"],"sourcesContent":["let counter = 0;\n\n/**\n * A unique id with a prefix; `taken` lets you skip ids already in use (for example, loaded from a file).\n * Уникальный id с префиксом; `taken` позволяет пропустить уже занятые (например, загруженные из файла).\n */\nexport function uid(prefix: string, taken: (id: string) => boolean = () => false): string {\n let id: string;\n do id = `${prefix}${++counter}`;\n while (taken(id));\n return id;\n}\n"],"mappings":";AAAA,IAAI,UAAU
|
|
1
|
+
{"version":3,"file":"ids.js","names":[],"sources":["../src/ids.ts"],"sourcesContent":["let counter = 0;\n\n/**\n * A unique id with a prefix; `taken` lets you skip ids already in use (for example, loaded from a file).\n * The counter starts from zero on every page load: good for ids that live inside one document (the nodes of a graph),\n * not for records that are stored or synced. For those use `uuid()`.\n * Уникальный id с префиксом; `taken` позволяет пропустить уже занятые (например, загруженные из файла).\n * Счётчик начинается с нуля при каждой загрузке страницы: годится для id внутри одного документа (узлы графа), но не\n * для записей, которые хранятся или синхронизируются. Для них — `uuid()`.\n */\nexport function uid(prefix: string, taken: (id: string) => boolean = () => false): string {\n let id: string;\n do id = `${prefix}${++counter}`;\n while (taken(id));\n return id;\n}\n\nconst hex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n\n/**\n * A random UUID v4, unique across loads, tabs and devices: for records that are stored or synced.\n * `crypto.randomUUID` where there is one; outside a secure context (plain http on a LAN address) it is missing, so the\n * same v4 is built from `crypto.getRandomValues`, and only without Web Crypto at all from `Math.random`.\n * Случайный UUID v4, уникальный между загрузками, вкладками и устройствами: для записей, которые хранятся или\n * синхронизируются. `crypto.randomUUID`, где он есть; вне безопасного контекста (http по адресу в локальной сети) его\n * нет, поэтому тот же v4 собирается из `crypto.getRandomValues`, а без Web Crypto совсем — из `Math.random`.\n */\nexport function uuid(): string {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (typeof c?.randomUUID === 'function') return c.randomUUID();\n\n const bytes = new Uint8Array(16);\n if (typeof c?.getRandomValues === 'function') c.getRandomValues(bytes);\n else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);\n bytes[6] = (bytes[6]! & 0x0f) | 0x40; // version 4 / версия 4\n bytes[8] = (bytes[8]! & 0x3f) | 0x80; // variant 10 / вариант 10\n const h = hex(bytes);\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n}\n"],"mappings":";AAAA,IAAI,UAAU;;;;;;;;;AAUd,SAAgB,IAAI,QAAgB,cAAuC,OAAe;CACtF,IAAI;CACJ;EAAG,KAAK,GAAG,SAAS,EAAE;QACf,MAAM,EAAE;CACf,OAAO;AACX;AAEA,IAAM,OAAO,UAAsB,MAAM,KAAK,QAAQ,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;;;;;;;;;AAUpG,SAAgB,OAAe;CAC3B,MAAM,IAAK,WAAmC;CAC9C,IAAI,OAAO,GAAG,eAAe,YAAY,OAAO,EAAE,WAAW;CAE7D,MAAM,wBAAQ,IAAI,WAAW,EAAE;CAC/B,IAAI,OAAO,GAAG,oBAAoB,YAAY,EAAE,gBAAgB,KAAK;MAChE,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK,MAAM,KAAK,KAAK,MAAM,KAAK,OAAO,IAAI,GAAG;CAC3E,MAAM,KAAM,MAAM,KAAM,KAAQ;CAChC,MAAM,KAAM,MAAM,KAAM,KAAQ;CAChC,MAAM,IAAI,IAAI,KAAK;CACnB,OAAO,GAAG,EAAE,MAAM,GAAG,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,EAAE,EAAE,GAAG,EAAE,MAAM,IAAI,EAAE,EAAE,GAAG,EAAE,MAAM,IAAI,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE;AACjG"}
|
package/dist/session.d.ts
CHANGED
|
@@ -52,7 +52,13 @@ export interface SessionOptions<D, K extends string> {
|
|
|
52
52
|
get(): D;
|
|
53
53
|
set(doc: D): void;
|
|
54
54
|
};
|
|
55
|
-
|
|
55
|
+
/**
|
|
56
|
+
* The view of a canvas editor: saved with the document and brought back on open. Leave it out for a document
|
|
57
|
+
* without one (a list of notes): `serialize` then gets `undefined`, and a `view` from `parse` is ignored.
|
|
58
|
+
* Вид редактора-холста: сохраняется с документом и возвращается при открытии. Не задавайте для документа без него
|
|
59
|
+
* (список заметок): тогда `serialize` получает `undefined`, а `view` из `parse` пропускается.
|
|
60
|
+
*/
|
|
61
|
+
camera?: {
|
|
56
62
|
get(): Camera;
|
|
57
63
|
set(camera: Camera): void;
|
|
58
64
|
};
|
|
@@ -63,10 +69,15 @@ export interface SessionOptions<D, K extends string> {
|
|
|
63
69
|
};
|
|
64
70
|
empty(): D;
|
|
65
71
|
/**
|
|
66
|
-
* How many
|
|
67
|
-
* Сколько
|
|
72
|
+
* How many items are in the document (nodes, notes): substituted into the message about opening a file.
|
|
73
|
+
* Сколько элементов в документе (узлов, заметок): подставляется в сообщение об открытии файла.
|
|
74
|
+
*/
|
|
75
|
+
countItems?(doc: D): number;
|
|
76
|
+
/**
|
|
77
|
+
* @deprecated The old name of `countItems`; still read when `countItems` is not given.
|
|
78
|
+
* Старое имя `countItems`; читается, если `countItems` не задан.
|
|
68
79
|
*/
|
|
69
|
-
countNodes(doc: D): number;
|
|
80
|
+
countNodes?(doc: D): number;
|
|
70
81
|
keys: SessionKeys<K>;
|
|
71
82
|
/**
|
|
72
83
|
* The document was replaced as a whole (open, new, restore): reset the selection, the drag, the palette.
|
package/dist/session.js
CHANGED
|
@@ -15,6 +15,7 @@ var DEFAULT_AUTOSAVE_MS = 400;
|
|
|
15
15
|
function createDocumentSession(options) {
|
|
16
16
|
const { document: doc, camera, storage, codec, keys } = options;
|
|
17
17
|
const noticeMs = options.noticeMs ?? DEFAULT_NOTICE_MS;
|
|
18
|
+
const count = (d) => (options.countItems ?? options.countNodes)?.(d) ?? 0;
|
|
18
19
|
const autosaveDelay = options.autosaveDelay ?? DEFAULT_AUTOSAVE_MS;
|
|
19
20
|
const notice = ref(null);
|
|
20
21
|
let noticeTimer;
|
|
@@ -38,7 +39,7 @@ function createDocumentSession(options) {
|
|
|
38
39
|
clearTimeout(saveTimer);
|
|
39
40
|
saveTimer = void 0;
|
|
40
41
|
if (!autosaveOn) return;
|
|
41
|
-
if (storage.write(codec.serialize(doc.get(), camera
|
|
42
|
+
if (storage.write(codec.serialize(doc.get(), camera?.get(), false))) saveFailedShown = false;
|
|
42
43
|
else if (!saveFailedShown) {
|
|
43
44
|
saveFailedShown = true;
|
|
44
45
|
showNotice("error", keys.saveFailed);
|
|
@@ -115,7 +116,7 @@ function createDocumentSession(options) {
|
|
|
115
116
|
function load(next, view, resetHistory = false) {
|
|
116
117
|
doc.set(next);
|
|
117
118
|
options.onReset?.();
|
|
118
|
-
if (view) camera.set({
|
|
119
|
+
if (view && camera) camera.set({
|
|
119
120
|
x: view.x,
|
|
120
121
|
y: view.y,
|
|
121
122
|
z: Math.min(2, Math.max(MIN_ZOOM, view.z))
|
|
@@ -129,7 +130,7 @@ function createDocumentSession(options) {
|
|
|
129
130
|
* The file text for download.
|
|
130
131
|
* Текст файла для скачивания.
|
|
131
132
|
*/
|
|
132
|
-
const exportText = () => codec.serialize(doc.get(), camera
|
|
133
|
+
const exportText = () => codec.serialize(doc.get(), camera?.get(), true);
|
|
133
134
|
/**
|
|
134
135
|
* Opens a document from file text. On an error the document is unchanged. The result is shown as a notice.
|
|
135
136
|
* Открывает документ из текста файла. При ошибке документ не меняется. Результат показывается уведомлением.
|
|
@@ -142,9 +143,9 @@ function createDocumentSession(options) {
|
|
|
142
143
|
return result.error;
|
|
143
144
|
}
|
|
144
145
|
load(result.doc, result.view);
|
|
145
|
-
const
|
|
146
|
-
if (result.dropped > 0) showNotice("error", keys.loadedWithDropped, [
|
|
147
|
-
else showNotice("info", keys.loaded, [
|
|
146
|
+
const items = count(result.doc);
|
|
147
|
+
if (result.dropped > 0) showNotice("error", keys.loadedWithDropped, [items, result.dropped]);
|
|
148
|
+
else showNotice("info", keys.loaded, [items]);
|
|
148
149
|
return null;
|
|
149
150
|
}
|
|
150
151
|
function newDocument() {
|
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 { MAX_ZOOM, MIN_ZOOM, type Camera } 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 nodes / {0} — число нод\n loadedWithDropped: K; // {0} is the number of nodes, {1} how many links were 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 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 nodes are in the document: substituted into the message about opening a file.\n * Сколько нод в документе: подставляется в сообщение об открытии файла.\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\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 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.set({ x: view.x, y: view.y, z: Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, view.z)) });\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 nodes = options.countNodes(result.doc);\n if (result.dropped > 0) showNotice('error', keys.loadedWithDropped, [nodes, result.dropped]);\n else showNotice('info', keys.loaded, [nodes]);\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":";;;;AAwFA,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,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;;;;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M,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;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"session.js","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { ref } from 'vue';\nimport { MAX_ZOOM, MIN_ZOOM, type Camera } 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\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: Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, view.z)) });\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":";;;;AAmGA,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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c;EACnB,KAAK,QAAQ,MAAM,GAAG;GAAE,GAAG;GAAG,GAAG;GAAG,GAAG;EAAE,CAAC;EAC1C,WAAW,QAAQ,KAAK,WAAW;CACvC;;;;;CAMA,SAAS,eAAwB;EAC7B,MAAM,OAAO,QAAQ,KAAK;EAC1B,IAAI,SAAS,MAAM,OAAO;EAE1B,MAAM,SAAS,MAAM,MAAM,IAAI;EAC/B,IAAI,CAAC,OAAO,IAAI;GACZ,QAAQ,aAAa,IAAI;GACzB,WAAW,SAAS,KAAK,aAAa;GACtC,OAAO;EACX;EAEA,KAAK,OAAO,KAAK,OAAO,MAAM,IAAI;EAClC,OAAO;CACX;CAEA,OAAO;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ;AACJ"}
|
package/dist/storage.d.ts
CHANGED
|
@@ -13,4 +13,42 @@ export interface SavedStorage {
|
|
|
13
13
|
*/
|
|
14
14
|
backupBroken(text: string): void;
|
|
15
15
|
}
|
|
16
|
-
|
|
16
|
+
/**
|
|
17
|
+
* Why a write failed: the quota is full (the user can free space), storage is denied (private mode, site settings),
|
|
18
|
+
* or something else.
|
|
19
|
+
* Почему запись не удалась: квота заполнена (пользователь может освободить место), хранилище запрещено (приватный
|
|
20
|
+
* режим, настройки сайта) или что-то другое.
|
|
21
|
+
*/
|
|
22
|
+
export type StorageFailure = 'quota' | 'denied' | 'unknown';
|
|
23
|
+
export type StorageWriteResult = {
|
|
24
|
+
ok: true;
|
|
25
|
+
} | {
|
|
26
|
+
ok: false;
|
|
27
|
+
reason: StorageFailure;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* What `createSavedStorage` returns: a `SavedStorage` (so it fits `createDocumentSession` as before) and more.
|
|
31
|
+
* Что возвращает `createSavedStorage`: `SavedStorage` (поэтому подходит `createDocumentSession`, как раньше) и больше.
|
|
32
|
+
*/
|
|
33
|
+
export interface KeyStorage extends SavedStorage {
|
|
34
|
+
/** Like `write`, with the reason of a failure. / Как `write`, с причиной отказа. */
|
|
35
|
+
tryWrite(text: string): StorageWriteResult;
|
|
36
|
+
/** Removes the key; true if storage answered. / Удаляет ключ; true, если хранилище ответило. */
|
|
37
|
+
remove(): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Calls `listener` when another tab of the same site changes this key: the new text, or null when it was removed
|
|
40
|
+
* or the whole storage was cleared. The tab that writes is not told (the browser fires the event in the others).
|
|
41
|
+
* Returns the function that stops listening.
|
|
42
|
+
* Вызывает `listener`, когда другая вкладка того же сайта меняет этот ключ: новый текст или null, если ключ удалён
|
|
43
|
+
* или хранилище очищено целиком. Пишущей вкладке не сообщается (браузер шлёт событие в остальные).
|
|
44
|
+
* Возвращает функцию, которая прекращает слушать.
|
|
45
|
+
*/
|
|
46
|
+
subscribe(listener: (text: string | null) => void): () => void;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The reason behind a storage exception. Browsers name a full quota differently (`QuotaExceededError`, the old
|
|
50
|
+
* Firefox `NS_ERROR_DOM_QUOTA_REACHED`, codes 22 and 1014); a ban is a `SecurityError`.
|
|
51
|
+
* Причина исключения хранилища. Браузеры называют полную квоту по-разному; запрет — это `SecurityError`.
|
|
52
|
+
*/
|
|
53
|
+
export declare function storageFailure(error: unknown): StorageFailure;
|
|
54
|
+
export declare function createSavedStorage(key: string): KeyStorage;
|
package/dist/storage.js
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
//#region src/storage.ts
|
|
2
|
+
/**
|
|
3
|
+
* The reason behind a storage exception. Browsers name a full quota differently (`QuotaExceededError`, the old
|
|
4
|
+
* Firefox `NS_ERROR_DOM_QUOTA_REACHED`, codes 22 and 1014); a ban is a `SecurityError`.
|
|
5
|
+
* Причина исключения хранилища. Браузеры называют полную квоту по-разному; запрет — это `SecurityError`.
|
|
6
|
+
*/
|
|
7
|
+
function storageFailure(error) {
|
|
8
|
+
const e = error;
|
|
9
|
+
if (!e) return "unknown";
|
|
10
|
+
if (e.name === "QuotaExceededError" || e.name === "NS_ERROR_DOM_QUOTA_REACHED" || e.code === 22 || e.code === 1014) return "quota";
|
|
11
|
+
if (e.name === "SecurityError" || e.code === 18) return "denied";
|
|
12
|
+
return "unknown";
|
|
13
|
+
}
|
|
2
14
|
function createSavedStorage(key) {
|
|
3
15
|
const brokenKey = `${key}.broken`;
|
|
16
|
+
function tryWrite(text) {
|
|
17
|
+
try {
|
|
18
|
+
localStorage.setItem(key, text);
|
|
19
|
+
return { ok: true };
|
|
20
|
+
} catch (error) {
|
|
21
|
+
return {
|
|
22
|
+
ok: false,
|
|
23
|
+
reason: storageFailure(error)
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
4
27
|
return {
|
|
5
28
|
read() {
|
|
6
29
|
try {
|
|
@@ -9,9 +32,11 @@ function createSavedStorage(key) {
|
|
|
9
32
|
return null;
|
|
10
33
|
}
|
|
11
34
|
},
|
|
12
|
-
write(text)
|
|
35
|
+
write: (text) => tryWrite(text).ok,
|
|
36
|
+
tryWrite,
|
|
37
|
+
remove() {
|
|
13
38
|
try {
|
|
14
|
-
localStorage.
|
|
39
|
+
localStorage.removeItem(key);
|
|
15
40
|
return true;
|
|
16
41
|
} catch {
|
|
17
42
|
return false;
|
|
@@ -21,10 +46,26 @@ function createSavedStorage(key) {
|
|
|
21
46
|
try {
|
|
22
47
|
localStorage.setItem(brokenKey, text);
|
|
23
48
|
} catch {}
|
|
49
|
+
},
|
|
50
|
+
subscribe(listener) {
|
|
51
|
+
if (typeof window === "undefined") return () => {};
|
|
52
|
+
let area = null;
|
|
53
|
+
try {
|
|
54
|
+
area = localStorage;
|
|
55
|
+
} catch {
|
|
56
|
+
return () => {};
|
|
57
|
+
}
|
|
58
|
+
const onStorage = (event) => {
|
|
59
|
+
if (event.storageArea && event.storageArea !== area) return;
|
|
60
|
+
if (event.key === key) listener(event.newValue);
|
|
61
|
+
else if (event.key === null) listener(null);
|
|
62
|
+
};
|
|
63
|
+
window.addEventListener("storage", onStorage);
|
|
64
|
+
return () => window.removeEventListener("storage", onStorage);
|
|
24
65
|
}
|
|
25
66
|
};
|
|
26
67
|
}
|
|
27
68
|
//#endregion
|
|
28
|
-
export { createSavedStorage };
|
|
69
|
+
export { createSavedStorage, storageFailure };
|
|
29
70
|
|
|
30
71
|
//# sourceMappingURL=storage.js.map
|
package/dist/storage.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage.js","names":[],"sources":["../src/storage.ts"],"sourcesContent":["/**\n * Autosave to localStorage. Any operation may fail: private mode, a site-level ban, a full quota.\n * So errors are swallowed and reported as a result, not thrown.\n * Автосохранение в localStorage. Любая операция может не сработать: приватный режим,\n * запрет сайта, переполнение квоты. Поэтому ошибки глушим и сообщаем результатом, а не исключением.\n */\nexport interface SavedStorage {\n read(): string | null;\n write(text: string): boolean;\n /**\n * What was saved could not be read: the copy is set aside so autosave does not overwrite it.\n * Сохранённое не удалось прочитать: откладываем копию, чтобы автосохранение её не затёрло.\n */\n backupBroken(text: string): void;\n}\n\nexport function createSavedStorage(key: string):
|
|
1
|
+
{"version":3,"file":"storage.js","names":[],"sources":["../src/storage.ts"],"sourcesContent":["/**\n * Autosave to localStorage. Any operation may fail: private mode, a site-level ban, a full quota.\n * So errors are swallowed and reported as a result, not thrown.\n * Автосохранение в localStorage. Любая операция может не сработать: приватный режим,\n * запрет сайта, переполнение квоты. Поэтому ошибки глушим и сообщаем результатом, а не исключением.\n */\nexport interface SavedStorage {\n read(): string | null;\n write(text: string): boolean;\n /**\n * What was saved could not be read: the copy is set aside so autosave does not overwrite it.\n * Сохранённое не удалось прочитать: откладываем копию, чтобы автосохранение её не затёрло.\n */\n backupBroken(text: string): void;\n}\n\n/**\n * Why a write failed: the quota is full (the user can free space), storage is denied (private mode, site settings),\n * or something else.\n * Почему запись не удалась: квота заполнена (пользователь может освободить место), хранилище запрещено (приватный\n * режим, настройки сайта) или что-то другое.\n */\nexport type StorageFailure = 'quota' | 'denied' | 'unknown';\n\nexport type StorageWriteResult = { ok: true } | { ok: false; reason: StorageFailure };\n\n/**\n * What `createSavedStorage` returns: a `SavedStorage` (so it fits `createDocumentSession` as before) and more.\n * Что возвращает `createSavedStorage`: `SavedStorage` (поэтому подходит `createDocumentSession`, как раньше) и больше.\n */\nexport interface KeyStorage extends SavedStorage {\n /** Like `write`, with the reason of a failure. / Как `write`, с причиной отказа. */\n tryWrite(text: string): StorageWriteResult;\n /** Removes the key; true if storage answered. / Удаляет ключ; true, если хранилище ответило. */\n remove(): boolean;\n /**\n * Calls `listener` when another tab of the same site changes this key: the new text, or null when it was removed\n * or the whole storage was cleared. The tab that writes is not told (the browser fires the event in the others).\n * Returns the function that stops listening.\n * Вызывает `listener`, когда другая вкладка того же сайта меняет этот ключ: новый текст или null, если ключ удалён\n * или хранилище очищено целиком. Пишущей вкладке не сообщается (браузер шлёт событие в остальные).\n * Возвращает функцию, которая прекращает слушать.\n */\n subscribe(listener: (text: string | null) => void): () => void;\n}\n\n/**\n * The reason behind a storage exception. Browsers name a full quota differently (`QuotaExceededError`, the old\n * Firefox `NS_ERROR_DOM_QUOTA_REACHED`, codes 22 and 1014); a ban is a `SecurityError`.\n * Причина исключения хранилища. Браузеры называют полную квоту по-разному; запрет — это `SecurityError`.\n */\nexport function storageFailure(error: unknown): StorageFailure {\n const e = error as { name?: string; code?: number } | null;\n if (!e) return 'unknown';\n if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED' || e.code === 22 || e.code === 1014) return 'quota';\n if (e.name === 'SecurityError' || e.code === 18) return 'denied';\n return 'unknown';\n}\n\nexport function createSavedStorage(key: string): KeyStorage {\n const brokenKey = `${key}.broken`;\n\n function tryWrite(text: string): StorageWriteResult {\n try {\n localStorage.setItem(key, text);\n return { ok: true };\n } catch (error) {\n return { ok: false, reason: storageFailure(error) };\n }\n }\n\n return {\n read() {\n try {\n return localStorage.getItem(key);\n } catch {\n return null;\n }\n },\n write: (text) => tryWrite(text).ok,\n tryWrite,\n remove() {\n try {\n localStorage.removeItem(key);\n return true;\n } catch {\n return false;\n }\n },\n backupBroken(text) {\n try {\n localStorage.setItem(brokenKey, text);\n } catch {\n // nothing to do: there is no room\n // нечего делать: места нет\n }\n },\n subscribe(listener) {\n if (typeof window === 'undefined') return () => {};\n let area: Storage | null = null;\n try {\n area = localStorage;\n } catch {\n return () => {}; // storage is denied: no other tab can write it either / хранилище запрещено\n }\n const onStorage = (event: StorageEvent) => {\n // the same key in sessionStorage is someone else's / тот же ключ в sessionStorage — чужой\n if (event.storageArea && event.storageArea !== area) return;\n // key null: the other tab called clear() / key null: другая вкладка вызвала clear()\n if (event.key === key) listener(event.newValue);\n else if (event.key === null) listener(null);\n };\n window.addEventListener('storage', onStorage);\n return () => window.removeEventListener('storage', onStorage);\n },\n };\n}\n"],"mappings":";;;;;;AAmDA,SAAgB,eAAe,OAAgC;CAC3D,MAAM,IAAI;CACV,IAAI,CAAC,GAAG,OAAO;CACf,IAAI,EAAE,SAAS,wBAAwB,EAAE,SAAS,gCAAgC,EAAE,SAAS,MAAM,EAAE,SAAS,MAAM,OAAO;CAC3H,IAAI,EAAE,SAAS,mBAAmB,EAAE,SAAS,IAAI,OAAO;CACxD,OAAO;AACX;AAEA,SAAgB,mBAAmB,KAAyB;CACxD,MAAM,YAAY,GAAG,IAAI;CAEzB,SAAS,SAAS,MAAkC;EAChD,IAAI;GACA,aAAa,QAAQ,KAAK,IAAI;GAC9B,OAAO,EAAE,IAAI,KAAK;EACtB,SAAS,OAAO;GACZ,OAAO;IAAE,IAAI;IAAO,QAAQ,eAAe,KAAK;GAAE;EACtD;CACJ;CAEA,OAAO;EACH,OAAO;GACH,IAAI;IACA,OAAO,aAAa,QAAQ,GAAG;GACnC,QAAQ;IACJ,OAAO;GACX;EACJ;EACA,QAAQ,SAAS,SAAS,IAAI,CAAC,CAAC;EAChC;EACA,SAAS;GACL,IAAI;IACA,aAAa,WAAW,GAAG;IAC3B,OAAO;GACX,QAAQ;IACJ,OAAO;GACX;EACJ;EACA,aAAa,MAAM;GACf,IAAI;IACA,aAAa,QAAQ,WAAW,IAAI;GACxC,QAAQ,CAGR;EACJ;EACA,UAAU,UAAU;GAChB,IAAI,OAAO,WAAW,aAAa,aAAa,CAAC;GACjD,IAAI,OAAuB;GAC3B,IAAI;IACA,OAAO;GACX,QAAQ;IACJ,aAAa,CAAC;GAClB;GACA,MAAM,aAAa,UAAwB;IAEvC,IAAI,MAAM,eAAe,MAAM,gBAAgB,MAAM;IAErD,IAAI,MAAM,QAAQ,KAAK,SAAS,MAAM,QAAQ;SACzC,IAAI,MAAM,QAAQ,MAAM,SAAS,IAAI;GAC9C;GACA,OAAO,iBAAiB,WAAW,SAAS;GAC5C,aAAa,OAAO,oBAAoB,WAAW,SAAS;EAChE;CACJ;AACJ"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@1337exp/taoux",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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",
|
package/skills/taoux/SKILL.md
CHANGED
|
@@ -25,18 +25,18 @@ shells, and TaoUX has **no buttons or fields of its own**. Pair it with TaoUI fo
|
|
|
25
25
|
|---|---|
|
|
26
26
|
| `camera` | pan, zoom around the cursor, screen ↔ world (`zoomAt`) |
|
|
27
27
|
| `history` | `new History(snapshot)`: undo / redo on string snapshots, rapid edits with one `key` merged into one step |
|
|
28
|
-
| `session` | `createDocumentSession(...)`: history + autosave + files + restore + notices for one document; `canUndo` / `canRedo` refs |
|
|
28
|
+
| `session` | `createDocumentSession(...)`: history + autosave + files + restore + notices for one document; `canUndo` / `canRedo` refs. `camera` is optional (a list, not a canvas); count with `countItems` (`countNodes` is its old name) |
|
|
29
29
|
| `commands` | `createCommands([...])`: one registry for menus, shortcuts and palettes (see below) |
|
|
30
30
|
| `hotkeys` | `parseHotkey('Mod+Shift+Z')`, `matchHotkey`, `formatHotkey` (`Ctrl+Shift+Z` / `⇧⌘Z`), `isReservedHotkey`, `bindHotkeys(element, map)` |
|
|
31
|
-
| `storage` | autosave to localStorage that never throws |
|
|
32
|
-
| `file` |
|
|
31
|
+
| `storage` | autosave to localStorage that never throws; `tryWrite` gives the reason (`quota` / `denied`), `remove`, `subscribe` for changes from other tabs |
|
|
32
|
+
| `file` | `downloadText(name, text, mime?)`; `readTextFile(file, limit?)` reads a picked file, refusing a big one |
|
|
33
33
|
| `snap` | soft snapping to a grid, threshold follows the zoom |
|
|
34
34
|
| `wheel` | wheel / trackpad → pan or zoom, like Figma (zoom only with Ctrl / ⌘ or a pinch) |
|
|
35
35
|
| `edgescroll` | auto-scroll near an edge while dragging (`createEdgeScroller`) |
|
|
36
|
-
| `gestures` | tap, double tap, long press, pinch |
|
|
36
|
+
| `gestures` | tap, double tap, long press, pinch; `SwipeTracker` (swipe vs scroll) + `settleOpen` (where a released row rests) |
|
|
37
37
|
| `touch` | `coarse`: is the pointer a finger |
|
|
38
38
|
| `curve` | link paths: Bezier between pins, arrowheads of constant screen size |
|
|
39
|
-
| `ids` | `uid(prefix, taken)` |
|
|
39
|
+
| `ids` | `uuid()` for stored / synced records; `uid(prefix, taken)` restarts from zero on every load, only for ids inside one document |
|
|
40
40
|
| `ease` | easing between curve points (8 families × in / out / in-out, `linear`, `step`, cubic Bezier), `easeValue` |
|
|
41
41
|
| `num` | `clamp`, `roundTo`, `snapTo`, `niceStep`, `ticks` |
|
|
42
42
|
| `palette` | search and groups for a palette of nodes |
|