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

KeybindingsSettings.logic.ts

356 lines11.6 KB

1import {
2 STATIC_KEYBINDING_COMMANDS,
3 type KeybindingCommand,
4 type KeybindingShortcut,
5 type KeybindingWhenNode,
6 type ResolvedKeybindingRule,
7 type ResolvedKeybindingsConfig,
8} from "@t3tools/contracts";
9import {
10 DEFAULT_RESOLVED_KEYBINDINGS,
11 parseKeybindingWhenExpression,
12} from "@t3tools/shared/keybindings";
13​
14import { shortcutKeyFromEvent } from "../../keybindings";
15import { isMacPlatform } from "../../lib/utils";
16​
17export type KeybindingSource = "Default" | "Custom" | "Project";
18​
19export interface KeybindingRow {
20 readonly id: string;
21 readonly command: KeybindingCommand;
22 readonly key: string;
23 readonly when: string;
24 readonly source: KeybindingSource;
25 readonly defaultKey: string | null;
26 readonly defaultWhen: string;
27 readonly binding: ResolvedKeybindingRule;
28 readonly conflicts: ReadonlyArray<string>;
30​
31export type WhenVariableOption = string;
32export type KeybindingCommandOption = KeybindingCommand;
33​
34const CORE_WHEN_VARIABLES = [
35 "terminalFocus",
36 "terminalOpen",
37 "isWeb",
38 "isDesktop",
39 "true",
40 "false",
41] as const;
42​
43const DEFAULT_WHEN_VARIABLES = new Set<string>(CORE_WHEN_VARIABLES);
44for (const binding of DEFAULT_RESOLVED_KEYBINDINGS) {
45 collectWhenIdentifiersFromNode(binding.whenAst, DEFAULT_WHEN_VARIABLES);
47​
48export const DEFAULT_WHEN_VARIABLE =
49 [...DEFAULT_WHEN_VARIABLES].find(
50 (identifier) => identifier !== "true" && identifier !== "false",
51 ) ?? "terminalFocus";
52const KNOWN_WHEN_VARIABLES = new Set(DEFAULT_WHEN_VARIABLES);
53​
54export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string {
55 const parts: string[] = [];
56 if (shortcut.modKey) parts.push("mod");
57 if (shortcut.metaKey) parts.push("meta");
58 if (shortcut.ctrlKey) parts.push("ctrl");
59 if (shortcut.altKey) parts.push("alt");
60 if (shortcut.shiftKey) parts.push("shift");
61 parts.push(shortcut.key === " " ? "space" : shortcut.key === "escape" ? "esc" : shortcut.key);
62 return parts.join("+");
64​
65export function whenAstToExpression(node: KeybindingWhenNode | undefined): string {
66 if (!node) return "";
67 switch (node.type) {
68 case "identifier":
69 return node.name;
70 case "not":
71 return `!${wrapWhenExpression(node.node)}`;
72 case "and":
73 return `${wrapWhenExpression(node.left)} && ${wrapWhenExpression(node.right)}`;
74 case "or":
75 return `${wrapWhenExpression(node.left)} || ${wrapWhenExpression(node.right)}`;
76 }
78​
79export function whenNodeRemoveLabel(node: KeybindingWhenNode, depth: number): string {
80 if (depth === 0) return "Clear all conditions";
81 if (node.type === "identifier" || (node.type === "not" && node.node.type === "identifier")) {
82 return "Remove condition";
83 }
84 return "Remove group and its conditions";
86​
87function wrapWhenExpression(node: KeybindingWhenNode): string {
88 if (node.type === "identifier" || node.type === "not") return whenAstToExpression(node);
89 return `(${whenAstToExpression(node)})`;
91​
92export function parseWhenExpressionDraft(
93 expression: string,
94): { ok: true; value: KeybindingWhenNode | undefined } | { ok: false; message: string } {
95 const trimmed = expression.trim();
96 if (trimmed.length === 0) return { ok: true, value: undefined };
97​
98 const ast = parseKeybindingWhenExpression(trimmed);
99 if (!ast) {
100 return {
101 ok: false,
102 message: "Use variables with !, &&, ||, and parentheses.",
103 };
104 }
105​
106 return { ok: true, value: ast };
108​
109function sourceForBinding(binding: ResolvedKeybindingRule): KeybindingSource {
110 if (String(binding.command).startsWith("script.")) {
111 return "Project";
112 }
113​
114 const bindingKey = shortcutToKeybindingInput(binding.shortcut);
115 const bindingWhen = whenAstToExpression(binding.whenAst);
116 const isDefault = DEFAULT_RESOLVED_KEYBINDINGS.some(
117 (entry) =>
118 entry.command === binding.command &&
119 shortcutToKeybindingInput(entry.shortcut) === bindingKey &&
120 whenAstToExpression(entry.whenAst) === bindingWhen,
121 );
122​
123 return isDefault ? "Default" : "Custom";
125​
126function defaultBindingForBinding(
127 binding: ResolvedKeybindingRule,
128): ResolvedKeybindingRule | undefined {
129 const bindingKey = shortcutToKeybindingInput(binding.shortcut);
130 const bindingWhen = whenAstToExpression(binding.whenAst);
131​
132 return (
133 DEFAULT_RESOLVED_KEYBINDINGS.find(
134 (entry) =>
135 entry.command === binding.command &&
136 shortcutToKeybindingInput(entry.shortcut) === bindingKey &&
137 whenAstToExpression(entry.whenAst) === bindingWhen,
138 ) ??
139 DEFAULT_RESOLVED_KEYBINDINGS.find(
140 (entry) =>
141 entry.command === binding.command && whenAstToExpression(entry.whenAst) === bindingWhen,
142 ) ??
143 DEFAULT_RESOLVED_KEYBINDINGS.find((entry) => entry.command === binding.command)
144 );
146​
147function keybindingRowId(command: KeybindingCommand, key: string, when: string): string {
148 return `${command}\u0000${key}\u0000${when}`;
150​
151function conflictsWithWhen(leftWhen: string, rightWhen: string): boolean {
152 return leftWhen.length === 0 || rightWhen.length === 0 || leftWhen === rightWhen;
154​
155export function keybindingConflictLabels(
156 rows: ReadonlyArray<KeybindingRow>,
157 input: { readonly rowId: string; readonly key: string; readonly when: string },
158): ReadonlyArray<string> {
159 if (input.key.trim().length === 0) return [];
160 const conflicts: Array<string> = [];
161 for (const candidate of rows) {
162 if (
163 candidate.id !== input.rowId &&
164 candidate.key === input.key &&
165 conflictsWithWhen(candidate.when, input.when)
166 ) {
167 conflicts.push(commandLabel(candidate.command));
168 }
169 }
170 return [...new Set(conflicts)].toSorted();
172​
173export function buildKeybindingRows(
174 keybindings: ResolvedKeybindingsConfig,
175 query: string,
176): ReadonlyArray<KeybindingRow> {
177 const normalizedQuery = query.trim().toLowerCase();
178 const rows = keybindings.map((binding, index) => {
179 const defaultBinding = defaultBindingForBinding(binding);
180 const key = shortcutToKeybindingInput(binding.shortcut);
181 const when = whenAstToExpression(binding.whenAst);
182 return {
183 id: `${keybindingRowId(binding.command, key, when)}\u0000${index}`,
184 command: binding.command,
185 key,
186 when,
187 source: sourceForBinding(binding),
188 defaultKey: defaultBinding ? shortcutToKeybindingInput(defaultBinding.shortcut) : null,
189 defaultWhen: whenAstToExpression(defaultBinding?.whenAst),
190 binding,
191 conflicts: [],
192 } satisfies KeybindingRow;
193 });
194​
195 const rowsWithConflicts = rows.map((row) => {
196 const conflicts = keybindingConflictLabels(rows, {
197 rowId: row.id,
198 key: row.key,
199 when: row.when,
200 });
201 return conflicts.length > 0
202 ? Object.assign({}, row, { conflicts: [...new Set(conflicts)].toSorted() })
203 : row;
204 });
205​
206 rowsWithConflicts.sort((left, right) => {
207 const commandCompare = left.command.localeCompare(right.command);
208 if (commandCompare !== 0) return commandCompare;
209 return left.key.localeCompare(right.key);
210 });
211​
212 if (normalizedQuery.length === 0) {
213 return rowsWithConflicts;
214 }
215​
216 return rowsWithConflicts.filter((row) => {
217 return (
218 row.command.toLowerCase().includes(normalizedQuery) ||
219 commandLabel(row.command).toLowerCase().includes(normalizedQuery) ||
220 row.key.toLowerCase().includes(normalizedQuery) ||
221 row.when.toLowerCase().includes(normalizedQuery) ||
222 row.source.toLowerCase().includes(normalizedQuery)
223 );
224 });
226​
227function collectWhenIdentifiersFromNode(
228 node: KeybindingWhenNode | undefined,
229 identifiers: Set<string>,
230): void {
231 if (!node) return;
232 switch (node.type) {
233 case "identifier":
234 identifiers.add(node.name);
235 return;
236 case "not":
237 collectWhenIdentifiersFromNode(node.node, identifiers);
238 return;
239 case "and":
240 case "or":
241 collectWhenIdentifiersFromNode(node.left, identifiers);
242 collectWhenIdentifiersFromNode(node.right, identifiers);
243 return;
244 }
246​
247export function isKnownWhenVariable(identifier: string): boolean {
248 return KNOWN_WHEN_VARIABLES.has(identifier);
250​
251export function unknownWhenVariables(node: KeybindingWhenNode | undefined): ReadonlyArray<string> {
252 const identifiers = new Set<string>();
253 collectWhenIdentifiersFromNode(node, identifiers);
254 return [...identifiers].filter((identifier) => !isKnownWhenVariable(identifier)).toSorted();
256​
257export function buildWhenVariableOptions(): ReadonlyArray<WhenVariableOption> {
258 return [...KNOWN_WHEN_VARIABLES].toSorted((left, right) => {
259 const leftCoreIndex = CORE_WHEN_VARIABLES.indexOf(left as (typeof CORE_WHEN_VARIABLES)[number]);
260 const rightCoreIndex = CORE_WHEN_VARIABLES.indexOf(
261 right as (typeof CORE_WHEN_VARIABLES)[number],
262 );
263 if (leftCoreIndex !== -1 || rightCoreIndex !== -1) {
264 return (
265 (leftCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : leftCoreIndex) -
266 (rightCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : rightCoreIndex)
267 );
268 }
269 return left.localeCompare(right);
270 });
272​
273export function buildKeybindingCommandOptions(
274 keybindings: ResolvedKeybindingsConfig,
275): ReadonlyArray<KeybindingCommandOption> {
276 const commands = new Set<KeybindingCommand>(STATIC_KEYBINDING_COMMANDS);
277 for (const binding of keybindings) {
278 commands.add(binding.command);
279 }
280 return [...commands].toSorted((left, right) =>
281 commandLabel(left).localeCompare(commandLabel(right)),
282 );
284​
285export function commandLabel(command: KeybindingCommand): string {
286 if (command === "thread.copyReference") return "Pull Request: Copy Link or Thread ID";
287 const raw = String(command);
288 if (raw.startsWith("script.") && raw.endsWith(".run")) {
289 return `Run Script: ${titleCaseCommandSegment(raw.slice("script.".length, -".run".length))}`;
290 }
291 return raw.split(".").map(titleCaseCommandSegment).join(": ");
293​
294function titleCaseCommandSegment(segment: string): string {
295 const words: Array<string> = [];
296 for (const part of segment.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[-_\s]+/)) {
297 if (part.length > 0) {
298 words.push(part.slice(0, 1).toUpperCase() + part.slice(1));
299 }
300 }
301 return words.join(" ");
303​
304function normalizeShortcutKeyToken(key: string): string | null {
305 const normalized = key.toLowerCase();
306 if (
307 normalized === "meta" ||
308 normalized === "control" ||
309 normalized === "ctrl" ||
310 normalized === "shift" ||
311 normalized === "alt" ||
312 normalized === "option"
313 ) {
314 return null;
315 }
316 if (normalized === " ") return "space";
317 if (normalized === "escape") return "esc";
318 if (normalized === "arrowup") return "arrowup";
319 if (normalized === "arrowdown") return "arrowdown";
320 if (normalized === "arrowleft") return "arrowleft";
321 if (normalized === "arrowright") return "arrowright";
322 if (normalized.length === 1) return normalized;
323 if (/^f\d{1,2}$/.test(normalized)) return normalized;
324 if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
325 return normalized;
326 }
327 if (normalized === "delete" || normalized === "home" || normalized === "end") {
328 return normalized;
329 }
330 if (normalized === "pageup" || normalized === "pagedown") return normalized;
331 return null;
333​
334export function keybindingFromKeyboardEvent(
335 event: Pick<KeyboardEvent, "key" | "code" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
336 platform: string,
337): string | null {
338 const keyToken = normalizeShortcutKeyToken(shortcutKeyFromEvent(event));
339 if (!keyToken) return null;
340​
341 const parts: string[] = [];
342 if (isMacPlatform(platform)) {
343 if (event.metaKey) parts.push("mod");
344 if (event.ctrlKey) parts.push("ctrl");
345 } else {
346 if (event.ctrlKey) parts.push("mod");
347 if (event.metaKey) parts.push("meta");
348 }
349 if (event.altKey) parts.push("alt");
350 if (event.shiftKey) parts.push("shift");
351 if (parts.length === 0) {
352 return null;
353 }
354 parts.push(keyToken);
355 return parts.join("+");