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

KeybindingsSettings.logic.ts

457 lines16.1 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 US_SHIFTED_TO_UNSHIFTED_KEYS,
13} from "@t3tools/shared/keybindings";
14​
15import { shortcutKeyFromEvent } from "../../keybindings";
16import { isMacPlatform } from "../../lib/utils";
17import { METRIC_OPTIONS, WINDOW_OPTIONS } from "../usage/usageShortcuts";
18​
19// Rank every usage command; mixing rank and alphabetical comparisons makes order input-dependent.
20const usageCommandOrder = new Map<KeybindingCommand, number>(
21 [
22 "usage.open" as const,
23 ...[...METRIC_OPTIONS, ...WINDOW_OPTIONS].map((option) => option.command),
24 ].map((command, index) => [command, index]),
25);
26​
27const firstUsageCommand = METRIC_OPTIONS[0].command;
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 interface KeybindingGroup {
199 readonly id: string;
200 readonly title: string;
201 readonly rows: ReadonlyArray<KeybindingRow>;
203​
204const KEYBINDING_GROUPS = [
205 {
206 id: "navigation",
207 title: "Navigation",
208 prefixes: ["sidebar", "rightPanel", "commandPalette", "filePicker", "projectSearch", "editor"],
209 },
210 { id: "threads", title: "Threads", prefixes: ["thread", "chat", "pullRequest"] },
211 { id: "composer", title: "Composer", prefixes: ["composer", "modelPicker"] },
212 { id: "terminal", title: "Terminal", prefixes: ["terminal"] },
213 { id: "preview", title: "Preview & diff", prefixes: ["preview", "diff"] },
214 { id: "appearance", title: "Appearance", prefixes: ["theme", "appearance", "themeEditor"] },
215 { id: "scripts", title: "Project scripts", prefixes: ["script"] },
216] as const;
217const OTHER_KEYBINDING_GROUP = { id: "other", title: "Other" } as const;
218​
219function keybindingGroupFor(command: KeybindingCommand): { id: string; title: string } {
220 const prefix = String(command).split(".")[0] ?? "";
221 return (
222 KEYBINDING_GROUPS.find((group) => (group.prefixes as ReadonlyArray<string>).includes(prefix)) ??
223 OTHER_KEYBINDING_GROUP
224 );
226​
227export function groupKeybindingRows(
228 rows: ReadonlyArray<KeybindingRow>,
229): ReadonlyArray<KeybindingGroup> {
230 const rowsByGroup = new Map<string, Array<KeybindingRow>>();
231 for (const row of rows) {
232 const group = keybindingGroupFor(row.command);
233 const bucket = rowsByGroup.get(group.id);
234 if (bucket) bucket.push(row);
235 else rowsByGroup.set(group.id, [row]);
236 }
237 return [...KEYBINDING_GROUPS, OTHER_KEYBINDING_GROUP].flatMap((group) => {
238 const groupRows = rowsByGroup.get(group.id);
239 return groupRows ? [{ id: group.id, title: group.title, rows: groupRows }] : [];
240 });
242​
243export function buildKeybindingRows(
244 keybindings: ResolvedKeybindingsConfig,
245): ReadonlyArray<KeybindingRow> {
246 const rowsById = new Map<string, KeybindingRow>();
247 for (const binding of keybindings) {
248 const defaultBinding = defaultBindingForBinding(binding);
249 const key = shortcutToKeybindingInput(binding.shortcut);
250 const when = whenAstToExpression(binding.whenAst);
251 const id = keybindingRowId(binding.command, key, when);
252 rowsById.set(id, {
253 id,
254 command: binding.command,
255 key,
256 when,
257 source: sourceForBinding(binding),
258 defaultKey: defaultBinding ? shortcutToKeybindingInput(defaultBinding.shortcut) : null,
259 defaultWhen: whenAstToExpression(defaultBinding?.whenAst),
260 binding,
261 conflicts: [],
262 });
263 }
264 const rows = [...rowsById.values()];
265​
266 const rowsWithConflicts = rows.map((row) => {
267 const conflicts = keybindingConflictLabels(rows, {
268 rowId: row.id,
269 key: row.key,
270 when: row.when,
271 });
272 return conflicts.length > 0
273 ? Object.assign({}, row, { conflicts: [...new Set(conflicts)].toSorted() })
274 : row;
275 });
276​
277 rowsWithConflicts.sort((left, right) => {
278 const commandCompare = compareCommands(left.command, right.command, (command) => command);
279 if (commandCompare !== 0) return commandCompare;
280 return left.key.localeCompare(right.key);
281 });
282​
283 return rowsWithConflicts;
285​
286export function filterKeybindingRows(
287 rows: ReadonlyArray<KeybindingRow>,
288 query: string,
289): ReadonlyArray<KeybindingRow> {
290 const normalizedQuery = query.trim().toLowerCase();
291 if (normalizedQuery.length === 0) return rows;
292 return rows.filter((row) => {
293 return (
294 row.command.toLowerCase().includes(normalizedQuery) ||
295 commandLabel(row.command).toLowerCase().includes(normalizedQuery) ||
296 row.key.toLowerCase().includes(normalizedQuery) ||
297 row.when.toLowerCase().includes(normalizedQuery) ||
298 row.source.toLowerCase().includes(normalizedQuery)
299 );
300 });
302​
303function collectWhenIdentifiersFromNode(
304 node: KeybindingWhenNode | undefined,
305 identifiers: Set<string>,
306): void {
307 if (!node) return;
308 switch (node.type) {
309 case "identifier":
310 identifiers.add(node.name);
311 return;
312 case "not":
313 collectWhenIdentifiersFromNode(node.node, identifiers);
314 return;
315 case "and":
316 case "or":
317 collectWhenIdentifiersFromNode(node.left, identifiers);
318 collectWhenIdentifiersFromNode(node.right, identifiers);
319 return;
320 }
322​
323export function isKnownWhenVariable(identifier: string): boolean {
324 return KNOWN_WHEN_VARIABLES.has(identifier);
326​
327export function unknownWhenVariables(node: KeybindingWhenNode | undefined): ReadonlyArray<string> {
328 const identifiers = new Set<string>();
329 collectWhenIdentifiersFromNode(node, identifiers);
330 return [...identifiers].filter((identifier) => !isKnownWhenVariable(identifier)).toSorted();
332​
333export function buildWhenVariableOptions(): ReadonlyArray<WhenVariableOption> {
334 return [...KNOWN_WHEN_VARIABLES].toSorted((left, right) => {
335 const leftCoreIndex = CORE_WHEN_VARIABLES.indexOf(left as (typeof CORE_WHEN_VARIABLES)[number]);
336 const rightCoreIndex = CORE_WHEN_VARIABLES.indexOf(
337 right as (typeof CORE_WHEN_VARIABLES)[number],
338 );
339 if (leftCoreIndex !== -1 || rightCoreIndex !== -1) {
340 return (
341 (leftCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : leftCoreIndex) -
342 (rightCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : rightCoreIndex)
343 );
344 }
345 return left.localeCompare(right);
346 });
348​
349export function buildKeybindingCommandOptions(
350 keybindings: ResolvedKeybindingsConfig,
351): ReadonlyArray<KeybindingCommandOption> {
352 const commands = new Set<KeybindingCommand>(STATIC_KEYBINDING_COMMANDS);
353 for (const binding of keybindings) {
354 commands.add(binding.command);
355 }
356 return [...commands].toSorted((left, right) => compareCommands(left, right, commandLabel));
358​
359export function commandLabel(command: KeybindingCommand): string {
360 if (command === "workspace.focusNext") return "Focus Next Workspace Area";
361 if (command === "workspace.focusPrevious") return "Focus Previous Workspace Area";
362 if (command === "composer.sendAlternate") return "Composer: Opposite Queue or Steer Action";
363 if (command === "composer.sendBackground") return "Composer: Start in Background";
364 if (command === "composer.sendAndNewThread") return "Composer: Send and Start New Thread";
365 if (command === "thread.steerQueuedMessage") return "Queue: Send First Queued Message";
366 if (command === "thread.editQueuedMessage") return "Queue: Edit Last Queued Message";
367 if (command === "thread.copyReference") return "Pull Request: Copy Link or Thread";
368 const usageMetric = METRIC_OPTIONS.find((option) => option.command === command);
369 if (usageMetric) return `Usage: ${usageMetric.label}`;
370 const usagePeriod = WINDOW_OPTIONS.find((option) => option.command === command);
371 if (usagePeriod) return `Usage: Period: ${usagePeriod.label}`;
372 if (command === "view.reopenClosed") return "Reopen Closed Tab";
373 if (command === "preview.focusUrl") return "Preview: Focus URL";
374 const raw = String(command);
375 if (raw.startsWith("script.") && raw.endsWith(".run")) {
376 return `Run Script: ${titleCaseCommandSegment(raw.slice("script.".length, -".run".length))}`;
377 }
378 return raw.split(".").map(titleCaseCommandSegment).join(": ");
380​
381function titleCaseCommandSegment(segment: string): string {
382 const words: Array<string> = [];
383 for (const part of segment.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[-_\s]+/)) {
384 if (part.length > 0) {
385 words.push(part.slice(0, 1).toUpperCase() + part.slice(1));
386 }
387 }
388 return words.join(" ");
390​
391function recordedLayoutShortcutKey(
392 event: Pick<KeyboardEvent, "key" | "code" | "shiftKey" | "altKey">,
393): string {
394 const physicalKey = shortcutKeyFromEvent(event);
395 const layoutKey = event.key.toLowerCase();
396 if (event.altKey || layoutKey.length !== 1) return physicalKey;
397 // Normalize only US shifted glyphs at their US position. Other layouts can
398 // produce the same glyph without Shift or at a different position.
399 const unshiftedKey = event.shiftKey ? US_SHIFTED_TO_UNSHIFTED_KEYS.get(layoutKey) : undefined;
400 return unshiftedKey === physicalKey ? physicalKey : layoutKey;
402​
403function normalizeShortcutKeyToken(key: string): string | null {
404 const normalized = key.toLowerCase();
405 if (
406 normalized === "meta" ||
407 normalized === "control" ||
408 normalized === "ctrl" ||
409 normalized === "shift" ||
410 normalized === "alt" ||
411 normalized === "option"
412 ) {
413 return null;
414 }
415 if (normalized === " ") return "space";
416 if (normalized === "escape") return "esc";
417 if (normalized === "arrowup") return "arrowup";
418 if (normalized === "arrowdown") return "arrowdown";
419 if (normalized === "arrowleft") return "arrowleft";
420 if (normalized === "arrowright") return "arrowright";
421 if (normalized.length === 1) return normalized;
422 if (/^f\d{1,2}$/.test(normalized)) return normalized;
423 if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
424 return normalized;
425 }
426 if (normalized === "delete" || normalized === "home" || normalized === "end") {
427 return normalized;
428 }
429 if (normalized === "pageup" || normalized === "pagedown") return normalized;
430 return null;
432​
433export function keybindingFromKeyboardEvent(
434 event: Pick<KeyboardEvent, "key" | "code" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
435 platform: string,
436 options?: {
437 readonly layoutCharacter?: boolean;
438 },
439): string | null {
440 const keyToken = normalizeShortcutKeyToken(
441 options?.layoutCharacter ? recordedLayoutShortcutKey(event) : shortcutKeyFromEvent(event),
442 );
443 if (!keyToken) return null;
444​
445 const parts: string[] = [];
446 if (isMacPlatform(platform)) {
447 if (event.metaKey) parts.push("mod");
448 if (event.ctrlKey) parts.push("ctrl");
449 } else {
450 if (event.ctrlKey) parts.push("mod");
451 if (event.metaKey) parts.push("meta");
452 }
453 if (event.altKey) parts.push("alt");
454 if (event.shiftKey) parts.push("shift");
455 parts.push(keyToken);
456 return parts.join("+");