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

KeybindingsSettings.logic.ts

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