Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

projectScriptKeybindings.ts

61 lines1.9 KB

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