@1337exp/taoux 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0
4
+
5
+ TaoUI 5.0 is out, and TaoUX follows it, with two new modules for the TaoUI menu bar.
6
+
7
+ ### Modules
8
+
9
+ - **A skill for AI assistants** ships in the package: `skills/taoux/SKILL.md` (the modules, the TaoUI bridge, commands and hotkeys with the menu bar, the usual mistakes). `tests/skill.test.ts` keeps it naming every module.
10
+ - **New `hotkeys`** (tier 0): `parseHotkey` (`Mod+Shift+Z`, aliases, the plus key; a typo throws), `matchHotkey` (`Mod` is ⌘ on Apple and Ctrl elsewhere; a non-Latin layout and Option on a Mac match by the physical key, the digit row too), `formatHotkey` (`Ctrl+Shift+Z` / `⇧⌘Z` in Apple's ⌃⌥⇧⌘ order), `normalizeHotkey`, `isReservedHotkey` (⌘W, ⌘T, ⌘N, Ctrl+Tab; ⌘Q on a Mac, Alt+F4 elsewhere, ⌘R in Safari), `bindHotkeys` (on any element; text fields keep plain keys and text editing by default).
11
+ - **New `commands`** (tier 1): `createCommands` — a registry of commands with `label`, `shortcut`, `icon`, `enabled`, `checked`, `group`, `run`; `toMenu(layout)` builds the menu tree for `TaoMenubar`, `TaoDropdownMenu` and `TaoContextMenu` (the same shape as TaoUI's `TaoMenuItem`, held by a type test, with no dependency on TaoUI); `bind` listens to the shortcuts (a disabled command swallows its key); `check` lists reserved and duplicate shortcuts; `historyCommands` gives Undo / Redo that disable themselves (a document session fits as is).
12
+
13
+ ### TaoUI
14
+
15
+ - **Built and tested against TaoUI 5.0.0** (peer range `^5.0.0`, optional). TaoUI 5 is ESM-only; its styles moved into `tokens/`, `themes/` and `contexts/`, and `TaoTimeline` is now `TaoScrubber`.
16
+ - **The bridge is unchanged for you:** the 13 `--tao-color-*` tokens it points at are the same. Its test no longer depends on one TaoUI file name: it reads every stylesheet of the installed TaoUI, so a future reshuffle cannot break it for the wrong reason.
17
+ - The sandbox, the docs and the consumer smoke test use `TaoScrubber`.
18
+ - `npm run smoke` accepts `TAOUI_TARBALL=<file.tgz>` to test against a TaoUI that is not published yet.
19
+
3
20
  ## 0.1.0
4
21
 
5
22
  The first public release.
package/README.md CHANGED
@@ -39,7 +39,7 @@
39
39
  <td width="50%"><img src="https://raw.githubusercontent.com/1337exp/taoux/main/docs/media/clips/gradienteditor.webp" alt="Gradient editor: adding and moving stops"><br><sub><b>gradienteditor</b> — stops, handles, <code>gradientCss</code></sub></td>
40
40
  </tr>
41
41
  <tr>
42
- <td><img src="https://raw.githubusercontent.com/1337exp/taoux/main/docs/media/clips/playback.webp" alt="Playback: TaoTimeline driven by usePlayback"><br><sub><b>playback</b> — time, loop, speed, seeking; <code>usePlayback</code> + TaoUI <code>TaoTimeline</code></sub></td>
42
+ <td><img src="https://raw.githubusercontent.com/1337exp/taoux/main/docs/media/clips/playback.webp" alt="Playback: TaoScrubber driven by usePlayback"><br><sub><b>playback</b> — time, loop, speed, seeking; <code>usePlayback</code> + TaoUI <code>TaoScrubber</code></sub></td>
43
43
  <td><img src="https://raw.githubusercontent.com/1337exp/taoux/main/docs/media/clips/curvefield.webp" alt="TaoxCurveField: a curve with TaoUI fields"><br><sub><b>curvefield</b> — a curve with TaoUI fields in one component</sub></td>
44
44
  </tr>
45
45
  </table>
@@ -51,7 +51,7 @@ npm install @1337exp/taoux
51
51
  npm install @1337exp/taoui # optional: only for curvefield and the TaoUI bridge
52
52
  ```
53
53
 
54
- Peers: `vue ^3.4` (for the Vue modules) and, optionally, `@1337exp/taoui ^3.2.1`. Modules without Vue need nothing.
54
+ Peers: `vue ^3.4` (for the Vue modules) and, optionally, `@1337exp/taoui ^5.0.0`. Modules without Vue need nothing.
55
55
  ESM only. Import by subpath; there is no root entry on purpose, so nothing you do not import can end up in your bundle.
56
56
 
57
57
  ## With TaoUI
@@ -64,7 +64,7 @@ import '@1337exp/taoux/taoui.css'; // the bridge: --tx-* → --tao-*, t
64
64
  import '@1337exp/taoux/curveeditor.css'; // styles of a Vue module are imported explicitly
65
65
  ```
66
66
 
67
- `taoui.css` is plain CSS with zero specificity and no dependency on TaoUI, so any rule of yours wins. Values then travel through `v-model`: `usePlayback` drives `TaoTimeline`, a TaoUI field edits a curve point, a TaoUI slider sets the opacity of a gradient stop. With code: [docs/taoui.md](docs/taoui.md). Without the bridge the editors keep their dark defaults; `TaoxCurveField` (built from TaoUI components) follows the theme by itself.
67
+ `taoui.css` is plain CSS with zero specificity and no dependency on TaoUI, so any rule of yours wins. Values then travel through `v-model`: `usePlayback` drives `TaoScrubber`, a TaoUI field edits a curve point, a TaoUI slider sets the opacity of a gradient stop. With code: [docs/taoui.md](docs/taoui.md). Without the bridge the editors keep their dark defaults; `TaoxCurveField` (built from TaoUI components) follows the theme by itself.
68
68
 
69
69
  <a id="modules"></a>
70
70
 
@@ -81,6 +81,7 @@ import { History } from '@1337exp/taoux/history';
81
81
  |---|---|---|
82
82
  | `camera` | canvas camera: pan, zoom around the cursor, screen ↔ world | nothing |
83
83
  | `history` | undo/redo on string snapshots, rapid edits merged into one step | nothing |
84
+ | `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`) |
84
85
  | `storage` | autosave to localStorage without exceptions | nothing |
85
86
  | `file` | download text as a file, size limit | DOM |
86
87
  | `snap` | soft snapping to a grid with a threshold that follows the camera zoom | nothing |
@@ -93,6 +94,7 @@ import { History } from '@1337exp/taoux/history';
93
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 |
94
95
  | `num` | small numeric helpers: `clamp`, `roundTo`, `snapTo`, `niceStep`, `ticks` (shared by the curve, gradient and playback modules) | nothing |
95
96
  | `session` | document lifecycle: history, autosave, files, restore, notices | vue (peer) |
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`) |
96
98
  | `palette` | search and groups of nodes for a palette | nothing |
97
99
  | `links` (Vue) | links layer: SVG from ready geometry, `--tx-link-*` | vue (peer) |
98
100
  | `canvas` (Vue) | canvas: mouse and touch gestures, wheel, auto-scroll, keys; the `CanvasHost` contract | vue (peer) |
@@ -103,10 +105,12 @@ import { History } from '@1337exp/taoux/history';
103
105
  | `pins` | row pin positions measured from the DOM: `usePinMeasure`, `createPinRegistry` | vue (peer) |
104
106
  | `i18n` | typed i18n: `createI18n({ locales, fallback, storageKey })` | vue (peer, optional) |
105
107
 
106
- Vue modules (`links`, `canvas`, `curveeditor`, `curvefield`, `gradienteditor`) need their styles imported explicitly: `import '@1337exp/taoux/canvas.css'`. Composite modules (session, palette, links, canvas, pins, curveeditor, gradienteditor, playback) import only primitives. Tier 2, fields (`curvefield`), assemble composites into a ready field on TaoUI components: it is the only tier allowed to import TaoUI, which is why `@1337exp/taoui` is an optional peer dependency. `curvefield` needs both `curveeditor.css` and `curvefield.css`. The `tiers.test.ts` test guards all of that. The canvas contract is described in [docs/canvas.md](docs/canvas.md) ([Русский](docs/canvas.ru.md)); transitions between curve points are in [docs/ease.md](docs/ease.md) ([Русский](docs/ease.ru.md)).
108
+ Vue modules (`links`, `canvas`, `curveeditor`, `curvefield`, `gradienteditor`) need their styles imported explicitly: `import '@1337exp/taoux/canvas.css'`. Composite modules (session, commands, palette, links, canvas, pins, curveeditor, gradienteditor, playback) import only primitives. Tier 2, fields (`curvefield`), assemble composites into a ready field on TaoUI components: it is the only tier allowed to import TaoUI, which is why `@1337exp/taoui` is an optional peer dependency. `curvefield` needs both `curveeditor.css` and `curvefield.css`. The `tiers.test.ts` test guards all of that. The canvas contract is described in [docs/canvas.md](docs/canvas.md) ([Русский](docs/canvas.ru.md)); transitions between curve points are in [docs/ease.md](docs/ease.md) ([Русский](docs/ease.ru.md)).
107
109
 
108
110
  The rule: a module lands here when a second project needs it. A module's core knows nothing about Vue or the DOM unless that is its job.
109
111
 
112
+ **For AI assistants:** the package ships a skill, `skills/taoux/SKILL.md`: how the modules fit together and the mistakes to avoid. Point your assistant at it (Claude Code: copy the folder into `.claude/skills/`).
113
+
110
114
  ## Development
111
115
 
112
116
  ```bash
package/README.ru.md CHANGED
@@ -39,7 +39,7 @@
39
39
  <td width="50%"><img src="https://raw.githubusercontent.com/1337exp/taoux/main/docs/media/clips/gradienteditor.webp" alt="Редактор градиента: добавление и перемещение остановок"><br><sub><b>gradienteditor</b> — остановки, ручки, <code>gradientCss</code></sub></td>
40
40
  </tr>
41
41
  <tr>
42
- <td><img src="https://raw.githubusercontent.com/1337exp/taoux/main/docs/media/clips/playback.webp" alt="Воспроизведение: TaoTimeline ведёт usePlayback"><br><sub><b>playback</b> — время, цикл, скорость, перемотка; <code>usePlayback</code> + <code>TaoTimeline</code> из TaoUI</sub></td>
42
+ <td><img src="https://raw.githubusercontent.com/1337exp/taoux/main/docs/media/clips/playback.webp" alt="Воспроизведение: TaoScrubber ведёт usePlayback"><br><sub><b>playback</b> — время, цикл, скорость, перемотка; <code>usePlayback</code> + <code>TaoScrubber</code> из TaoUI</sub></td>
43
43
  <td><img src="https://raw.githubusercontent.com/1337exp/taoux/main/docs/media/clips/curvefield.webp" alt="TaoxCurveField: кривая с полями TaoUI"><br><sub><b>curvefield</b> — кривая с полями TaoUI в одном компоненте</sub></td>
44
44
  </tr>
45
45
  </table>
@@ -51,7 +51,7 @@ npm install @1337exp/taoux
51
51
  npm install @1337exp/taoui # по желанию: только для curvefield и моста к TaoUI
52
52
  ```
53
53
 
54
- Peer-зависимости: `vue ^3.4` (для Vue-модулей) и, по желанию, `@1337exp/taoui ^3.2.1`. Модулям без Vue ничего не нужно.
54
+ Peer-зависимости: `vue ^3.4` (для Vue-модулей) и, по желанию, `@1337exp/taoui ^5.0.0`. Модулям без Vue ничего не нужно.
55
55
  Только ESM. Импорт по subpath; корневой точки входа нет намеренно, чтобы в сборку не попало ничего неимпортированного.
56
56
 
57
57
  ## С TaoUI
@@ -64,7 +64,7 @@ import '@1337exp/taoux/taoui.css'; // мост: --tx-* → --tao-*, р
64
64
  import '@1337exp/taoux/curveeditor.css'; // стили Vue-модуля подключаются явно
65
65
  ```
66
66
 
67
- `taoui.css` это обычный CSS с нулевой специфичностью и без зависимости от TaoUI, поэтому любое ваше правило главнее. Дальше значения ходят через `v-model`: `usePlayback` ведёт `TaoTimeline`, поле TaoUI правит точку кривой, слайдер TaoUI задаёт прозрачность остановки градиента. С кодом: [docs/taoui.ru.md](docs/taoui.ru.md). Без моста редакторы остаются с тёмными значениями по умолчанию; `TaoxCurveField` (собран из компонентов TaoUI) подстраивается под тему сам.
67
+ `taoui.css` это обычный CSS с нулевой специфичностью и без зависимости от TaoUI, поэтому любое ваше правило главнее. Дальше значения ходят через `v-model`: `usePlayback` ведёт `TaoScrubber`, поле TaoUI правит точку кривой, слайдер TaoUI задаёт прозрачность остановки градиента. С кодом: [docs/taoui.ru.md](docs/taoui.ru.md). Без моста редакторы остаются с тёмными значениями по умолчанию; `TaoxCurveField` (собран из компонентов TaoUI) подстраивается под тему сам.
68
68
 
69
69
  <a id="модули"></a>
70
70
 
@@ -81,6 +81,7 @@ import { History } from '@1337exp/taoux/history';
81
81
  |---|---|---|
82
82
  | `camera` | камера холста: pan, zoom вокруг курсора, экран ↔ мир | нет |
83
83
  | `history` | undo/redo на снимках-строках со склейкой частых правок | нет |
84
+ | `hotkeys` | сочетания клавиш: `parseHotkey('Mod+Shift+Z')`, `matchHotkey` (Mod = ⌘ / Ctrl, нелатинские раскладки по физической клавише), `formatHotkey` (`Ctrl+Shift+Z` / `⇧⌘Z`), `isReservedHotkey` (⌘W, ⌘T, ⌘Q…), `bindHotkeys` на элементе | DOM (для `bindHotkeys`) |
84
85
  | `storage` | автосохранение в localStorage без исключений | нет |
85
86
  | `file` | скачивание текста как файла, лимит размера | DOM |
86
87
  | `snap` | мягкая привязка к сетке с порогом по масштабу камеры | нет |
@@ -93,6 +94,7 @@ import { History } from '@1337exp/taoux/history';
93
94
  | `ease` | функции движения между точками кривой: 8 семейств × in / out / in-out, `linear`, `step`, кубический Безье; `easeValue`, `isEase` (редактор рисует ими, рантайм считает ими же) | нет |
94
95
  | `num` | мелкая числовая математика: `clamp`, `roundTo`, `snapTo`, `niceStep`, `ticks` (общая для кривой, градиента и воспроизведения) | нет |
95
96
  | `session` | жизненный цикл документа: история, автосохранение, файлы, восстановление, уведомления | vue (peer) |
97
+ | `commands` | реестр команд (подпись, сочетание, `enabled`, `checked`, `run`): `toMenu(layout)` строит дерево `TaoMenuItem[]` для `TaoMenubar` / `TaoContextMenu`, `bind` слушает те же сочетания, `historyCommands` даёт Undo / Redo, которые сами становятся недоступными, `check` находит занятые браузером и повторённые сочетания | DOM (для `bind`) |
96
98
  | `palette` | поиск и группы нод для палитры | нет |
97
99
  | `links` (Vue) | слой связей: SVG из готовой геометрии, `--tx-link-*` | vue (peer) |
98
100
  | `canvas` (Vue) | холст: жесты мыши и сенсора, колесо, автопрокрутка, клавиши; контракт `CanvasHost` | vue (peer) |
@@ -103,10 +105,12 @@ import { History } from '@1337exp/taoux/history';
103
105
  | `pins` | позиции пинов-строк, измеренные по DOM: `usePinMeasure`, `createPinRegistry` | vue (peer) |
104
106
  | `i18n` | типизированный i18n: `createI18n({ locales, fallback, storageKey })` | vue (peer, опционально) |
105
107
 
106
- Vue-модули (`links`, `canvas`, `curveeditor`, `curvefield`, `gradienteditor`) требуют явного импорта стилей: `import '@1337exp/taoux/canvas.css'`. Составные модули (session, palette, links, canvas, pins, curveeditor, gradienteditor, playback) импортируют только примитивы. Ярус 2, поля (`curvefield`), собирает составные модули в готовое поле на компонентах TaoUI: только ему можно импортировать TaoUI, поэтому `@1337exp/taoui` это необязательная peer-зависимость. Для `curvefield` нужны оба файла стилей, `curveeditor.css` и `curvefield.css`. Всё это охраняет тест `tiers.test.ts`; контракт холста описан в [docs/canvas.ru.md](docs/canvas.ru.md), переходы между точками кривой в [docs/ease.ru.md](docs/ease.ru.md).
108
+ Vue-модули (`links`, `canvas`, `curveeditor`, `curvefield`, `gradienteditor`) требуют явного импорта стилей: `import '@1337exp/taoux/canvas.css'`. Составные модули (session, commands, palette, links, canvas, pins, curveeditor, gradienteditor, playback) импортируют только примитивы. Ярус 2, поля (`curvefield`), собирает составные модули в готовое поле на компонентах TaoUI: только ему можно импортировать TaoUI, поэтому `@1337exp/taoui` это необязательная peer-зависимость. Для `curvefield` нужны оба файла стилей, `curveeditor.css` и `curvefield.css`. Всё это охраняет тест `tiers.test.ts`; контракт холста описан в [docs/canvas.ru.md](docs/canvas.ru.md), переходы между точками кривой в [docs/ease.ru.md](docs/ease.ru.md).
107
109
 
108
110
  Правило: модуль попадает сюда, когда он понадобился во втором проекте. Ядро модулей не знает про Vue и DOM, если это не их задача.
109
111
 
112
+ **Для ИИ-ассистентов:** в пакете есть skill, `skills/taoux/SKILL.md`: как модули стыкуются и каких ошибок избегать. Покажите его ассистенту (Claude Code: скопируйте папку в `.claude/skills/`).
113
+
110
114
  ## Разработка
111
115
 
112
116
  ```bash
@@ -0,0 +1,134 @@
1
+ import { type BindOptions, type PlatformOptions, type ReservedOptions } from './hotkeys';
2
+ /**
3
+ * A registry of commands: one source for the menu bar, a context menu, a toolbar, a command palette and the keyboard.
4
+ * A command knows its label, its shortcut, whether it can run now and whether it is checked; the menus only show that.
5
+ * Реестр команд: один источник для полосы меню, контекстного меню, панели инструментов, палитры команд и клавиатуры.
6
+ * Команда знает подпись, сочетание, можно ли её сейчас выполнить и отмечена ли она; меню это только показывают.
7
+ */
8
+ type Text = string | (() => string);
9
+ export interface Command {
10
+ id: string;
11
+ /** A function is read every time: a label from `i18n` follows the language. / Функция читается каждый раз: подпись из `i18n` следует за языком. */
12
+ label: Text;
13
+ /**
14
+ * `Mod+S`, or several (the first one is shown). `Mod` is ⌘ on Apple and Ctrl elsewhere.
15
+ * `Mod+S` или несколько (показывается первое). `Mod` — ⌘ у Apple и Ctrl у остальных.
16
+ */
17
+ shortcut?: string | readonly string[];
18
+ /** Icon name for the menu. / Имя иконки для меню. */
19
+ icon?: string;
20
+ /** Can it run now. Default: always. / Можно ли выполнить сейчас. По умолчанию всегда. */
21
+ enabled?: () => boolean;
22
+ /** Makes it a checkbox (a toggle) in the menu. / Делает её чекбоксом (переключателем) в меню. */
23
+ checked?: () => boolean;
24
+ /** With `checked`: a radio of this group. / Вместе с `checked`: радио этой группы. */
25
+ group?: string;
26
+ run: () => void;
27
+ }
28
+ /**
29
+ * The menu entries `toMenu` builds. The same shape as `TaoMenuItem` of TaoUI (a test holds it), declared here,
30
+ * so TaoUX does not depend on TaoUI: pass the result to `TaoMenubar`, `TaoDropdownMenu`, `TaoContextMenu` as is.
31
+ * Пункты меню, которые строит `toMenu`. Та же форма, что у `TaoMenuItem` из TaoUI (это держит тест), объявлена здесь,
32
+ * чтобы TaoUX не зависел от TaoUI: результат передаётся в `TaoMenubar`, `TaoDropdownMenu`, `TaoContextMenu` как есть.
33
+ */
34
+ export type CommandMenuItem = {
35
+ type?: 'item';
36
+ id: string;
37
+ label: string;
38
+ icon?: string;
39
+ shortcut?: string;
40
+ disabled?: boolean;
41
+ items?: CommandMenuItem[];
42
+ } | {
43
+ type: 'checkbox';
44
+ id: string;
45
+ label: string;
46
+ checked: boolean;
47
+ shortcut?: string;
48
+ disabled?: boolean;
49
+ } | {
50
+ type: 'radio';
51
+ id: string;
52
+ group: string;
53
+ label: string;
54
+ checked: boolean;
55
+ shortcut?: string;
56
+ disabled?: boolean;
57
+ } | {
58
+ type: 'label';
59
+ label: string;
60
+ } | {
61
+ type: 'separator';
62
+ };
63
+ /**
64
+ * What a menu is made of: a command id, `'-'` for a separator, a submenu, a group caption.
65
+ * Из чего состоит меню: id команды, `'-'` для разделителя, подменю, подпись группы.
66
+ */
67
+ export type MenuLayoutEntry = string | {
68
+ id?: string;
69
+ label: Text;
70
+ icon?: string;
71
+ items: MenuLayout;
72
+ } | {
73
+ type: 'label';
74
+ label: Text;
75
+ };
76
+ export type MenuLayout = readonly MenuLayoutEntry[];
77
+ export interface ShortcutProblem {
78
+ id: string;
79
+ shortcut: string;
80
+ /** `reserved`: the browser keeps it; `duplicate`: another command has it too (`other`). */
81
+ problem: 'reserved' | 'duplicate';
82
+ other?: string;
83
+ }
84
+ /**
85
+ * Creates the registry. Nothing is reactive by itself: `toMenu` reads `label`, `enabled` and `checked` when called,
86
+ * so in Vue call it inside `computed` and read refs in those functions, and the menu follows the state.
87
+ * Создаёт реестр. Сам по себе ничего не реактивно: `toMenu` читает `label`, `enabled` и `checked` в момент вызова,
88
+ * так что во Vue вызывайте его внутри `computed` и читайте ref-ы в этих функциях, и меню будет следовать за состоянием.
89
+ */
90
+ export declare function createCommands(initial?: readonly Command[], options?: PlatformOptions): {
91
+ add: (command: Command | readonly Command[]) => () => void;
92
+ get: (id: string) => Command | undefined;
93
+ has: (id: string) => boolean;
94
+ list: () => Command[];
95
+ isEnabled: (id: string) => boolean;
96
+ run: (id: string) => boolean;
97
+ label: (id: string) => string | undefined;
98
+ shortcutLabel: (id: string) => string | undefined;
99
+ toMenu: (layout: MenuLayout, path?: string) => CommandMenuItem[];
100
+ bind: (target: EventTarget, bindOptions?: Omit<BindOptions, "mac">) => () => void;
101
+ check: (reservedOptions?: Omit<ReservedOptions, "mac">) => ShortcutProblem[];
102
+ };
103
+ export type Commands = ReturnType<typeof createCommands>;
104
+ type Flag = boolean | {
105
+ readonly value: boolean;
106
+ } | (() => boolean);
107
+ /**
108
+ * What undo/redo needs from a history: a document session (`canUndo` refs) fits as is, a `History` with an `apply` wrapper.
109
+ * Что undo/redo нужно от истории: сессия документа (ref-ы `canUndo`) подходит как есть, `History` — с обёрткой `apply`.
110
+ */
111
+ export interface UndoSource {
112
+ readonly canUndo: Flag;
113
+ readonly canRedo: Flag;
114
+ undo(): unknown;
115
+ redo(): unknown;
116
+ }
117
+ export interface HistoryCommandOptions {
118
+ labels?: {
119
+ undo?: Text;
120
+ redo?: Text;
121
+ };
122
+ }
123
+ /**
124
+ * Undo and Redo as commands (`undo`, `redo`; Mod+Z, Mod+Shift+Z and Mod+Y): they are disabled by themselves when
125
+ * there is nothing to undo or redo, in the menu and on the keyboard.
126
+ * Undo и Redo как команды (`undo`, `redo`; Mod+Z, Mod+Shift+Z и Mod+Y): сами становятся недоступными, когда
127
+ * откатывать или возвращать нечего, и в меню, и на клавиатуре.
128
+ *
129
+ * ```ts
130
+ * commands.add(historyCommands(session, { labels: { undo: () => t('undo'), redo: () => t('redo') } }));
131
+ * ```
132
+ */
133
+ export declare function historyCommands(source: UndoSource, options?: HistoryCommandOptions): Command[];
134
+ export {};
@@ -0,0 +1,189 @@
1
+ import { bindHotkeys, formatHotkey, isApplePlatform, isReservedHotkey, normalizeHotkey } from "./hotkeys.js";
2
+ //#region src/commands.ts
3
+ var text = (value) => typeof value === "function" ? value() : value;
4
+ var shortcuts = (command) => command.shortcut === void 0 ? [] : typeof command.shortcut === "string" ? [command.shortcut] : [...command.shortcut];
5
+ /**
6
+ * Creates the registry. Nothing is reactive by itself: `toMenu` reads `label`, `enabled` and `checked` when called,
7
+ * so in Vue call it inside `computed` and read refs in those functions, and the menu follows the state.
8
+ * Создаёт реестр. Сам по себе ничего не реактивно: `toMenu` читает `label`, `enabled` и `checked` в момент вызова,
9
+ * так что во Vue вызывайте его внутри `computed` и читайте ref-ы в этих функциях, и меню будет следовать за состоянием.
10
+ */
11
+ function createCommands(initial = [], options = {}) {
12
+ const mac = options.mac ?? isApplePlatform();
13
+ const commands = /* @__PURE__ */ new Map();
14
+ /**
15
+ * Adds commands; an id taken twice is an error. Returns the function that removes them again.
16
+ * Добавляет команды; занятый id — ошибка. Возвращает функцию, которая их убирает.
17
+ */
18
+ function add(command) {
19
+ const list = Array.isArray(command) ? command : [command];
20
+ for (const c of list) if (commands.has(c.id)) throw new Error(`commands: "${c.id}" is already registered`);
21
+ list.forEach((c) => commands.set(c.id, c));
22
+ return () => list.forEach((c) => commands.get(c.id) === c && commands.delete(c.id));
23
+ }
24
+ const get = (id) => commands.get(id);
25
+ const isEnabled = (id) => {
26
+ const command = commands.get(id);
27
+ return !!command && (command.enabled?.() ?? true);
28
+ };
29
+ /**
30
+ * Runs the command if it exists and is enabled. Returns whether it ran. Give it to `@select` of a menu.
31
+ * Выполняет команду, если она есть и доступна. Возвращает, выполнилась ли. Отдайте его в `@select` меню.
32
+ */
33
+ function run(id) {
34
+ if (!isEnabled(id)) return false;
35
+ commands.get(id).run();
36
+ return true;
37
+ }
38
+ /** The shortcut label for this platform (`⇧⌘Z` / `Ctrl+Shift+Z`), or undefined. / Подпись сочетания для этой платформы. */
39
+ function shortcutLabel(id) {
40
+ const first = shortcuts(commands.get(id) ?? {})[0];
41
+ return first === void 0 ? void 0 : formatHotkey(first, { mac });
42
+ }
43
+ function item(command) {
44
+ const base = {
45
+ id: command.id,
46
+ label: text(command.label),
47
+ shortcut: shortcutLabel(command.id),
48
+ disabled: !isEnabled(command.id)
49
+ };
50
+ if (command.checked && command.group !== void 0) return {
51
+ type: "radio",
52
+ group: command.group,
53
+ checked: command.checked(),
54
+ ...base
55
+ };
56
+ if (command.checked) return {
57
+ type: "checkbox",
58
+ checked: command.checked(),
59
+ ...base
60
+ };
61
+ return {
62
+ ...base,
63
+ icon: command.icon
64
+ };
65
+ }
66
+ /**
67
+ * Builds the menu tree from a layout. An unknown id is an error (a typo would silently lose a menu entry).
68
+ * For a menu bar the top level is submenus: `[{ id: 'file', label: 'File', items: ['save', '-', 'undo'] }]`.
69
+ * Строит дерево меню по раскладке. Незнакомый id — ошибка (опечатка тихо потеряла бы пункт).
70
+ * Для полосы меню верхний уровень — подменю: `[{ id: 'file', label: 'File', items: ['save', '-', 'undo'] }]`.
71
+ */
72
+ function toMenu(layout, path = "menu") {
73
+ return layout.map((entry, index) => {
74
+ if (entry === "-") return { type: "separator" };
75
+ if (typeof entry === "string") {
76
+ const command = commands.get(entry);
77
+ if (!command) throw new Error(`commands: the menu names "${entry}", which is not registered`);
78
+ return item(command);
79
+ }
80
+ if ("type" in entry) return {
81
+ type: "label",
82
+ label: text(entry.label)
83
+ };
84
+ const id = entry.id ?? `${path}-${index}`;
85
+ return {
86
+ id,
87
+ label: text(entry.label),
88
+ icon: entry.icon,
89
+ items: toMenu(entry.items, id)
90
+ };
91
+ });
92
+ }
93
+ /**
94
+ * Listens to the shortcuts of every registered command on the target (commands added later count too).
95
+ * A disabled command swallows its key and does nothing, so Mod+S never opens the browser's "Save page".
96
+ * Returns the function that stops listening.
97
+ * Слушает сочетания всех зарегистрированных команд на цели (добавленные позже тоже).
98
+ * Недоступная команда глотает свою клавишу и ничего не делает, так что Mod+S не откроет «Сохранить страницу» браузера.
99
+ * Возвращает функцию, которая перестаёт слушать.
100
+ */
101
+ function bind(target, bindOptions = {}) {
102
+ const bindings = () => {
103
+ const map = {};
104
+ for (const command of commands.values()) for (const combo of shortcuts(command)) map[combo] ??= () => {
105
+ run(command.id);
106
+ };
107
+ return map;
108
+ };
109
+ return bindHotkeys(target, bindings, {
110
+ ...bindOptions,
111
+ mac
112
+ });
113
+ }
114
+ /**
115
+ * Shortcuts that will not work: kept by the browser, or given to two commands. Handy in a test of your app.
116
+ * Сочетания, которые не сработают: их держит браузер или они даны двум командам. Удобно в тесте приложения.
117
+ */
118
+ function check(reservedOptions = {}) {
119
+ const problems = [];
120
+ const seen = /* @__PURE__ */ new Map();
121
+ for (const command of commands.values()) for (const shortcut of shortcuts(command)) {
122
+ if (isReservedHotkey(shortcut, {
123
+ ...reservedOptions,
124
+ mac
125
+ })) problems.push({
126
+ id: command.id,
127
+ shortcut,
128
+ problem: "reserved"
129
+ });
130
+ const key = normalizeHotkey(shortcut, { mac });
131
+ const other = seen.get(key);
132
+ if (other !== void 0 && other !== command.id) problems.push({
133
+ id: command.id,
134
+ shortcut,
135
+ problem: "duplicate",
136
+ other
137
+ });
138
+ else seen.set(key, command.id);
139
+ }
140
+ return problems;
141
+ }
142
+ add(initial);
143
+ return {
144
+ add,
145
+ get,
146
+ has: (id) => commands.has(id),
147
+ list: () => [...commands.values()],
148
+ isEnabled,
149
+ run,
150
+ label: (id) => {
151
+ const command = commands.get(id);
152
+ return command ? text(command.label) : void 0;
153
+ },
154
+ shortcutLabel,
155
+ toMenu,
156
+ bind,
157
+ check
158
+ };
159
+ }
160
+ var flag = (value) => typeof value === "function" ? value() : typeof value === "boolean" ? value : value.value;
161
+ /**
162
+ * Undo and Redo as commands (`undo`, `redo`; Mod+Z, Mod+Shift+Z and Mod+Y): they are disabled by themselves when
163
+ * there is nothing to undo or redo, in the menu and on the keyboard.
164
+ * Undo и Redo как команды (`undo`, `redo`; Mod+Z, Mod+Shift+Z и Mod+Y): сами становятся недоступными, когда
165
+ * откатывать или возвращать нечего, и в меню, и на клавиатуре.
166
+ *
167
+ * ```ts
168
+ * commands.add(historyCommands(session, { labels: { undo: () => t('undo'), redo: () => t('redo') } }));
169
+ * ```
170
+ */
171
+ function historyCommands(source, options = {}) {
172
+ return [{
173
+ id: "undo",
174
+ label: options.labels?.undo ?? "Undo",
175
+ shortcut: "Mod+Z",
176
+ enabled: () => flag(source.canUndo),
177
+ run: () => void source.undo()
178
+ }, {
179
+ id: "redo",
180
+ label: options.labels?.redo ?? "Redo",
181
+ shortcut: ["Mod+Shift+Z", "Mod+Y"],
182
+ enabled: () => flag(source.canRedo),
183
+ run: () => void source.redo()
184
+ }];
185
+ }
186
+ //#endregion
187
+ export { createCommands, historyCommands };
188
+
189
+ //# sourceMappingURL=commands.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"commands.js","names":[],"sources":["../src/commands.ts"],"sourcesContent":["import { bindHotkeys, type BindOptions, formatHotkey, type HotkeyHandler, isApplePlatform, isReservedHotkey, normalizeHotkey, type PlatformOptions, type ReservedOptions } from './hotkeys';\n\n/**\n * A registry of commands: one source for the menu bar, a context menu, a toolbar, a command palette and the keyboard.\n * A command knows its label, its shortcut, whether it can run now and whether it is checked; the menus only show that.\n * Реестр команд: один источник для полосы меню, контекстного меню, панели инструментов, палитры команд и клавиатуры.\n * Команда знает подпись, сочетание, можно ли её сейчас выполнить и отмечена ли она; меню это только показывают.\n */\n\ntype Text = string | (() => string);\n\nexport interface Command {\n id: string;\n /** A function is read every time: a label from `i18n` follows the language. / Функция читается каждый раз: подпись из `i18n` следует за языком. */\n label: Text;\n /**\n * `Mod+S`, or several (the first one is shown). `Mod` is ⌘ on Apple and Ctrl elsewhere.\n * `Mod+S` или несколько (показывается первое). `Mod` — ⌘ у Apple и Ctrl у остальных.\n */\n shortcut?: string | readonly string[];\n /** Icon name for the menu. / Имя иконки для меню. */\n icon?: string;\n /** Can it run now. Default: always. / Можно ли выполнить сейчас. По умолчанию всегда. */\n enabled?: () => boolean;\n /** Makes it a checkbox (a toggle) in the menu. / Делает её чекбоксом (переключателем) в меню. */\n checked?: () => boolean;\n /** With `checked`: a radio of this group. / Вместе с `checked`: радио этой группы. */\n group?: string;\n run: () => void;\n}\n\n/**\n * The menu entries `toMenu` builds. The same shape as `TaoMenuItem` of TaoUI (a test holds it), declared here,\n * so TaoUX does not depend on TaoUI: pass the result to `TaoMenubar`, `TaoDropdownMenu`, `TaoContextMenu` as is.\n * Пункты меню, которые строит `toMenu`. Та же форма, что у `TaoMenuItem` из TaoUI (это держит тест), объявлена здесь,\n * чтобы TaoUX не зависел от TaoUI: результат передаётся в `TaoMenubar`, `TaoDropdownMenu`, `TaoContextMenu` как есть.\n */\nexport type CommandMenuItem =\n | { type?: 'item'; id: string; label: string; icon?: string; shortcut?: string; disabled?: boolean; items?: CommandMenuItem[] }\n | { type: 'checkbox'; id: string; label: string; checked: boolean; shortcut?: string; disabled?: boolean }\n | { type: 'radio'; id: string; group: string; label: string; checked: boolean; shortcut?: string; disabled?: boolean }\n | { type: 'label'; label: string }\n | { type: 'separator' };\n\n/**\n * What a menu is made of: a command id, `'-'` for a separator, a submenu, a group caption.\n * Из чего состоит меню: id команды, `'-'` для разделителя, подменю, подпись группы.\n */\nexport type MenuLayoutEntry = string | { id?: string; label: Text; icon?: string; items: MenuLayout } | { type: 'label'; label: Text };\nexport type MenuLayout = readonly MenuLayoutEntry[];\n\nexport interface ShortcutProblem {\n id: string;\n shortcut: string;\n /** `reserved`: the browser keeps it; `duplicate`: another command has it too (`other`). */\n problem: 'reserved' | 'duplicate';\n other?: string;\n}\n\nconst text = (value: Text) => (typeof value === 'function' ? value() : value);\nconst shortcuts = (command: Command) => (command.shortcut === undefined ? [] : typeof command.shortcut === 'string' ? [command.shortcut] : [...command.shortcut]);\n\n/**\n * Creates the registry. Nothing is reactive by itself: `toMenu` reads `label`, `enabled` and `checked` when called,\n * so in Vue call it inside `computed` and read refs in those functions, and the menu follows the state.\n * Создаёт реестр. Сам по себе ничего не реактивно: `toMenu` читает `label`, `enabled` и `checked` в момент вызова,\n * так что во Vue вызывайте его внутри `computed` и читайте ref-ы в этих функциях, и меню будет следовать за состоянием.\n */\nexport function createCommands(initial: readonly Command[] = [], options: PlatformOptions = {}) {\n const mac = options.mac ?? isApplePlatform();\n const commands = new Map<string, Command>();\n\n /**\n * Adds commands; an id taken twice is an error. Returns the function that removes them again.\n * Добавляет команды; занятый id — ошибка. Возвращает функцию, которая их убирает.\n */\n function add(command: Command | readonly Command[]): () => void {\n const list = Array.isArray(command) ? (command as readonly Command[]) : [command as Command];\n for (const c of list) {\n if (commands.has(c.id)) throw new Error(`commands: \"${c.id}\" is already registered`);\n }\n list.forEach((c) => commands.set(c.id, c));\n return () => list.forEach((c) => commands.get(c.id) === c && commands.delete(c.id));\n }\n\n const get = (id: string) => commands.get(id);\n const isEnabled = (id: string) => {\n const command = commands.get(id);\n return !!command && (command.enabled?.() ?? true);\n };\n\n /**\n * Runs the command if it exists and is enabled. Returns whether it ran. Give it to `@select` of a menu.\n * Выполняет команду, если она есть и доступна. Возвращает, выполнилась ли. Отдайте его в `@select` меню.\n */\n function run(id: string): boolean {\n if (!isEnabled(id)) return false;\n commands.get(id)!.run();\n return true;\n }\n\n /** The shortcut label for this platform (`⇧⌘Z` / `Ctrl+Shift+Z`), or undefined. / Подпись сочетания для этой платформы. */\n function shortcutLabel(id: string): string | undefined {\n const first = shortcuts(commands.get(id) ?? ({} as Command))[0];\n return first === undefined ? undefined : formatHotkey(first, { mac });\n }\n\n function item(command: Command): CommandMenuItem {\n const base = { id: command.id, label: text(command.label), shortcut: shortcutLabel(command.id), disabled: !isEnabled(command.id) };\n if (command.checked && command.group !== undefined) return { type: 'radio', group: command.group, checked: command.checked(), ...base };\n if (command.checked) return { type: 'checkbox', checked: command.checked(), ...base };\n return { ...base, icon: command.icon };\n }\n\n /**\n * Builds the menu tree from a layout. An unknown id is an error (a typo would silently lose a menu entry).\n * For a menu bar the top level is submenus: `[{ id: 'file', label: 'File', items: ['save', '-', 'undo'] }]`.\n * Строит дерево меню по раскладке. Незнакомый id — ошибка (опечатка тихо потеряла бы пункт).\n * Для полосы меню верхний уровень — подменю: `[{ id: 'file', label: 'File', items: ['save', '-', 'undo'] }]`.\n */\n function toMenu(layout: MenuLayout, path = 'menu'): CommandMenuItem[] {\n return layout.map((entry, index): CommandMenuItem => {\n if (entry === '-') return { type: 'separator' };\n if (typeof entry === 'string') {\n const command = commands.get(entry);\n if (!command) throw new Error(`commands: the menu names \"${entry}\", which is not registered`);\n return item(command);\n }\n if ('type' in entry) return { type: 'label', label: text(entry.label) };\n const id = entry.id ?? `${path}-${index}`;\n return { id, label: text(entry.label), icon: entry.icon, items: toMenu(entry.items, id) };\n });\n }\n\n /**\n * Listens to the shortcuts of every registered command on the target (commands added later count too).\n * A disabled command swallows its key and does nothing, so Mod+S never opens the browser's \"Save page\".\n * Returns the function that stops listening.\n * Слушает сочетания всех зарегистрированных команд на цели (добавленные позже тоже).\n * Недоступная команда глотает свою клавишу и ничего не делает, так что Mod+S не откроет «Сохранить страницу» браузера.\n * Возвращает функцию, которая перестаёт слушать.\n */\n function bind(target: EventTarget, bindOptions: Omit<BindOptions, 'mac'> = {}): () => void {\n const bindings = () => {\n const map: Record<string, HotkeyHandler> = {};\n for (const command of commands.values()) {\n for (const combo of shortcuts(command)) {\n map[combo] ??= () => {\n run(command.id);\n };\n }\n }\n return map;\n };\n return bindHotkeys(target, bindings, { ...bindOptions, mac });\n }\n\n /**\n * Shortcuts that will not work: kept by the browser, or given to two commands. Handy in a test of your app.\n * Сочетания, которые не сработают: их держит браузер или они даны двум командам. Удобно в тесте приложения.\n */\n function check(reservedOptions: Omit<ReservedOptions, 'mac'> = {}): ShortcutProblem[] {\n const problems: ShortcutProblem[] = [];\n const seen = new Map<string, string>();\n for (const command of commands.values()) {\n for (const shortcut of shortcuts(command)) {\n if (isReservedHotkey(shortcut, { ...reservedOptions, mac })) problems.push({ id: command.id, shortcut, problem: 'reserved' });\n const key = normalizeHotkey(shortcut, { mac });\n const other = seen.get(key);\n if (other !== undefined && other !== command.id) problems.push({ id: command.id, shortcut, problem: 'duplicate', other });\n else seen.set(key, command.id);\n }\n }\n return problems;\n }\n\n add(initial);\n\n return {\n add,\n get,\n has: (id: string) => commands.has(id),\n list: () => [...commands.values()],\n isEnabled,\n run,\n label: (id: string) => {\n const command = commands.get(id);\n return command ? text(command.label) : undefined;\n },\n shortcutLabel,\n toMenu,\n bind,\n check,\n };\n}\n\nexport type Commands = ReturnType<typeof createCommands>;\n\ntype Flag = boolean | { readonly value: boolean } | (() => boolean);\nconst flag = (value: Flag) => (typeof value === 'function' ? value() : typeof value === 'boolean' ? value : value.value);\n\n/**\n * What undo/redo needs from a history: a document session (`canUndo` refs) fits as is, a `History` with an `apply` wrapper.\n * Что undo/redo нужно от истории: сессия документа (ref-ы `canUndo`) подходит как есть, `History` — с обёрткой `apply`.\n */\nexport interface UndoSource {\n readonly canUndo: Flag;\n readonly canRedo: Flag;\n undo(): unknown;\n redo(): unknown;\n}\n\nexport interface HistoryCommandOptions {\n labels?: { undo?: Text; redo?: Text };\n}\n\n/**\n * Undo and Redo as commands (`undo`, `redo`; Mod+Z, Mod+Shift+Z and Mod+Y): they are disabled by themselves when\n * there is nothing to undo or redo, in the menu and on the keyboard.\n * Undo и Redo как команды (`undo`, `redo`; Mod+Z, Mod+Shift+Z и Mod+Y): сами становятся недоступными, когда\n * откатывать или возвращать нечего, и в меню, и на клавиатуре.\n *\n * ```ts\n * commands.add(historyCommands(session, { labels: { undo: () => t('undo'), redo: () => t('redo') } }));\n * ```\n */\nexport function historyCommands(source: UndoSource, options: HistoryCommandOptions = {}): Command[] {\n return [\n { id: 'undo', label: options.labels?.undo ?? 'Undo', shortcut: 'Mod+Z', enabled: () => flag(source.canUndo), run: () => void source.undo() },\n { id: 'redo', label: options.labels?.redo ?? 'Redo', shortcut: ['Mod+Shift+Z', 'Mod+Y'], enabled: () => flag(source.canRedo), run: () => void source.redo() },\n ];\n}\n"],"mappings":";;AA2DA,IAAM,QAAQ,UAAiB,OAAO,UAAU,aAAa,MAAM,IAAI;AACvE,IAAM,aAAa,YAAsB,QAAQ,aAAa,KAAA,IAAY,CAAC,IAAI,OAAO,QAAQ,aAAa,WAAW,CAAC,QAAQ,QAAQ,IAAI,CAAC,GAAG,QAAQ,QAAQ;;;;;;;AAQ/J,SAAgB,eAAe,UAA8B,CAAC,GAAG,UAA2B,CAAC,GAAG;CAC5F,MAAM,MAAM,QAAQ,OAAO,gBAAgB;CAC3C,MAAM,2BAAW,IAAI,IAAqB;;;;;CAM1C,SAAS,IAAI,SAAmD;EAC5D,MAAM,OAAO,MAAM,QAAQ,OAAO,IAAK,UAAiC,CAAC,OAAkB;EAC3F,KAAK,MAAM,KAAK,MACZ,IAAI,SAAS,IAAI,EAAE,EAAE,GAAG,MAAM,IAAI,MAAM,cAAc,EAAE,G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;QACnH,KAAK,IAAI,KAAK,QAAQ,EAAE;EACjC;EAEJ,OAAO;CACX;CAEA,IAAI,OAAO;CAEX,OAAO;EACH;EACA;EACA,MAAM,OAAe,SAAS,IAAI,EAAE;EACpC,YAAY,CAAC,GAAG,SAAS,OAAO,CAAC;EACjC;EACA;EACA,QAAQ,OAAe;GACnB,MAAM,UAAU,SAAS,IAAI,EAAE;GAC/B,OAAO,UAAU,KAAK,QAAQ,KAAK,IAAI,KAAA;EAC3C;EACA;EACA;EACA;EACA;CACJ;AACJ;AAKA,IAAM,QAAQ,UAAiB,OAAO,UAAU,aAAa,MAAM,IAAI,OAAO,UAAU,YAAY,QAAQ,MAAM;;;;;;;;;;;AA2BlH,SAAgB,gBAAgB,QAAoB,UAAiC,CAAC,GAAc;CAChG,OAAO,CACH;EAAE,IAAI;EAAQ,OAAO,QAAQ,QAAQ,QAAQ;EAAQ,UAAU;EAAS,eAAe,KAAK,OAAO,OAAO;EAAG,WAAW,KAAK,OAAO,KAAK;CAAE,GAC3I;EAAE,IAAI;EAAQ,OAAO,QAAQ,QAAQ,QAAQ;EAAQ,UAAU,CAAC,eAAe,OAAO;EAAG,eAAe,KAAK,OAAO,OAAO;EAAG,WAAW,KAAK,OAAO,KAAK;CAAE,CAChK;AACJ"}
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Keyboard shortcuts: parse `Mod+Shift+Z`, match a keydown against it, show it the way the platform writes it,
3
+ * and know which ones the browser never gives to a page. `Mod` is ⌘ on Apple platforms and Ctrl elsewhere,
4
+ * so the data stores `Mod` and not a concrete key.
5
+ * Сочетания клавиш: разобрать `Mod+Shift+Z`, сверить с ним keydown, показать так, как пишет платформа,
6
+ * и знать, какие браузер странице не отдаёт никогда. `Mod` — это ⌘ на платформах Apple и Ctrl на остальных,
7
+ * поэтому в данных хранится `Mod`, а не конкретная клавиша.
8
+ */
9
+ export interface Hotkey {
10
+ /**
11
+ * `event.key` in lower case: `z`, `arrowup`, `escape`, `f2`, `'`, `' '` for the space bar.
12
+ * `event.key` в нижнем регистре: `z`, `arrowup`, `escape`, `f2`, `'`, `' '` для пробела.
13
+ */
14
+ key: string;
15
+ /** ⌘ on Apple, Ctrl elsewhere. / ⌘ у Apple, Ctrl у остальных. */
16
+ mod: boolean;
17
+ ctrl: boolean;
18
+ /** ⌘ / the Windows key. / ⌘ / клавиша Windows. */
19
+ meta: boolean;
20
+ /** Option on Apple. / Option у Apple. */
21
+ alt: boolean;
22
+ shift: boolean;
23
+ }
24
+ export interface PlatformOptions {
25
+ /**
26
+ * Apple platform (⌘ for `Mod`, glyphs in labels). Default: detected from `navigator`, false without one (SSR).
27
+ * Платформа Apple (⌘ для `Mod`, значки в подписях). По умолчанию: из `navigator`, без него (SSR) false.
28
+ */
29
+ mac?: boolean;
30
+ }
31
+ /**
32
+ * Apple platform: macOS, iOS, iPadOS. False on the server.
33
+ * Платформа Apple: macOS, iOS, iPadOS. На сервере false.
34
+ */
35
+ export declare function isApplePlatform(): boolean;
36
+ /**
37
+ * Parses `Mod+Shift+Z`, `Ctrl+Alt+Delete`, `Shift+?`, `Mod++` (the plus key). Case and spaces around `+` do not matter.
38
+ * Throws on an empty combination, an unknown modifier or two keys: a typo in a shortcut is a bug, not data.
39
+ * Разбирает `Mod+Shift+Z`, `Ctrl+Alt+Delete`, `Shift+?`, `Mod++` (клавиша плюс). Регистр и пробелы вокруг `+` не важны.
40
+ * Бросает ошибку на пустое сочетание, незнакомый модификатор или две клавиши: опечатка в сочетании — это баг, а не данные.
41
+ */
42
+ export declare function parseHotkey(combo: string): Hotkey;
43
+ export interface KeyLike {
44
+ key: string;
45
+ code?: string;
46
+ ctrlKey: boolean;
47
+ metaKey: boolean;
48
+ altKey: boolean;
49
+ shiftKey: boolean;
50
+ }
51
+ /**
52
+ * Does this keydown press the combination?
53
+ * A letter or a digit is also found by its physical key when the layout gives a non-Latin character (Ctrl+Я is Ctrl+Z
54
+ * on a Russian layout, Option+S on a Mac gives ß), but not on another Latin layout, where the letter itself counts.
55
+ * A symbol (`?`, `+`) often needs Shift to be typed at all, so Shift is checked for it only when the combination names it.
56
+ * Нажимает ли этот keydown сочетание?
57
+ * Буква или цифра находится и по физической клавише, когда раскладка даёт нелатинский символ (Ctrl+Я — это Ctrl+Z
58
+ * в русской раскладке, Option+S на Mac даёт ß), но не на другой латинской раскладке, там считается сама буква.
59
+ * Символ (`?`, `+`) часто без Shift не набрать, поэтому Shift для него проверяется, только если он назван в сочетании.
60
+ */
61
+ export declare function matchHotkey(event: KeyLike, combo: string | Hotkey, options?: PlatformOptions): boolean;
62
+ /**
63
+ * The label to show in a menu or a tooltip: `Ctrl+Shift+Z` on Windows and Linux, `⇧⌘Z` on a Mac
64
+ * (glyphs in Apple's order ⌃⌥⇧⌘, no separators; Backspace is ⌫, forward Delete ⌦).
65
+ * Подпись для меню или подсказки: `Ctrl+Shift+Z` на Windows и Linux, `⇧⌘Z` на Mac
66
+ * (значки в порядке Apple ⌃⌥⇧⌘, без разделителей; Backspace — ⌫, Delete вперёд — ⌦).
67
+ */
68
+ export declare function formatHotkey(combo: string | Hotkey, options?: PlatformOptions): string;
69
+ /**
70
+ * A canonical form for comparing two combinations on one platform: `Mod+Z` and `Ctrl+Z` are equal off Apple.
71
+ * Каноническая запись для сравнения двух сочетаний на одной платформе: вне Apple `Mod+Z` и `Ctrl+Z` равны.
72
+ */
73
+ export declare function normalizeHotkey(combo: string | Hotkey, options?: PlatformOptions): string;
74
+ export interface ReservedOptions extends PlatformOptions {
75
+ /** Safari (it keeps ⌘R). Default: detected from `navigator`. / Safari (оставляет себе ⌘R). По умолчанию из `navigator`. */
76
+ safari?: boolean;
77
+ }
78
+ /**
79
+ * Will the browser or the system keep this combination to itself? Such a combination must not be offered as a shortcut:
80
+ * it closes the tab or the window instead of reaching the page. `preventDefault` cannot help.
81
+ * Оставит ли браузер или система это сочетание себе? Такое нельзя предлагать как горячую клавишу:
82
+ * оно закроет вкладку или окно вместо того, чтобы дойти до страницы. `preventDefault` тут не поможет.
83
+ */
84
+ export declare function isReservedHotkey(combo: string | Hotkey, options?: ReservedOptions): boolean;
85
+ /**
86
+ * When a key comes from a text field: `smart` lets through only combinations with Ctrl / ⌘ / Alt and leaves the text
87
+ * editing ones to the field (Mod+Z, Mod+Shift+Z, Mod+Y, Mod+A, Mod+C, Mod+X, Mod+V); `never` ignores fields; `always` takes everything.
88
+ * Когда клавиша пришла из текстового поля: `smart` пропускает только сочетания с Ctrl / ⌘ / Alt и оставляет полю
89
+ * текстовые (Mod+Z, Mod+Shift+Z, Mod+Y, Mod+A, Mod+C, Mod+X, Mod+V); `never` поля игнорирует; `always` берёт всё.
90
+ */
91
+ export type EditablePolicy = 'smart' | 'never' | 'always';
92
+ export interface BindOptions extends PlatformOptions {
93
+ /** Default `smart`. / По умолчанию `smart`. */
94
+ editable?: EditablePolicy;
95
+ /** Fire again while the key is held. Default true. / Срабатывать снова, пока клавиша зажата. По умолчанию true. */
96
+ repeat?: boolean;
97
+ }
98
+ /** One binding: the combination and what it does. Returning `false` lets the key go on (no `preventDefault`). */
99
+ export type HotkeyHandler = (event: KeyboardEvent) => void | boolean;
100
+ /**
101
+ * Listens to `keydown` on the target (an element, `document`, `window`) and runs the first matching handler.
102
+ * A matched key gets `preventDefault` (unless the handler returns `false`). Returns the function that stops listening.
103
+ * In Vue: bind in `onMounted`, call the result in `onBeforeUnmount`.
104
+ * Слушает `keydown` на цели (элемент, `document`, `window`) и запускает первый подходящий обработчик.
105
+ * Совпавшей клавише делается `preventDefault` (если обработчик не вернул `false`). Возвращает функцию, которая перестаёт слушать.
106
+ * Во Vue: связать в `onMounted`, вызвать результат в `onBeforeUnmount`.
107
+ */
108
+ export declare function bindHotkeys(target: EventTarget, bindings: Record<string, HotkeyHandler> | (() => Record<string, HotkeyHandler>), options?: BindOptions): () => void;
@@ -0,0 +1,280 @@
1
+ //#region src/hotkeys.ts
2
+ /**
3
+ * Apple platform: macOS, iOS, iPadOS. False on the server.
4
+ * Платформа Apple: macOS, iOS, iPadOS. На сервере false.
5
+ */
6
+ function isApplePlatform() {
7
+ if (typeof navigator === "undefined") return false;
8
+ const nav = navigator;
9
+ const platform = nav.userAgentData?.platform || nav.platform || nav.userAgent || "";
10
+ return /mac|iphone|ipad|ipod/i.test(platform);
11
+ }
12
+ var MODIFIERS = {
13
+ mod: "mod",
14
+ ctrl: "ctrl",
15
+ control: "ctrl",
16
+ cmd: "meta",
17
+ command: "meta",
18
+ meta: "meta",
19
+ super: "meta",
20
+ win: "meta",
21
+ alt: "alt",
22
+ option: "alt",
23
+ opt: "alt",
24
+ shift: "shift"
25
+ };
26
+ var KEY_ALIASES = {
27
+ esc: "escape",
28
+ del: "delete",
29
+ ins: "insert",
30
+ return: "enter",
31
+ space: " ",
32
+ spacebar: " ",
33
+ plus: "+",
34
+ up: "arrowup",
35
+ down: "arrowdown",
36
+ left: "arrowleft",
37
+ right: "arrowright",
38
+ pgup: "pageup",
39
+ pgdn: "pagedown"
40
+ };
41
+ /**
42
+ * Parses `Mod+Shift+Z`, `Ctrl+Alt+Delete`, `Shift+?`, `Mod++` (the plus key). Case and spaces around `+` do not matter.
43
+ * Throws on an empty combination, an unknown modifier or two keys: a typo in a shortcut is a bug, not data.
44
+ * Разбирает `Mod+Shift+Z`, `Ctrl+Alt+Delete`, `Shift+?`, `Mod++` (клавиша плюс). Регистр и пробелы вокруг `+` не важны.
45
+ * Бросает ошибку на пустое сочетание, незнакомый модификатор или две клавиши: опечатка в сочетании — это баг, а не данные.
46
+ */
47
+ function parseHotkey(combo) {
48
+ const text = combo.trim();
49
+ const parts = text.endsWith("++") ? [...text.slice(0, -2).split("+"), "+"] : text === "+" ? ["+"] : text.split("+");
50
+ const hotkey = {
51
+ key: "",
52
+ mod: false,
53
+ ctrl: false,
54
+ meta: false,
55
+ alt: false,
56
+ shift: false
57
+ };
58
+ parts.forEach((raw, index) => {
59
+ const part = raw.trim();
60
+ const lower = part.toLowerCase();
61
+ if (!(index === parts.length - 1)) {
62
+ const modifier = MODIFIERS[lower];
63
+ if (!modifier) throw new Error(`hotkeys: unknown modifier "${part}" in "${combo}"`);
64
+ hotkey[modifier] = true;
65
+ return;
66
+ }
67
+ if (!part && raw !== " ") throw new Error(`hotkeys: no key in "${combo}"`);
68
+ hotkey.key = KEY_ALIASES[lower] ?? (raw === " " ? " " : lower);
69
+ });
70
+ return hotkey;
71
+ }
72
+ var asHotkey = (combo) => typeof combo === "string" ? parseHotkey(combo) : combo;
73
+ /**
74
+ * What modifiers the combination really needs on this platform (`Mod` resolved).
75
+ * Какие модификаторы сочетанию нужны на этой платформе на самом деле (`Mod` раскрыт).
76
+ */
77
+ function resolve(hotkey, mac) {
78
+ return {
79
+ ctrl: hotkey.ctrl || hotkey.mod && !mac,
80
+ meta: hotkey.meta || hotkey.mod && mac,
81
+ alt: hotkey.alt,
82
+ shift: hotkey.shift
83
+ };
84
+ }
85
+ var isLatinLetter = (key) => /^[a-z]$/.test(key);
86
+ var isDigit = (key) => /^[0-9]$/.test(key);
87
+ var isSymbol = (key) => key.length === 1 && !isLatinLetter(key) && !isDigit(key) && key !== " ";
88
+ /**
89
+ * Does this keydown press the combination?
90
+ * A letter or a digit is also found by its physical key when the layout gives a non-Latin character (Ctrl+Я is Ctrl+Z
91
+ * on a Russian layout, Option+S on a Mac gives ß), but not on another Latin layout, where the letter itself counts.
92
+ * A symbol (`?`, `+`) often needs Shift to be typed at all, so Shift is checked for it only when the combination names it.
93
+ * Нажимает ли этот keydown сочетание?
94
+ * Буква или цифра находится и по физической клавише, когда раскладка даёт нелатинский символ (Ctrl+Я — это Ctrl+Z
95
+ * в русской раскладке, Option+S на Mac даёт ß), но не на другой латинской раскладке, там считается сама буква.
96
+ * Символ (`?`, `+`) часто без Shift не набрать, поэтому Shift для него проверяется, только если он назван в сочетании.
97
+ */
98
+ function matchHotkey(event, combo, options = {}) {
99
+ const hotkey = asHotkey(combo);
100
+ const need = resolve(hotkey, options.mac ?? isApplePlatform());
101
+ if (event.ctrlKey !== need.ctrl || event.metaKey !== need.meta || event.altKey !== need.alt) return false;
102
+ if (!(isSymbol(hotkey.key) && !need.shift) && event.shiftKey !== need.shift) return false;
103
+ if (event.key.toLowerCase() === hotkey.key) return true;
104
+ if (!event.code) return false;
105
+ if (isDigit(hotkey.key)) return event.code === `Digit${hotkey.key}`;
106
+ if (isLatinLetter(hotkey.key) && /[^\x20-\x7e]/.test(event.key)) return event.code === `Key${hotkey.key.toUpperCase()}`;
107
+ return false;
108
+ }
109
+ var MAC_KEYS = {
110
+ arrowup: "↑",
111
+ arrowdown: "↓",
112
+ arrowleft: "←",
113
+ arrowright: "→",
114
+ enter: "↩",
115
+ escape: "⎋",
116
+ backspace: "⌫",
117
+ delete: "⌦",
118
+ tab: "⇥",
119
+ " ": "Space",
120
+ pageup: "⇞",
121
+ pagedown: "⇟",
122
+ home: "↖",
123
+ end: "↘"
124
+ };
125
+ var PC_KEYS = {
126
+ arrowup: "↑",
127
+ arrowdown: "↓",
128
+ arrowleft: "←",
129
+ arrowright: "→",
130
+ escape: "Esc",
131
+ delete: "Del",
132
+ insert: "Ins",
133
+ " ": "Space",
134
+ pageup: "PgUp",
135
+ pagedown: "PgDn"
136
+ };
137
+ var keyLabel = (key, mac) => (mac ? MAC_KEYS : PC_KEYS)[key] ?? (key.length === 1 ? key.toUpperCase() : key[0].toUpperCase() + key.slice(1));
138
+ /**
139
+ * The label to show in a menu or a tooltip: `Ctrl+Shift+Z` on Windows and Linux, `⇧⌘Z` on a Mac
140
+ * (glyphs in Apple's order ⌃⌥⇧⌘, no separators; Backspace is ⌫, forward Delete ⌦).
141
+ * Подпись для меню или подсказки: `Ctrl+Shift+Z` на Windows и Linux, `⇧⌘Z` на Mac
142
+ * (значки в порядке Apple ⌃⌥⇧⌘, без разделителей; Backspace — ⌫, Delete вперёд — ⌦).
143
+ */
144
+ function formatHotkey(combo, options = {}) {
145
+ const hotkey = asHotkey(combo);
146
+ const mac = options.mac ?? isApplePlatform();
147
+ const need = resolve(hotkey, mac);
148
+ const key = keyLabel(hotkey.key, mac);
149
+ if (mac) return `${need.ctrl ? "⌃" : ""}${need.alt ? "⌥" : ""}${need.shift ? "⇧" : ""}${need.meta ? "⌘" : ""}${key}`;
150
+ return [...[
151
+ need.ctrl && "Ctrl",
152
+ need.alt && "Alt",
153
+ need.shift && "Shift",
154
+ need.meta && "Win"
155
+ ].filter(Boolean), key].join("+");
156
+ }
157
+ /**
158
+ * A canonical form for comparing two combinations on one platform: `Mod+Z` and `Ctrl+Z` are equal off Apple.
159
+ * Каноническая запись для сравнения двух сочетаний на одной платформе: вне Apple `Mod+Z` и `Ctrl+Z` равны.
160
+ */
161
+ function normalizeHotkey(combo, options = {}) {
162
+ const hotkey = asHotkey(combo);
163
+ const need = resolve(hotkey, options.mac ?? isApplePlatform());
164
+ return [...[
165
+ need.ctrl && "ctrl",
166
+ need.meta && "meta",
167
+ need.alt && "alt",
168
+ need.shift && "shift"
169
+ ].filter(Boolean), hotkey.key === " " ? "space" : hotkey.key].join("+");
170
+ }
171
+ /** The browser or the system keeps these: a page never gets them (closing, opening, switching tabs and windows). */
172
+ var RESERVED_ALL = [
173
+ "Mod+W",
174
+ "Mod+T",
175
+ "Mod+N",
176
+ "Mod+Shift+T",
177
+ "Mod+Shift+N",
178
+ "Mod+Shift+W",
179
+ "Ctrl+Tab",
180
+ "Ctrl+Shift+Tab"
181
+ ];
182
+ var RESERVED_MAC = [
183
+ "Mod+Q",
184
+ "Mod+H",
185
+ "Mod+M",
186
+ "Mod+Tab",
187
+ "Mod+Space",
188
+ "Mod+Alt+Escape"
189
+ ];
190
+ var RESERVED_PC = [
191
+ "Alt+F4",
192
+ "Alt+Tab",
193
+ "Ctrl+Alt+Delete"
194
+ ];
195
+ /** Safari does not let a page take reload. / Safari не даёт странице перехватить перезагрузку. */
196
+ var RESERVED_SAFARI = ["Mod+R"];
197
+ var isSafari = () => typeof navigator !== "undefined" && /^((?!chrome|android|crios|fxios|edg).)*safari/i.test(navigator.userAgent);
198
+ /**
199
+ * Will the browser or the system keep this combination to itself? Such a combination must not be offered as a shortcut:
200
+ * it closes the tab or the window instead of reaching the page. `preventDefault` cannot help.
201
+ * Оставит ли браузер или система это сочетание себе? Такое нельзя предлагать как горячую клавишу:
202
+ * оно закроет вкладку или окно вместо того, чтобы дойти до страницы. `preventDefault` тут не поможет.
203
+ */
204
+ function isReservedHotkey(combo, options = {}) {
205
+ const mac = options.mac ?? isApplePlatform();
206
+ const safari = options.safari ?? isSafari();
207
+ const list = [
208
+ ...RESERVED_ALL,
209
+ ...mac ? RESERVED_MAC : RESERVED_PC,
210
+ ...safari ? RESERVED_SAFARI : []
211
+ ];
212
+ const own = normalizeHotkey(combo, { mac });
213
+ return list.some((reserved) => normalizeHotkey(reserved, { mac }) === own);
214
+ }
215
+ var TEXT_EDITING = [
216
+ "Mod+Z",
217
+ "Mod+Shift+Z",
218
+ "Mod+Y",
219
+ "Mod+A",
220
+ "Mod+C",
221
+ "Mod+X",
222
+ "Mod+V"
223
+ ];
224
+ function isEditable(target) {
225
+ const el = target;
226
+ if (!el || typeof el.tagName !== "string") return false;
227
+ if (el.isContentEditable) return true;
228
+ if (el.tagName === "TEXTAREA" || el.tagName === "SELECT") return true;
229
+ if (el.tagName !== "INPUT") return false;
230
+ const type = el.type;
231
+ return ![
232
+ "button",
233
+ "checkbox",
234
+ "radio",
235
+ "range",
236
+ "color",
237
+ "file",
238
+ "submit",
239
+ "reset",
240
+ "image"
241
+ ].includes(type);
242
+ }
243
+ /**
244
+ * Listens to `keydown` on the target (an element, `document`, `window`) and runs the first matching handler.
245
+ * A matched key gets `preventDefault` (unless the handler returns `false`). Returns the function that stops listening.
246
+ * In Vue: bind in `onMounted`, call the result in `onBeforeUnmount`.
247
+ * Слушает `keydown` на цели (элемент, `document`, `window`) и запускает первый подходящий обработчик.
248
+ * Совпавшей клавише делается `preventDefault` (если обработчик не вернул `false`). Возвращает функцию, которая перестаёт слушать.
249
+ * Во Vue: связать в `onMounted`, вызвать результат в `onBeforeUnmount`.
250
+ */
251
+ function bindHotkeys(target, bindings, options = {}) {
252
+ const mac = options.mac ?? isApplePlatform();
253
+ const editable = options.editable ?? "smart";
254
+ const textEditing = TEXT_EDITING.map((combo) => parseHotkey(combo));
255
+ const cache = /* @__PURE__ */ new Map();
256
+ const parse = (combo) => cache.get(combo) ?? cache.set(combo, parseHotkey(combo)).get(combo);
257
+ if (typeof bindings !== "function") Object.keys(bindings).forEach(parse);
258
+ const onKeydown = (raw) => {
259
+ const event = raw;
260
+ if (event.defaultPrevented || event.isComposing) return;
261
+ if (event.repeat && options.repeat === false) return;
262
+ const inField = isEditable(event.target);
263
+ if (inField && editable === "never") return;
264
+ const current = typeof bindings === "function" ? bindings() : bindings;
265
+ for (const [combo, handler] of Object.entries(current)) {
266
+ if (!matchHotkey(event, parse(combo), { mac })) continue;
267
+ if (inField && editable === "smart") {
268
+ if (!(event.ctrlKey || event.metaKey || event.altKey) || textEditing.some((t) => matchHotkey(event, t, { mac }))) return;
269
+ }
270
+ if (handler(event) !== false) event.preventDefault();
271
+ return;
272
+ }
273
+ };
274
+ target.addEventListener("keydown", onKeydown);
275
+ return () => target.removeEventListener("keydown", onKeydown);
276
+ }
277
+ //#endregion
278
+ export { bindHotkeys, formatHotkey, isApplePlatform, isReservedHotkey, matchHotkey, normalizeHotkey, parseHotkey };
279
+
280
+ //# sourceMappingURL=hotkeys.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hotkeys.js","names":[],"sources":["../src/hotkeys.ts"],"sourcesContent":["/**\n * Keyboard shortcuts: parse `Mod+Shift+Z`, match a keydown against it, show it the way the platform writes it,\n * and know which ones the browser never gives to a page. `Mod` is ⌘ on Apple platforms and Ctrl elsewhere,\n * so the data stores `Mod` and not a concrete key.\n * Сочетания клавиш: разобрать `Mod+Shift+Z`, сверить с ним keydown, показать так, как пишет платформа,\n * и знать, какие браузер странице не отдаёт никогда. `Mod` — это ⌘ на платформах Apple и Ctrl на остальных,\n * поэтому в данных хранится `Mod`, а не конкретная клавиша.\n */\n\nexport interface Hotkey {\n /**\n * `event.key` in lower case: `z`, `arrowup`, `escape`, `f2`, `'`, `' '` for the space bar.\n * `event.key` в нижнем регистре: `z`, `arrowup`, `escape`, `f2`, `'`, `' '` для пробела.\n */\n key: string;\n /** ⌘ on Apple, Ctrl elsewhere. / ⌘ у Apple, Ctrl у остальных. */\n mod: boolean;\n ctrl: boolean;\n /** ⌘ / the Windows key. / ⌘ / клавиша Windows. */\n meta: boolean;\n /** Option on Apple. / Option у Apple. */\n alt: boolean;\n shift: boolean;\n}\n\nexport interface PlatformOptions {\n /**\n * Apple platform (⌘ for `Mod`, glyphs in labels). Default: detected from `navigator`, false without one (SSR).\n * Платформа Apple (⌘ для `Mod`, значки в подписях). По умолчанию: из `navigator`, без него (SSR) false.\n */\n mac?: boolean;\n}\n\n/**\n * Apple platform: macOS, iOS, iPadOS. False on the server.\n * Платформа Apple: macOS, iOS, iPadOS. На сервере false.\n */\nexport function isApplePlatform(): boolean {\n if (typeof navigator === 'undefined') return false;\n const nav = navigator as Navigator & { userAgentData?: { platform?: string } };\n const platform = nav.userAgentData?.platform || nav.platform || nav.userAgent || '';\n return /mac|iphone|ipad|ipod/i.test(platform);\n}\n\nconst MODIFIERS: Record<string, keyof Omit<Hotkey, 'key'>> = {\n mod: 'mod',\n ctrl: 'ctrl',\n control: 'ctrl',\n cmd: 'meta',\n command: 'meta',\n meta: 'meta',\n super: 'meta',\n win: 'meta',\n alt: 'alt',\n option: 'alt',\n opt: 'alt',\n shift: 'shift',\n};\n\nconst KEY_ALIASES: Record<string, string> = {\n esc: 'escape',\n del: 'delete',\n ins: 'insert',\n return: 'enter',\n space: ' ',\n spacebar: ' ',\n plus: '+',\n up: 'arrowup',\n down: 'arrowdown',\n left: 'arrowleft',\n right: 'arrowright',\n pgup: 'pageup',\n pgdn: 'pagedown',\n};\n\n/**\n * Parses `Mod+Shift+Z`, `Ctrl+Alt+Delete`, `Shift+?`, `Mod++` (the plus key). Case and spaces around `+` do not matter.\n * Throws on an empty combination, an unknown modifier or two keys: a typo in a shortcut is a bug, not data.\n * Разбирает `Mod+Shift+Z`, `Ctrl+Alt+Delete`, `Shift+?`, `Mod++` (клавиша плюс). Регистр и пробелы вокруг `+` не важны.\n * Бросает ошибку на пустое сочетание, незнакомый модификатор или две клавиши: опечатка в сочетании — это баг, а не данные.\n */\nexport function parseHotkey(combo: string): Hotkey {\n const text = combo.trim();\n // a trailing \"+\" after a separator is the plus key itself / «+» в конце после разделителя — это сама клавиша плюс\n const parts = text.endsWith('++') ? [...text.slice(0, -2).split('+'), '+'] : text === '+' ? ['+'] : text.split('+');\n const hotkey: Hotkey = { key: '', mod: false, ctrl: false, meta: false, alt: false, shift: false };\n\n parts.forEach((raw, index) => {\n const part = raw.trim();\n const lower = part.toLowerCase();\n const last = index === parts.length - 1;\n if (!last) {\n const modifier = MODIFIERS[lower];\n if (!modifier) throw new Error(`hotkeys: unknown modifier \"${part}\" in \"${combo}\"`);\n hotkey[modifier] = true;\n return;\n }\n if (!part && raw !== ' ') throw new Error(`hotkeys: no key in \"${combo}\"`);\n hotkey.key = KEY_ALIASES[lower] ?? (raw === ' ' ? ' ' : lower);\n });\n return hotkey;\n}\n\nconst asHotkey = (combo: string | Hotkey): Hotkey => (typeof combo === 'string' ? parseHotkey(combo) : combo);\n\n/**\n * What modifiers the combination really needs on this platform (`Mod` resolved).\n * Какие модификаторы сочетанию нужны на этой платформе на самом деле (`Mod` раскрыт).\n */\nfunction resolve(hotkey: Hotkey, mac: boolean) {\n return {\n ctrl: hotkey.ctrl || (hotkey.mod && !mac),\n meta: hotkey.meta || (hotkey.mod && mac),\n alt: hotkey.alt,\n shift: hotkey.shift,\n };\n}\n\nexport interface KeyLike {\n key: string;\n code?: string;\n ctrlKey: boolean;\n metaKey: boolean;\n altKey: boolean;\n shiftKey: boolean;\n}\n\nconst isLatinLetter = (key: string) => /^[a-z]$/.test(key);\nconst isDigit = (key: string) => /^[0-9]$/.test(key);\nconst isSymbol = (key: string) => key.length === 1 && !isLatinLetter(key) && !isDigit(key) && key !== ' ';\n\n/**\n * Does this keydown press the combination?\n * A letter or a digit is also found by its physical key when the layout gives a non-Latin character (Ctrl+Я is Ctrl+Z\n * on a Russian layout, Option+S on a Mac gives ß), but not on another Latin layout, where the letter itself counts.\n * A symbol (`?`, `+`) often needs Shift to be typed at all, so Shift is checked for it only when the combination names it.\n * Нажимает ли этот keydown сочетание?\n * Буква или цифра находится и по физической клавише, когда раскладка даёт нелатинский символ (Ctrl+Я — это Ctrl+Z\n * в русской раскладке, Option+S на Mac даёт ß), но не на другой латинской раскладке, там считается сама буква.\n * Символ (`?`, `+`) часто без Shift не набрать, поэтому Shift для него проверяется, только если он назван в сочетании.\n */\nexport function matchHotkey(event: KeyLike, combo: string | Hotkey, options: PlatformOptions = {}): boolean {\n const hotkey = asHotkey(combo);\n const need = resolve(hotkey, options.mac ?? isApplePlatform());\n if (event.ctrlKey !== need.ctrl || event.metaKey !== need.meta || event.altKey !== need.alt) return false;\n if (!(isSymbol(hotkey.key) && !need.shift) && event.shiftKey !== need.shift) return false;\n\n const key = event.key.toLowerCase();\n if (key === hotkey.key) return true;\n if (!event.code) return false;\n // the digit row is the same on every layout, but Shift (or AZERTY) types a symbol on it: ask the physical key\n // ряд цифр один на всех раскладках, но Shift (или AZERTY) набирает на нём символ: спрашиваем физическую клавишу\n if (isDigit(hotkey.key)) return event.code === `Digit${hotkey.key}`;\n // a non-ASCII character: the layout is not Latin (or Option made a special one), ask the physical key\n // не-ASCII символ: раскладка не латинская (или Option дал особый символ), спрашиваем физическую клавишу\n if (isLatinLetter(hotkey.key) && /[^\\x20-\\x7e]/.test(event.key)) return event.code === `Key${hotkey.key.toUpperCase()}`;\n return false;\n}\n\nconst MAC_KEYS: Record<string, string> = {\n arrowup: '↑',\n arrowdown: '↓',\n arrowleft: '←',\n arrowright: '→',\n enter: '↩',\n escape: '⎋',\n backspace: '⌫',\n delete: '⌦',\n tab: '⇥',\n ' ': 'Space',\n pageup: '⇞',\n pagedown: '⇟',\n home: '↖',\n end: '↘',\n};\n\nconst PC_KEYS: Record<string, string> = {\n arrowup: '↑',\n arrowdown: '↓',\n arrowleft: '←',\n arrowright: '→',\n escape: 'Esc',\n delete: 'Del',\n insert: 'Ins',\n ' ': 'Space',\n pageup: 'PgUp',\n pagedown: 'PgDn',\n};\n\nconst keyLabel = (key: string, mac: boolean) => (mac ? MAC_KEYS : PC_KEYS)[key] ?? (key.length === 1 ? key.toUpperCase() : key[0]!.toUpperCase() + key.slice(1));\n\n/**\n * The label to show in a menu or a tooltip: `Ctrl+Shift+Z` on Windows and Linux, `⇧⌘Z` on a Mac\n * (glyphs in Apple's order ⌃⌥⇧⌘, no separators; Backspace is ⌫, forward Delete ⌦).\n * Подпись для меню или подсказки: `Ctrl+Shift+Z` на Windows и Linux, `⇧⌘Z` на Mac\n * (значки в порядке Apple ⌃⌥⇧⌘, без разделителей; Backspace — ⌫, Delete вперёд — ⌦).\n */\nexport function formatHotkey(combo: string | Hotkey, options: PlatformOptions = {}): string {\n const hotkey = asHotkey(combo);\n const mac = options.mac ?? isApplePlatform();\n const need = resolve(hotkey, mac);\n const key = keyLabel(hotkey.key, mac);\n if (mac) {\n return `${need.ctrl ? '⌃' : ''}${need.alt ? '⌥' : ''}${need.shift ? '⇧' : ''}${need.meta ? '⌘' : ''}${key}`;\n }\n const mods = [need.ctrl && 'Ctrl', need.alt && 'Alt', need.shift && 'Shift', need.meta && 'Win'].filter(Boolean);\n return [...mods, key].join('+');\n}\n\n/**\n * A canonical form for comparing two combinations on one platform: `Mod+Z` and `Ctrl+Z` are equal off Apple.\n * Каноническая запись для сравнения двух сочетаний на одной платформе: вне Apple `Mod+Z` и `Ctrl+Z` равны.\n */\nexport function normalizeHotkey(combo: string | Hotkey, options: PlatformOptions = {}): string {\n const hotkey = asHotkey(combo);\n const need = resolve(hotkey, options.mac ?? isApplePlatform());\n const mods = [need.ctrl && 'ctrl', need.meta && 'meta', need.alt && 'alt', need.shift && 'shift'].filter(Boolean);\n return [...mods, hotkey.key === ' ' ? 'space' : hotkey.key].join('+');\n}\n\n/** The browser or the system keeps these: a page never gets them (closing, opening, switching tabs and windows). */\nconst RESERVED_ALL = ['Mod+W', 'Mod+T', 'Mod+N', 'Mod+Shift+T', 'Mod+Shift+N', 'Mod+Shift+W', 'Ctrl+Tab', 'Ctrl+Shift+Tab'];\nconst RESERVED_MAC = ['Mod+Q', 'Mod+H', 'Mod+M', 'Mod+Tab', 'Mod+Space', 'Mod+Alt+Escape'];\nconst RESERVED_PC = ['Alt+F4', 'Alt+Tab', 'Ctrl+Alt+Delete'];\n/** Safari does not let a page take reload. / Safari не даёт странице перехватить перезагрузку. */\nconst RESERVED_SAFARI = ['Mod+R'];\n\nexport interface ReservedOptions extends PlatformOptions {\n /** Safari (it keeps ⌘R). Default: detected from `navigator`. / Safari (оставляет себе ⌘R). По умолчанию из `navigator`. */\n safari?: boolean;\n}\n\nconst isSafari = () => typeof navigator !== 'undefined' && /^((?!chrome|android|crios|fxios|edg).)*safari/i.test(navigator.userAgent);\n\n/**\n * Will the browser or the system keep this combination to itself? Such a combination must not be offered as a shortcut:\n * it closes the tab or the window instead of reaching the page. `preventDefault` cannot help.\n * Оставит ли браузер или система это сочетание себе? Такое нельзя предлагать как горячую клавишу:\n * оно закроет вкладку или окно вместо того, чтобы дойти до страницы. `preventDefault` тут не поможет.\n */\nexport function isReservedHotkey(combo: string | Hotkey, options: ReservedOptions = {}): boolean {\n const mac = options.mac ?? isApplePlatform();\n const safari = options.safari ?? isSafari();\n const list = [...RESERVED_ALL, ...(mac ? RESERVED_MAC : RESERVED_PC), ...(safari ? RESERVED_SAFARI : [])];\n const own = normalizeHotkey(combo, { mac });\n return list.some((reserved) => normalizeHotkey(reserved, { mac }) === own);\n}\n\n/**\n * When a key comes from a text field: `smart` lets through only combinations with Ctrl / ⌘ / Alt and leaves the text\n * editing ones to the field (Mod+Z, Mod+Shift+Z, Mod+Y, Mod+A, Mod+C, Mod+X, Mod+V); `never` ignores fields; `always` takes everything.\n * Когда клавиша пришла из текстового поля: `smart` пропускает только сочетания с Ctrl / ⌘ / Alt и оставляет полю\n * текстовые (Mod+Z, Mod+Shift+Z, Mod+Y, Mod+A, Mod+C, Mod+X, Mod+V); `never` поля игнорирует; `always` берёт всё.\n */\nexport type EditablePolicy = 'smart' | 'never' | 'always';\n\nexport interface BindOptions extends PlatformOptions {\n /** Default `smart`. / По умолчанию `smart`. */\n editable?: EditablePolicy;\n /** Fire again while the key is held. Default true. / Срабатывать снова, пока клавиша зажата. По умолчанию true. */\n repeat?: boolean;\n}\n\n/** One binding: the combination and what it does. Returning `false` lets the key go on (no `preventDefault`). */\nexport type HotkeyHandler = (event: KeyboardEvent) => void | boolean;\n\nconst TEXT_EDITING = ['Mod+Z', 'Mod+Shift+Z', 'Mod+Y', 'Mod+A', 'Mod+C', 'Mod+X', 'Mod+V'];\n\nfunction isEditable(target: EventTarget | null): boolean {\n const el = target as HTMLElement | null;\n if (!el || typeof el.tagName !== 'string') return false;\n if (el.isContentEditable) return true;\n if (el.tagName === 'TEXTAREA' || el.tagName === 'SELECT') return true;\n if (el.tagName !== 'INPUT') return false;\n const type = (el as HTMLInputElement).type;\n return !['button', 'checkbox', 'radio', 'range', 'color', 'file', 'submit', 'reset', 'image'].includes(type);\n}\n\n/**\n * Listens to `keydown` on the target (an element, `document`, `window`) and runs the first matching handler.\n * A matched key gets `preventDefault` (unless the handler returns `false`). Returns the function that stops listening.\n * In Vue: bind in `onMounted`, call the result in `onBeforeUnmount`.\n * Слушает `keydown` на цели (элемент, `document`, `window`) и запускает первый подходящий обработчик.\n * Совпавшей клавише делается `preventDefault` (если обработчик не вернул `false`). Возвращает функцию, которая перестаёт слушать.\n * Во Vue: связать в `onMounted`, вызвать результат в `onBeforeUnmount`.\n */\nexport function bindHotkeys(\n target: EventTarget,\n bindings: Record<string, HotkeyHandler> | (() => Record<string, HotkeyHandler>),\n options: BindOptions = {},\n): () => void {\n const mac = options.mac ?? isApplePlatform();\n const editable = options.editable ?? 'smart';\n const textEditing = TEXT_EDITING.map((combo) => parseHotkey(combo));\n // a function is read on every key, so bindings added later count; parsing is cached per string\n // функция читается на каждую клавишу, так что поздние привязки тоже работают; разбор кэшируется по строке\n const cache = new Map<string, Hotkey>();\n const parse = (combo: string) => cache.get(combo) ?? cache.set(combo, parseHotkey(combo)).get(combo)!;\n if (typeof bindings !== 'function') Object.keys(bindings).forEach(parse); // a typo throws at once / опечатка бросает сразу\n\n const onKeydown = (raw: Event) => {\n const event = raw as KeyboardEvent;\n if (event.defaultPrevented || event.isComposing) return;\n if (event.repeat && options.repeat === false) return;\n const inField = isEditable(event.target);\n if (inField && editable === 'never') return;\n\n const current = typeof bindings === 'function' ? bindings() : bindings;\n for (const [combo, handler] of Object.entries(current)) {\n if (!matchHotkey(event, parse(combo), { mac })) continue;\n if (inField && editable === 'smart') {\n const modified = event.ctrlKey || event.metaKey || event.altKey;\n if (!modified || textEditing.some((t) => matchHotkey(event, t, { mac }))) return;\n }\n if (handler(event) !== false) event.preventDefault();\n return;\n }\n };\n\n target.addEventListener('keydown', onKeydown);\n return () => target.removeEventListener('keydown', onKeydown);\n}\n"],"mappings":";;;;;AAqCA,SAAgB,kBAA2B;CACvC,IAAI,OAAO,cAAc,aAAa,OAAO;CAC7C,MAAM,MAAM;CACZ,MAAM,WAAW,IAAI,eAAe,YAAY,IAAI,YAAY,IAAI,aAAa;CACjF,OAAO,wBAAwB,KAAK,QAAQ;AAChD;AAEA,IAAM,YAAuD;CACzD,KAAK;CACL,MAAM;CACN,SAAS;CACT,KAAK;CACL,SAAS;CACT,MAAM;CACN,OAAO;CACP,KAAK;CACL,KAAK;CACL,QAAQ;CACR,KAAK;CACL,OAAO;AACX;AAEA,IAAM,cAAsC;CACxC,KAAK;CACL,KAAK;CACL,KAAK;CACL,QAAQ;CACR,OAAO;CACP,UAAU;CACV,MAAM;CACN,IAAI;CACJ,MAAM;CACN,MAAM;CACN,OAAO;CACP,MAAM;CACN,MAAM;AAC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AC,YAAY,OAAO,MAAM,KAAK,GAAG,EAAE,IAAI,CAAC,GAAG;GAChD,IAAI,WAAW,aAAa,SAEpB;QAAA,EADa,MAAM,WAAW,MAAM,WAAW,MAAM,WACxC,YAAY,MAAM,MAAM,YAAY,OAAO,GAAG,EAAE,IAAI,CAAC,CAAC,GAAG;GAAA;GAE9E,IAAI,QAAQ,KAAK,MAAM,OAAO,MAAM,eAAe;GACnD;EACJ;CACJ;CAEA,OAAO,iBAAiB,WAAW,SAAS;CAC5C,aAAa,OAAO,oBAAoB,WAAW,SAAS;AAChE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@1337exp/taoux",
3
- "version": "0.1.1",
3
+ "version": "0.2.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",
@@ -34,7 +34,8 @@
34
34
  "files": [
35
35
  "dist",
36
36
  "theme",
37
- "CHANGELOG.md"
37
+ "CHANGELOG.md",
38
+ "skills"
38
39
  ],
