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

projectScriptKeybindings.ts

59 lines1.8 KB

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