@1337exp/taoux 0.1.0 → 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.
@@ -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":"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"}
@@ -1 +1 @@
1
- export { t as TaoxCurveEditor, n as addPoint, r as movePoint, i as removePoint, a as sampleCurve, o as sampleSegment, s as setEase, c as valueBounds } from "./chunks/curveeditor-goX9maE5.js";
1
+ export { t as TaoxCurveEditor, n as addPoint, r as movePoint, i as removePoint, a as sampleCurve, o as sampleSegment, s as setEase, c as valueBounds } from "./chunks/curveeditor-F3XBWHPL.js";
@@ -1,6 +1,6 @@
1
1
  import { clampTo, niceStep, roundTo } from "./num.js";
2
2
  import { DEFAULT_BEZIER, EASE_DIRECTIONS, EASE_FAMILIES, easeName, easeParts } from "./ease.js";
3
- import { c as valueBounds, i as removePoint, r as movePoint, s as setEase, t as TaoxCurveEditor_default } from "./chunks/curveeditor-goX9maE5.js";
3
+ import { c as valueBounds, i as removePoint, r as movePoint, s as setEase, t as TaoxCurveEditor_default } from "./chunks/curveeditor-F3XBWHPL.js";
4
4
  import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, openBlock, ref, renderList, toDisplayString, unref, withCtx } from "vue";
5
5
  import { TaoButton, TaoInputNumber, TaoSegmented, TaoSegmentedOption, TaoSelect, TaoSwitch } from "@1337exp/taoui";
6
6
  //#region src/curvefield/TaoxCurveField.vue?vue&type=script&setup=true&lang.ts
@@ -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