39
40
  "exports": {
40
41
  "./camera": {
@@ -46,6 +47,10 @@
46
47
  "import": "./dist/canvas.js"
47
48
  },
48
49
  "./canvas.css": "./dist/canvas.css",
50
+ "./commands": {
51
+ "types": "./dist/commands.d.ts",
52
+ "import": "./dist/commands.js"
53
+ },
49
54
  "./curve": {
50
55
  "types": "./dist/curve.d.ts",
51
56
  "import": "./dist/curve.js"
@@ -85,6 +90,10 @@
85
90
  "types": "./dist/history.d.ts",
86
91
  "import": "./dist/history.js"
87
92
  },
93
+ "./hotkeys": {
94
+ "types": "./dist/hotkeys.d.ts",
95
+ "import": "./dist/hotkeys.js"
96
+ },
88
97
  "./i18n": {
89
98
  "types": "./dist/i18n.d.ts",
90
99
  "import": "./dist/i18n.js"
@@ -151,7 +160,7 @@
151
160
  "media": "node scripts/media.mjs"
152
161
  },
153
162
  "peerDependencies": {
154
- "@1337exp/taoui": "^3.2.1",
163
+ "@1337exp/taoui": "^5.0.0",
155
164
  "vue": "^3.4.0"
156
165
  },
157
166
  "peerDependenciesMeta": {
@@ -163,7 +172,7 @@
163
172
  }
164
173
  },
