Open History to see the last commit
1import {
2 KeybindingRule as KeybindingRuleSchema,
3 type KeybindingCommand,
4 type KeybindingRule,
5 type ResolvedKeybindingsConfig,
6} from "@t3tools/contracts";
7import * as Schema from "effect/Schema";
8import { msg } from "gt-react";
9
10import { m } from "../i18n/messages";
11
12export const PROJECT_SCRIPT_KEYBINDING_INVALID_MESSAGE = msg("Invalid keybinding.");
13
14const decodeKeybindingRule = Schema.decodeUnknownOption(KeybindingRuleSchema);
15
16function normalizeProjectScriptKeybindingInput(
17 keybinding: string | null | undefined,
18): string | null {
19 const trimmed = keybinding?.trim() ?? "";
20 return trimmed.length > 0 ? trimmed : null;
21}
22
23export function decodeProjectScriptKeybindingRule(input: {
24 keybinding: string | null | undefined;
25 command: KeybindingCommand | null;
26}): KeybindingRule | null {
27 const normalizedKey = normalizeProjectScriptKeybindingInput(input.keybinding);
28 if (!normalizedKey) return null;
29
30 if (input.command === null) {
31 throw new Error(m(PROJECT_SCRIPT_KEYBINDING_INVALID_MESSAGE));
32 }
33
34 const decoded = decodeKeybindingRule({
35 key: normalizedKey,
36 command: input.command,
37 });
38 if (decoded._tag === "None") {
39 throw new Error(m(PROJECT_SCRIPT_KEYBINDING_INVALID_MESSAGE));
40 }
41 return decoded.value;
42}
43
44export function keybindingValueForCommand(
45 keybindings: ResolvedKeybindingsConfig,
46 command: KeybindingCommand | null,
47): string | null {
48 if (command === null) return null;
49 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
50 const binding = keybindings[index];
51 if (!binding || binding.command !== command) continue;
52
53 const parts: string[] = [];
54 if (binding.shortcut.modKey) parts.push("mod");
55 if (binding.shortcut.ctrlKey) parts.push("ctrl");
56 if (binding.shortcut.metaKey) parts.push("meta");
57 if (binding.shortcut.altKey) parts.push("alt");
58 if (binding.shortcut.shiftKey) parts.push("shift");
59 const keyToken =
60 binding.shortcut.key === " "
61 ? "space"
62 : binding.shortcut.key === "escape"
63 ? "esc"
64 : binding.shortcut.key;
65 parts.push(keyToken);
66 return parts.join("+");
67 }
68 return null;
69}