165
174
  "devDependencies": {
166
- "@1337exp/taoui": "^3.3.1",
175
+ "@1337exp/taoui": "^5.0.0",
167
176
  "@types/node": "^26.6.4",
168
177
  "@vitejs/plugin-vue": "^6.0.10",
169
178
  "@vue/test-utils": "^2.5.1",
@@ -0,0 +1,93 @@
1
+ ---
2
+ name: taoux
3
+ description: Build editor-like behaviour in Vue 3 apps with @1337exp/taoux (TaoUX) — subpath modules for camera, undo history, document sessions, commands and hotkeys, playback, canvas, curve and gradient editors, and joining them to TaoUI. Use when code imports @1337exp/taoux/*, uses Taox* components or --tx-* variables, or the user asks for TaoUX.
4
+ ---
5
+
6
+ # TaoUX
7
+
8
+ Behaviour building blocks for editors: the logic is plain TypeScript (tested without a DOM), the few Vue modules are thin
9
+ shells, and TaoUX has **no buttons or fields of its own**. Pair it with TaoUI for the controls, or with your own design.
10
+
11
+ ## Rules
12
+
13
+ 1. **Import by subpath**, there is no root entry: `import { History } from '@1337exp/taoux/history'`. Only what you import
14
+ reaches the bundle. ESM only.
15
+ 2. **A Vue module's styles are imported explicitly**: `import '@1337exp/taoux/curveeditor.css'` (also `canvas.css`,
16
+ `links.css`, `gradienteditor.css`, `curvefield.css`; `curvefield` needs `curveeditor.css` too).
17
+ 3. **With TaoUI, add the bridge**: `import '@1337exp/taoux/taoui.css'` points every `--tx-*` colour at a `--tao-*` role, so
18
+ the editors follow the TaoUI theme and palettes. Zero specificity: your rules win. Without it the editors stay dark.
19
+ 4. **Values travel through `v-model`**; TaoUX never renders a TaoUI control itself, except tier-2 `curvefield`.
20
+ 5. **Pre-1.0**: breaking changes happen between minors; read `CHANGELOG.md`.
21
+
22
+ ## Modules
23
+
24
+ | Import | What for |
25
+ |---|---|
26
+ | `camera` | pan, zoom around the cursor, screen ↔ world (`zoomAt`) |
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 |
29
+ | `commands` | `createCommands([...])`: one registry for menus, shortcuts and palettes (see below) |
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` | download text as a file, with a size limit |
33
+ | `snap` | soft snapping to a grid, threshold follows the zoom |
34
+ | `wheel` | wheel / trackpad → pan or zoom, like Figma (zoom only with Ctrl / ⌘ or a pinch) |
35
+ | `edgescroll` | auto-scroll near an edge while dragging (`createEdgeScroller`) |
36
+ | `gestures` | tap, double tap, long press, pinch |
37
+ | `touch` | `coarse`: is the pointer a finger |
38
+ | `curve` | link paths: Bezier between pins, arrowheads of constant screen size |
39
+ | `ids` | `uid(prefix, taken)` |
40
+ | `ease` | easing between curve points (8 families × in / out / in-out, `linear`, `step`, cubic Bezier), `easeValue` |
41
+ | `num` | `clamp`, `roundTo`, `snapTo`, `niceStep`, `ticks` |
42
+ | `palette` | search and groups for a palette of nodes |
43
+ | `pins` | row pin positions measured from the DOM (`usePinMeasure`, `createPinRegistry`) |
44
+ | `playback` | time, pause, loop, speed, seeking: `createPlayback` (no Vue), `usePlayback` (drives TaoUI `TaoScrubber`) |
45
+ | `i18n` | typed i18n: `createI18n({ locales, fallback, storageKey })` |
46
+ | `links` (Vue) | `TaoxLinks`: an SVG layer of links from ready geometry |
47
+ | `canvas` (Vue) | `TaoxCanvas`: pan / zoom canvas with mouse, touch, wheel, auto-scroll, keys; the `CanvasHost` contract |
48
+ | `curveeditor` (Vue) | `TaoxCurveEditor`: points, snapping, bounds, per-segment easing with Bezier handles, keyboard |
49
+ | `gradienteditor` (Vue) | `TaoxGradientEditor`: stops on a bar, `gradientCss`, keyboard |
50
+ | `curvefield` (Vue, needs TaoUI) | `TaoxCurveField`: a curve editor with TaoUI fields for time, value, easing, snapping |
51
+
52
+ ## Commands, hotkeys and the TaoUI menu bar
53
+
54
+ ```ts
55
+ import { computed, onBeforeUnmount, onMounted } from 'vue';
56
+ import { createCommands, historyCommands } from '@1337exp/taoux/commands';
57
+
58
+ const commands = createCommands([
59
+ { id: 'save', label: () => t('save'), shortcut: 'Mod+S', enabled: () => dirty.value, run: save },
60
+ { id: 'grid', label: () => t('grid'), shortcut: "Mod+'", checked: () => grid.value, run: () => (grid.value = !grid.value) },
61
+ ...historyCommands(session), // Undo / Redo, disabled when there is nothing to undo
62
+ ]);
63
+
64
+ // in computed: labels, enabled and checked follow the refs they read
65
+ const menu = computed(() => commands.toMenu([
66
+ { id: 'file', label: t('file'), items: ['save'] },
67
+ { id: 'edit', label: t('edit'), items: ['undo', 'redo', '-', 'grid'] },
68
+ ]));
69
+
70
+ let unbind = () => {};
71
+ onMounted(() => (unbind = commands.bind(document)));
72
+ onBeforeUnmount(() => unbind());
73
+ ```
74
+
75
+ ```vue
76
+ <TaoMenubar :items="menu" @select="commands.run" />
77
+ ```
78
+
79
+ - `Mod` is ⌘ on Apple and Ctrl elsewhere; the menu shows the platform's label by itself.
80
+ - A disabled command swallows its key, so Mod+S never opens the browser's «Save page».
81
+ - In a text field, plain keys and text editing (Mod+Z / C / V / A) stay with the field.
82
+ - `commands.check()` in a test lists shortcuts the browser keeps (⌘W, ⌘T, ⌘Q, ⌘R in Safari) and duplicates.
83
+ - `toMenu` returns the same shape as TaoUI's `TaoMenuItem[]` (a type test holds it), so it also feeds `TaoContextMenu`
84
+ and `TaoDropdownMenu`.
85
+
86
+ ## Mistakes to avoid
87
+
88
+ - Importing from `@1337exp/taoux` (no root entry) or from `dist/` paths.
89
+ - Forgetting the module CSS (`curveeditor.css`…) or the bridge `taoui.css`: the editor renders unstyled or dark.
90
+ - Calling `toMenu` outside `computed`: the menu does not follow the state.
91
+ - Keeping editor state outside `history` / `session` and then wondering why Undo skips it: commit a snapshot after
92
+ every edit (`session.commit(key)` or `recorded(fn)`).
93
+ - Offering a reserved shortcut (⌘W, ⌘T, ⌘N, Ctrl+Tab): the browser takes it before the page.