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

KeybindingsSettings.tsx

1,337 lines44.6 KB

1import {
2 ChevronDownIcon,
3 CircleXIcon,
4 EllipsisIcon,
5 FileJsonIcon,
6 InfoIcon,
7 MinusIcon,
8 PlusIcon,
9 SearchIcon,
10 TriangleAlertIcon,
11 XIcon,
12} from "lucide-react";
13import {
14 type KeyboardEvent,
15 type ReactNode,
16 type RefObject,
17 useCallback,
18 useEffect,
19 useMemo,
20 useReducer,
21 useRef,
22 useState,
23} from "react";
24import {
25 type KeybindingCommand,
26 type KeybindingWhenNode,
27 type ServerRemoveKeybindingInput,
28 type ServerUpsertKeybindingInput,
29} from "@t3tools/contracts";
30import { useAtomValue } from "@effect/atom-react";
31import {
32 isAtomCommandInterrupted,
33 squashAtomCommandFailure,
34} from "@t3tools/client-runtime/state/runtime";
35​
36import { isElectron } from "../../env";
37import { useOpenInPreferredEditor } from "../../editorPreferences";
38import { formatShortcutLabel } from "../../keybindings";
39import { cn } from "../../lib/utils";
40import {
41 primaryServerAvailableEditorsAtom,
42 primaryServerKeybindingsAtom,
43 primaryServerKeybindingsConfigPathAtom,
44 serverEnvironment,
45} from "../../state/server";
46import { usePrimaryEnvironment } from "../../state/environments";
47import { Button } from "../ui/button";
48import { Input } from "../ui/input";
49import { Kbd, KbdGroup } from "../ui/kbd";
50import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
51import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
52import { ScrollArea } from "../ui/scroll-area";
53import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
54import { Toggle } from "../ui/toggle";
55import { toastManager } from "../ui/toast";
56import {
57 buildKeybindingRows,
58 buildKeybindingCommandOptions,
59 buildWhenVariableOptions,
60 commandLabel,
61 DEFAULT_WHEN_VARIABLE,
62 isKnownWhenVariable,
63 keybindingConflictLabels,
64 keybindingFromKeyboardEvent,
65 parseWhenExpressionDraft,
66 type KeybindingCommandOption,
67 type KeybindingRow,
68 type WhenVariableOption,
69 unknownWhenVariables,
70 whenAstToExpression,
71} from "./KeybindingsSettings.logic";
72import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
73import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
74import { useAtomCommand } from "../../state/use-atom-command";
75​
76function KeybindingPill({ value }: { value: string }) {
77 const parts = value.split("+");
78 return (
79 <KbdGroup className="bg-transparent p-0 shadow-none">
80 {parts.map((part) => (
81 <Kbd key={part} className="min-w-6 justify-center px-1.5">
82 {part === "mod"
83 ? navigator.platform.toLowerCase().includes("mac")
84 ? "⌘"
85 : "Ctrl"
86 : part === "shift"
87 ? "⇧"
88 : part === "alt"
89 ? navigator.platform.toLowerCase().includes("mac")
90 ? "⌥"
91 : "Alt"
92 : part === "ctrl"
93 ? "⌃"
94 : part.length === 1
95 ? part.toUpperCase()
96 : part}
97 </Kbd>
98 ))}
99 </KbdGroup>
100 );
102​
103function ExpandableHeaderSearch({
104 query,
105 onChange,
106 isOpen,
107 onOpenChange,
108 inputRef,
109 collapsedAccessory,
110}: {
111 query: string;
112 onChange: (next: string) => void;
113 isOpen: boolean;
114 onOpenChange: (next: boolean) => void;
115 inputRef?: RefObject<HTMLInputElement | null>;
116 collapsedAccessory?: ReactNode;
117}) {
118 if (!isOpen) {
119 return (
120 <>
121 {collapsedAccessory}
122 <Tooltip>
123 <TooltipTrigger
124 render={
125 <Button
126 type="button"
127 size="icon-xs"
128 variant="ghost"
129 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
130 onClick={() => onOpenChange(true)}
131 aria-label="Search keybindings"
132 >
133 <SearchIcon className="size-3" />
134 </Button>
135 }
136 />
137 <TooltipPopup side="top">Search keybindings</TooltipPopup>
138 </Tooltip>
139 </>
140 );
141 }
142​
143 return (
144 <div className="relative">
145 <SearchIcon className="pointer-events-none absolute top-1/2 left-2 size-3 -translate-y-1/2 text-muted-foreground" />
146 <input
147 ref={inputRef}
148 autoFocus
149 type="text"
150 value={query}
151 onChange={(event) => onChange(event.currentTarget.value)}
152 onBlur={() => {
153 if (query.length === 0) onOpenChange(false);
154 }}
155 onKeyDown={(event) => {
156 if (event.key === "Escape") {
157 event.preventDefault();
158 onChange("");
159 onOpenChange(false);
160 }
161 }}
162 placeholder="Search keybindings"
163 aria-label="Search keybindings"
164 className="h-6 w-44 rounded-md border border-input bg-background pl-7 pr-2 text-[11px] text-foreground outline-none placeholder:text-muted-foreground/72 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/24"
165 />
166 </div>
167 );
169​
170type BooleanOperator = "and" | "or";
171​
172function flattenWhenChildren(
173 node: KeybindingWhenNode,
174 operator: BooleanOperator,
175): KeybindingWhenNode[] {
176 if (node.type !== operator) return [node];
177 return [
178 ...flattenWhenChildren(node.left, operator),
179 ...flattenWhenChildren(node.right, operator),
180 ];
182​
183function buildWhenExpressionGroup(
184 children: readonly KeybindingWhenNode[],
185 operator: BooleanOperator,
186): KeybindingWhenNode | undefined {
187 const first = children[0];
188 if (!first) return undefined;
189 return children.slice(1).reduce<KeybindingWhenNode>(
190 (left, right) => ({
191 type: operator,
192 left,
193 right,
194 }),
195 first,
196 );
198​
199function conditionParts(node: KeybindingWhenNode): { identifier: string; negated: boolean } | null {
200 if (node.type === "identifier") return { identifier: node.name, negated: false };
201 if (node.type === "not" && node.node.type === "identifier") {
202 return { identifier: node.node.name, negated: true };
203 }
204 return null;
206​
207function setConditionIdentifier(node: KeybindingWhenNode, identifier: string): KeybindingWhenNode {
208 const parts = conditionParts(node);
209 if (!parts) return node;
210 const next: KeybindingWhenNode = { type: "identifier", name: identifier };
211 return parts.negated ? { type: "not", node: next } : next;
213​
214function setConditionNegated(node: KeybindingWhenNode, negated: boolean): KeybindingWhenNode {
215 const parts = conditionParts(node);
216 if (!parts) return negated ? { type: "not", node } : node;
217 const identifier: KeybindingWhenNode = { type: "identifier", name: parts.identifier };
218 return negated ? { type: "not", node: identifier } : identifier;
220​
221function defaultWhenCondition(): KeybindingWhenNode {
222 return { type: "identifier", name: DEFAULT_WHEN_VARIABLE };
224​
225function defaultWhenGroup(operator: BooleanOperator = "and"): KeybindingWhenNode {
226 return {
227 type: operator,
228 left: defaultWhenCondition(),
229 right: { type: "not", node: defaultWhenCondition() },
230 };
232​
233function UnknownWhenVariableWarning({
234 identifiers,
235 focusable = true,
236}: {
237 identifiers: ReadonlyArray<string>;
238 focusable?: boolean;
239}) {
240 if (identifiers.length === 0) return null;
241 const label =
242 identifiers.length === 1
243 ? `Unknown condition: ${identifiers[0]}`
244 : `Unknown conditions: ${identifiers.join(", ")}`;
245​
246 return (
247 <Tooltip>
248 <TooltipTrigger
249 render={
250 <span
251 tabIndex={focusable ? 0 : undefined}
252 aria-label={label}
253 className="inline-flex size-4.5 shrink-0 items-center justify-center rounded-sm text-warning outline-none transition-colors hover:bg-warning/10 focus-visible:ring-[3px] focus-visible:ring-warning/25"
254 >
255 <TriangleAlertIcon className="size-3.5" />
256 </span>
257 }
258 />
259 <TooltipPopup side="top" className="max-w-72 whitespace-normal leading-relaxed">
260 T3 Code does not recognize this condition yet. It can still be saved, but it may not match
261 unless the runtime provides it.
262 </TooltipPopup>
263 </Tooltip>
264 );
266​
267function KeybindingConflictWarning({ labels }: { labels: ReadonlyArray<string> }) {
268 if (labels.length === 0) return null;
269 const description =
270 labels.length === 1
271 ? `Conflicts with ${labels[0]}.`
272 : `Conflicts with ${labels.slice(0, 3).join(", ")}${labels.length > 3 ? ", and more" : ""}.`;
273​
274 return (
275 <Tooltip>
276 <TooltipTrigger
277 render={
278 <span
279 tabIndex={0}
280 aria-label={description}
281 className="inline-flex size-5 shrink-0 items-center justify-center rounded-sm text-warning outline-none transition-colors hover:bg-warning/10 focus-visible:ring-[3px] focus-visible:ring-warning/25"
282 >
283 <TriangleAlertIcon className="size-3.5" />
284 </span>
285 }
286 />
287 <TooltipPopup side="top" className="max-w-72 whitespace-normal leading-relaxed">
288 {description} The most recent matching binding wins when both conditions can apply.
289 </TooltipPopup>
290 </Tooltip>
291 );
293​
294function WhenVariableSelect({
295 value,
296 variables,
297 unknownIdentifiers,
298 onChange,
299}: {
300 value: string;
301 variables: ReadonlyArray<WhenVariableOption>;
302 unknownIdentifiers?: ReadonlyArray<string>;
303 onChange: (value: string) => void;
304}) {
305 const selected = variables.find((option) => option === value);
306 const options =
307 selected || variables.some((option) => option === value) ? variables : [value, ...variables];
308​
309 return (
310 <Select value={value} onValueChange={(nextValue) => nextValue && onChange(nextValue)}>
311 <SelectTrigger
312 size="xs"
313 className="h-7 min-h-7 min-w-0 flex-1 rounded-md font-mono text-xs sm:h-7"
314 >
315 <SelectValue placeholder="Condition" className="leading-7" />
316 {unknownIdentifiers && unknownIdentifiers.length > 0 ? (
317 <UnknownWhenVariableWarning identifiers={unknownIdentifiers} focusable={false} />
318 ) : null}
319 </SelectTrigger>
320 <SelectContent
321 alignItemWithTrigger={false}
322 matchTriggerWidth={false}
323 popupClassName="w-fit"
324 className="max-h-72 w-fit min-w-44"
325 >
326 {options.map((option) => (
327 <SelectItem
328 key={option}
329 value={option}
330 className="min-h-7 w-full py-1 font-mono text-[12px]"
331 >
332 <span className="truncate">{option}</span>
333 </SelectItem>
334 ))}
335 </SelectContent>
336 </Select>
337 );
339​
340function WhenExpressionNodeEditor({
341 node,
342 variables,
343 depth = 0,
344 onChange,
345 onRemove,
346}: {
347 node: KeybindingWhenNode;
348 variables: ReadonlyArray<WhenVariableOption>;
349 depth?: number;
350 onChange: (node: KeybindingWhenNode) => void;
351 onRemove?: () => void;
352}) {
353 const condition = conditionParts(node);
354​
355 if (condition) {
356 const unknownIdentifiers = isKnownWhenVariable(condition.identifier)
357 ? []
358 : [condition.identifier];
359​
360 return (
361 <div className="flex items-center gap-2 rounded-md border border-border/70 bg-background/60 px-2 py-2">
362 <Toggle
363 pressed={condition.negated}
364 onPressedChange={(pressed) => onChange(setConditionNegated(node, pressed))}
365 aria-label={`Negate ${condition.identifier}`}
366 variant="outline"
367 size="xs"
368 className="h-7 min-w-10 px-2 text-[11px] sm:h-7"
369 >
370 Not
371 </Toggle>
372 <WhenVariableSelect
373 value={condition.identifier}
374 variables={variables}
375 unknownIdentifiers={unknownIdentifiers}
376 onChange={(value) => onChange(setConditionIdentifier(node, value))}
377 />
378 {onRemove ? (
379 <Button
380 type="button"
381 variant="ghost"
382 size="icon-sm"
383 className="size-7 sm:size-7"
384 aria-label="Remove condition"
385 onClick={onRemove}
386 >
387 <MinusIcon className="size-3.5" />
388 </Button>
389 ) : null}
390 </div>
391 );
392 }
393​
394 if (node.type === "not") {
395 return (
396 <div
397 className={cn(
398 "space-y-2 rounded-lg border border-border/70 bg-muted/20 p-2",
399 depth > 0 && "border-border/50 bg-background/50",
400 )}
401 >
402 <div className="flex items-center gap-2">
403 <Toggle
404 pressed
405 onPressedChange={(pressed) => onChange(pressed ? node : node.node)}
406 aria-label="Negate group"
407 variant="outline"
408 size="xs"
409 className="h-7 min-w-10 px-2 text-[11px] sm:h-7"
410 >
411 Not
412 </Toggle>
413 {onRemove ? (
414 <Button
415 type="button"
416 variant="ghost"
417 size="icon-sm"
418 className="ml-auto size-7 sm:size-7"
419 aria-label="Remove negated group"
420 onClick={onRemove}
421 >
422 <MinusIcon className="size-3.5" />
423 </Button>
424 ) : null}
425 </div>
426 <div className="relative pl-4">
427 <span className="absolute top-0 bottom-0 left-1.5 w-px bg-border/70" aria-hidden />
428 <span className="absolute top-4 left-1.5 h-px w-2.5 bg-border/70" aria-hidden />
429 <WhenExpressionNodeEditor
430 node={node.node}
431 variables={variables}
432 depth={depth + 1}
433 onChange={(next) => onChange({ type: "not", node: next })}
434 />
435 </div>
436 </div>
437 );
438 }
439​
440 const operator: BooleanOperator = node.type === "or" ? "or" : "and";
441 const children = flattenWhenChildren(node, operator);
442 const childKeyCounts = new Map<string, number>();
443 const childEntries = children.map((child) => {
444 const baseKey = `${child.type}-${whenAstToExpression(child)}`;
445 const count = childKeyCounts.get(baseKey) ?? 0;
446 childKeyCounts.set(baseKey, count + 1);
447 return { child, key: count === 0 ? baseKey : `${baseKey}-${count}` };
448 });
449​
450 const updateChild = (target: KeybindingWhenNode, next: KeybindingWhenNode) => {
451 let didUpdate = false;
452 const nextChildren = children.map((child) => {
453 if (!didUpdate && child === target) {
454 didUpdate = true;
455 return next;
456 }
457 return child;
458 });
459 const nextNode = buildWhenExpressionGroup(nextChildren, operator);
460 if (nextNode) onChange(nextNode);
461 };
462​
463 const removeChild = (target: KeybindingWhenNode) => {
464 let didRemove = false;
465 const nextChildren = children.filter((child) => {
466 if (!didRemove && child === target) {
467 didRemove = true;
468 return false;
469 }
470 return true;
471 });
472 const nextNode = buildWhenExpressionGroup(nextChildren, operator);
473 if (nextNode) {
474 onChange(nextNode);
475 } else {
476 onChange(defaultWhenCondition());
477 }
478 };
479​
480 const setOperator = (nextOperator: BooleanOperator) => {
481 if (nextOperator === operator) return;
482 const nextNode = buildWhenExpressionGroup(children, nextOperator);
483 if (nextNode) onChange(nextNode);
484 };
485​
486 const addCondition = () => {
487 const nextNode = buildWhenExpressionGroup([...children, defaultWhenCondition()], operator);
488 if (nextNode) onChange(nextNode);
489 };
490​
491 const addGroup = () => {
492 const nestedOperator: BooleanOperator = operator === "and" ? "or" : "and";
493 const group: KeybindingWhenNode = {
494 type: nestedOperator,
495 left: defaultWhenCondition(),
496 right: { type: "not", node: defaultWhenCondition() },
497 };
498 const nextNode = buildWhenExpressionGroup([...children, group], operator);
499 if (nextNode) onChange(nextNode);
500 };
501​
502 return (
503 <div
504 className={cn(
505 "space-y-2 rounded-lg border border-border/60 bg-muted/10 p-2",
506 depth > 0 && "border-border/70 bg-background/55",
507 )}
508 >
509 <div className="flex flex-wrap items-center gap-2">
510 <Select value={operator} onValueChange={(value) => setOperator(value as BooleanOperator)}>
511 <SelectTrigger size="xs" className="h-7 min-h-7 w-24 rounded-md text-xs sm:h-7">
512 <SelectValue />
513 </SelectTrigger>
514 <SelectContent
515 alignItemWithTrigger={false}
516 matchTriggerWidth={false}
517 popupClassName="w-fit"
518 className="w-fit min-w-24"
519 >
520 <SelectItem value="and" className="min-h-7 py-1 font-mono text-[12px]">
521 and
522 </SelectItem>
523 <SelectItem value="or" className="min-h-7 py-1 font-mono text-[12px]">
524 or
525 </SelectItem>
526 </SelectContent>
527 </Select>
528 <Button
529 type="button"
530 variant="outline"
531 size="xs"
532 className="h-7 sm:h-7"
533 onClick={addCondition}
534 >
535 <PlusIcon className="size-3.5" />
536 Condition
537 </Button>
538 <Button type="button" variant="outline" size="xs" className="h-7 sm:h-7" onClick={addGroup}>
539 <PlusIcon className="size-3.5" />
540 Group
541 </Button>
542 {onRemove ? (
543 <Button
544 type="button"
545 variant="ghost"
546 size="icon-sm"
547 className="ml-auto size-7 sm:size-7"
548 aria-label="Remove group"
549 onClick={onRemove}
550 >
551 <MinusIcon className="size-3.5" />
552 </Button>
553 ) : null}
554 </div>
555 <div className="space-y-2">
556 {childEntries.map(({ child, key }) => (
557 <div key={key} className="relative pl-4">
558 <span
559 className={cn(
560 "absolute top-0 bottom-0 left-1.5 w-px",
561 depth === 0 ? "bg-border" : "bg-border/70",
562 )}
563 aria-hidden
564 />
565 <span
566 className={cn(
567 "absolute top-4 left-1.5 h-px w-2.5",
568 depth === 0 ? "bg-border" : "bg-border/70",
569 )}
570 aria-hidden
571 />
572 <WhenExpressionNodeEditor
573 node={child}
574 variables={variables}
575 depth={depth + 1}
576 onChange={(next) => updateChild(child, next)}
577 onRemove={() => removeChild(child)}
578 />
579 </div>
580 ))}
581 </div>
582 </div>
583 );
585​
586function WhenExpressionBuilder({
587 value,
588 variables,
589 onChange,
590 onValidityChange,
591}: {
592 value: KeybindingWhenNode | undefined;
593 variables: ReadonlyArray<WhenVariableOption>;
594 onChange: (value: KeybindingWhenNode | undefined) => void;
595 onValidityChange?: (valid: boolean) => void;
596}) {
597 const expression = whenAstToExpression(value);
598 const [expressionDraft, setExpressionDraft] = useState(expression);
599 const parseResult = useMemo(() => parseWhenExpressionDraft(expressionDraft), [expressionDraft]);
600 const parseError = parseResult.ok ? null : parseResult.message;
601 const unknownIdentifiers = parseResult.ok ? unknownWhenVariables(parseResult.value) : [];
602​
603 const updateExpressionDraft = (nextExpression: string) => {
604 setExpressionDraft(nextExpression);
605 const nextResult = parseWhenExpressionDraft(nextExpression);
606 onValidityChange?.(nextResult.ok);
607 if (nextResult.ok) {
608 onChange(nextResult.value);
609 }
610 };
611​
612 const updateExpressionValue = (nextValue: KeybindingWhenNode | undefined) => {
613 setExpressionDraft(whenAstToExpression(nextValue));
614 onValidityChange?.(true);
615 onChange(nextValue);
616 };
617​
618 const addRootCondition = () => {
619 if (!value) {
620 updateExpressionValue(defaultWhenCondition());
621 return;
622 }
623 updateExpressionValue({ type: "and", left: value, right: defaultWhenCondition() });
624 };
625​
626 const addRootGroup = () => {
627 const group = defaultWhenGroup("or");
628 if (!value) {
629 updateExpressionValue(group);
630 return;
631 }
632 updateExpressionValue({ type: "and", left: value, right: group });
633 };
634​
635 return (
636 <div className="w-[min(34rem,calc(100vw-2rem))] space-y-3">
637 <div className="flex items-start justify-between gap-3">
638 <div className="min-w-0">
639 <div className="text-sm font-medium text-foreground">When</div>
640 </div>
641 <div className="flex shrink-0 items-center gap-2">
642 <Button
643 type="button"
644 variant="outline"
645 size="xs"
646 className="h-7 sm:h-7"
647 onClick={addRootCondition}
648 >
649 <PlusIcon className="size-3.5" />
650 Condition
651 </Button>
652 <Button
653 type="button"
654 variant="outline"
655 size="xs"
656 className="h-7 sm:h-7"
657 onClick={addRootGroup}
658 >
659 <PlusIcon className="size-3.5" />
660 Group
661 </Button>
662 </div>
663 </div>
664​
665 <div className="space-y-1.5">
666 <div className="relative">
667 <Input
668 value={expressionDraft}
669 onChange={(event) => updateExpressionDraft(event.currentTarget.value)}
670 placeholder="Always"
671 aria-invalid={Boolean(parseError)}
672 aria-label="When expression"
673 className={cn(
674 "h-7 rounded-md font-mono text-[12px] leading-7 sm:h-7 sm:leading-7",
675 unknownIdentifiers.length > 0 && "pr-9",
676 parseError && "border-destructive/70 focus-visible:border-destructive",
677 )}
678 />
679 {unknownIdentifiers.length > 0 ? (
680 <span className="absolute inset-y-0 right-2 flex items-center">
681 <UnknownWhenVariableWarning identifiers={unknownIdentifiers} />
682 </span>
683 ) : null}
684 </div>
685 {parseError ? (
686 <div className="flex items-center gap-1.5 text-[11px] text-destructive">
687 <CircleXIcon className="size-3.5" />
688 {parseError}
689 </div>
690 ) : null}
691 </div>
692​
693 <div className="relative">
694 {value ? (
695 <WhenExpressionNodeEditor
696 node={value}
697 variables={variables}
698 onChange={updateExpressionValue}
699 onRemove={() => updateExpressionValue(undefined)}
700 />
701 ) : (
702 <div className="rounded-md border border-dashed border-border/80 bg-muted/15 p-3">
703 <div className="flex flex-wrap gap-2">
704 <Button type="button" size="xs" className="h-7 sm:h-7" onClick={addRootCondition}>
705 <PlusIcon className="size-3.5" />
706 Condition
707 </Button>
708 <Button
709 type="button"
710 variant="outline"
711 size="xs"
712 className="h-7 sm:h-7"
713 onClick={addRootGroup}
714 >
715 <PlusIcon className="size-3.5" />
716 Group
717 </Button>
718 </div>
719 </div>
720 )}
721 {parseError ? (
722 <div className="pointer-events-none absolute inset-0 flex items-center justify-center rounded-lg border border-destructive/30 bg-background/75 p-4 text-center text-xs text-destructive backdrop-blur-[1px]">
723 Fix the expression above to continue editing visually.
724 </div>
725 ) : null}
726 </div>
727 </div>
728 );
730​
731type KeybindingRowDraftState = {
732 keyDraft: string;
733 whenDraft: KeybindingWhenNode | undefined;
734 isRecording: boolean;
735 isWhenDraftValid: boolean;
736};
737​
738function createKeybindingRowDraft(row: KeybindingRow): KeybindingRowDraftState {
739 return {
740 keyDraft: row.key,
741 whenDraft: row.binding.whenAst,
742 isRecording: false,
743 isWhenDraftValid: true,
744 };
746​
747function keybindingRowDraftReducer(
748 state: KeybindingRowDraftState,
749 patch: Partial<KeybindingRowDraftState>,
750): KeybindingRowDraftState {
751 return { ...state, ...patch };
753​
754function rowKeybindingTarget(row: KeybindingRow): ServerRemoveKeybindingInput {
755 return {
756 command: row.command,
757 key: row.key,
758 ...(row.when.trim().length > 0 ? { when: row.when } : {}),
759 };
761​
762function KeybindingTableRow({
763 row,
764 allRows,
765 variables,
766 isSaving,
767 onSave,
768 onReset,
769 onRemove,
770}: {
771 row: KeybindingRow;
772 allRows: ReadonlyArray<KeybindingRow>;
773 variables: ReadonlyArray<WhenVariableOption>;
774 isSaving: boolean;
775 onSave: (input: ServerUpsertKeybindingInput) => void;
776 onReset: (row: KeybindingRow) => void;
777 onRemove: (row: KeybindingRow) => void;
778}) {
779 const [draft, setDraft] = useReducer(keybindingRowDraftReducer, row, createKeybindingRowDraft);
780 const { keyDraft, whenDraft, isRecording, isWhenDraftValid } = draft;
781 const whenDraftExpression = whenAstToExpression(whenDraft);
782 const isDirty = keyDraft !== row.key || whenDraftExpression !== row.when;
783 const displayShortcut = formatShortcutLabel(row.binding.shortcut);
784 const canReset = row.source === "Custom" && row.defaultKey !== null;
785 const canRemove = row.source !== "Default";
786 const hasRowActions = canReset || canRemove;
787 const showPill = !isRecording && keyDraft === row.key && row.key.length > 0 && !isDirty;
788 const conflictLabels = keybindingConflictLabels(allRows, {
789 rowId: row.id,
790 key: keyDraft,
791 when: whenDraftExpression,
792 });
793​
794 const save = () => {
795 onSave({
796 command: row.command,
797 key: keyDraft,
798 when: whenDraftExpression.trim().length > 0 ? whenDraftExpression : undefined,
799 replace: rowKeybindingTarget(row),
800 });
801 };
802​
803 const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
804 if (event.key === "Tab") return;
805 event.preventDefault();
806 if (event.key === "Escape") {
807 setDraft({ keyDraft: row.key, isRecording: false });
808 return;
809 }
810 const next = keybindingFromKeyboardEvent(event.nativeEvent, navigator.platform);
811 if (!next) return;
812 setDraft({ keyDraft: next, isRecording: false });
813 };
814​
815 return (
816 <div className="grid grid-cols-[minmax(190px,1.1fr)_minmax(220px,0.85fr)_minmax(210px,1fr)_60px] items-center px-4 py-1.5 text-sm even:bg-muted/15 hover:bg-accent/40">
817 <div className="min-w-0 pr-4">
818 <div className="flex min-w-0 items-center gap-1.5">
819 <Tooltip>
820 <TooltipTrigger
821 render={
822 <div
823 aria-label={row.command}
824 className="truncate text-[13px] font-medium text-foreground"
825 />
826 }
827 >
828 {commandLabel(row.command)}
829 </TooltipTrigger>
830 <TooltipPopup side="top">{row.command}</TooltipPopup>
831 </Tooltip>
832 </div>
833 </div>
834 <div className="flex min-w-0 items-center gap-2 pr-4">
835 {showPill ? (
836 <button
837 type="button"
838 onClick={() => setDraft({ isRecording: true })}
839 aria-label={`Edit shortcut for ${commandLabel(row.command)}`}
840 className="group inline-flex h-7 items-center gap-1.5 rounded-md border border-transparent px-1.5 outline-none transition-colors hover:border-border/70 hover:bg-background focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/24"
841 >
842 <KeybindingPill value={row.key} />
843 <span className="text-[10px] uppercase tracking-[0.08em] text-muted-foreground/0 transition-opacity group-hover:text-muted-foreground/70 group-focus-visible:text-muted-foreground/70">
844 Edit
845 </span>
846 </button>
847 ) : (
848 <Input
849 data-keybinding-capture=""
850 autoFocus={isRecording}
851 aria-label={`Keybinding for ${commandLabel(row.command)}`}
852 value={isRecording ? "" : keyDraft}
853 placeholder={isRecording ? "Press shortcut" : "Unassigned"}
854 className={cn(
855 "h-7 w-44 rounded-md font-mono text-[12px] sm:h-7",
856 isRecording && "border-primary/70 bg-primary/5",
857 )}
858 onFocus={() => setDraft({ isRecording: true })}
859 onBlur={() => setDraft({ isRecording: false })}
860 onChange={(event) => setDraft({ keyDraft: event.currentTarget.value })}
861 onKeyDown={captureKeybinding}
862 />
863 )}
864 {isDirty ? (
865 <Button
866 size="xs"
867 className="h-7 sm:h-7"
868 disabled={isSaving || keyDraft.trim().length === 0 || !isWhenDraftValid}
869 onClick={save}
870 >
871 {isSaving ? "Saving" : "Save"}
872 </Button>
873 ) : null}
874 </div>
875 <div className="pr-4">
876 <Popover>
877 <PopoverTrigger
878 className={cn(
879 "inline-flex h-7 w-full items-center justify-between gap-2 rounded-md border border-input bg-background px-2.5 text-left font-mono text-[12px] text-foreground shadow-xs/5 outline-none transition-colors hover:bg-accent focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/24",
880 !whenDraftExpression && "text-muted-foreground",
881 )}
882 aria-label={`Edit when clause for ${commandLabel(row.command)}`}
883 >
884 <span className="truncate">{whenDraftExpression || "Always"}</span>
885 <ChevronDownIcon className="size-3.5 shrink-0 opacity-60" />
886 </PopoverTrigger>
887 <PopoverContent align="start" sideOffset={6}>
888 <WhenExpressionBuilder
889 value={whenDraft}
890 variables={variables}
891 onChange={(nextWhenDraft) => setDraft({ whenDraft: nextWhenDraft })}
892 onValidityChange={(nextIsValid) => setDraft({ isWhenDraftValid: nextIsValid })}
893 />
894 </PopoverContent>
895 </Popover>
896 </div>
897 <div className="flex items-center justify-end gap-1">
898 <KeybindingConflictWarning labels={conflictLabels} />
899 {hasRowActions ? (
900 <Menu>
901 <MenuTrigger
902 render={
903 <Button
904 type="button"
905 variant="ghost"
906 size="icon-sm"
907 className="size-7 text-muted-foreground hover:text-foreground sm:size-7"
908 disabled={isSaving}
909 aria-label={`Actions for ${commandLabel(row.command)}`}
910 />
911 }
912 >
913 <EllipsisIcon className="size-3.5" />
914 </MenuTrigger>
915 <MenuPopup align="end" className="min-w-36">
916 {canReset ? (
917 <MenuItem disabled={isSaving} onClick={() => onReset(row)}>
918 Reset to default
919 </MenuItem>
920 ) : null}
921 {canRemove ? (
922 <MenuItem variant="destructive" disabled={isSaving} onClick={() => onRemove(row)}>
923 Remove
924 </MenuItem>
925 ) : null}
926 </MenuPopup>
927 </Menu>
928 ) : null}
929 <span className="sr-only">{displayShortcut}</span>
930 </div>
931 </div>
932 );
934​
935function NewKeybindingTableRow({
936 commandOptions,
937 allRows,
938 variables,
939 isSaving,
940 onSave,
941 onCancel,
942}: {
943 commandOptions: ReadonlyArray<KeybindingCommandOption>;
944 allRows: ReadonlyArray<KeybindingRow>;
945 variables: ReadonlyArray<WhenVariableOption>;
946 isSaving: boolean;
947 onSave: (input: ServerUpsertKeybindingInput) => void;
948 onCancel: () => void;
949}) {
950 const [commandDraft, setCommandDraft] = useState<KeybindingCommand | "">("");
951 const [draft, setDraft] = useReducer(keybindingRowDraftReducer, {
952 keyDraft: "",
953 whenDraft: undefined,
954 isRecording: false,
955 isWhenDraftValid: true,
956 });
957 const { keyDraft, whenDraft, isRecording, isWhenDraftValid } = draft;
958 const whenDraftExpression = whenAstToExpression(whenDraft);
959 const conflictLabels = keybindingConflictLabels(allRows, {
960 rowId: "new",
961 key: keyDraft,
962 when: whenDraftExpression,
963 });
964 const commandLabelText = commandDraft ? commandLabel(commandDraft) : "new keybinding";
965​
966 const save = () => {
967 if (!commandDraft) return;
968 onSave({
969 command: commandDraft,
970 key: keyDraft,
971 ...(whenDraftExpression.trim().length > 0 ? { when: whenDraftExpression } : {}),
972 });
973 };
974​
975 const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
976 if (event.key === "Tab") return;
977 event.preventDefault();
978 if (event.key === "Escape") {
979 setDraft({ keyDraft: "", isRecording: false });
980 return;
981 }
982 const next = keybindingFromKeyboardEvent(event.nativeEvent, navigator.platform);
983 if (!next) return;
984 setDraft({ keyDraft: next, isRecording: false });
985 };
986​
987 return (
988 <div className="grid grid-cols-[minmax(190px,1.1fr)_minmax(220px,0.85fr)_minmax(210px,1fr)_60px] items-center px-4 py-1.5 text-sm even:bg-muted/15 hover:bg-accent/40">
989 <div className="min-w-0 pr-4">
990 <Select
991 value={commandDraft}
992 onValueChange={(value) => setCommandDraft(value as KeybindingCommand)}
993 >
994 <SelectTrigger
995 size="xs"
996 className="h-7 min-h-7 w-full max-w-60 rounded-md text-xs sm:h-7"
997 >
998 <SelectValue placeholder="Command" />
999 </SelectTrigger>
1000 <SelectContent
1001 alignItemWithTrigger={false}
1002 matchTriggerWidth={false}
1003 className="max-h-72 w-fit min-w-56"
1005 {commandOptions.map((command) => (
1006 <SelectItem key={command} value={command} className="min-h-7 w-full py-1 text-[12px]">
1007 <span className="truncate">{commandLabel(command)}</span>
1008 </SelectItem>
1009 ))}
1010 </SelectContent>
1011 </Select>
1012 </div>
1013 <div className="flex min-w-0 items-center gap-2 pr-4">
1014 <Input
1015 data-keybinding-capture=""
1016 aria-label={`Keybinding for ${commandLabelText}`}
1017 value={isRecording ? "" : keyDraft}
1018 placeholder={isRecording ? "Press shortcut" : "Unassigned"}
1019 className={cn(
1020 "h-7 w-44 rounded-md font-mono text-[12px] sm:h-7",
1021 isRecording && "border-primary/70 bg-primary/5",
1022 )}
1023 onFocus={() => setDraft({ isRecording: true })}
1024 onBlur={() => setDraft({ isRecording: false })}
1025 onChange={(event) => setDraft({ keyDraft: event.currentTarget.value })}
1026 onKeyDown={captureKeybinding}
1027 />
1028 <Button
1029 size="xs"
1030 className="h-7 sm:h-7"
1031 disabled={isSaving || !commandDraft || keyDraft.trim().length === 0 || !isWhenDraftValid}
1032 onClick={save}
1034 {isSaving ? "Saving" : "Save"}
1035 </Button>
1036 </div>
1037 <div className="pr-4">
1038 <Popover>
1039 <PopoverTrigger
1040 className={cn(
1041 "inline-flex h-7 w-full items-center justify-between gap-2 rounded-md border border-input bg-background px-2.5 text-left font-mono text-[12px] text-foreground shadow-xs/5 outline-none transition-colors hover:bg-accent focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/24",
1042 !whenDraftExpression && "text-muted-foreground",
1043 )}
1044 aria-label={`Edit when clause for ${commandLabelText}`}
1046 <span className="truncate">{whenDraftExpression || "Always"}</span>
1047 <ChevronDownIcon className="size-3.5 shrink-0 opacity-60" />
1048 </PopoverTrigger>
1049 <PopoverContent align="start" sideOffset={6}>
1050 <WhenExpressionBuilder
1051 value={whenDraft}
1052 variables={variables}
1053 onChange={(nextWhenDraft) => setDraft({ whenDraft: nextWhenDraft })}
1054 onValidityChange={(nextIsValid) => setDraft({ isWhenDraftValid: nextIsValid })}
1055 />
1056 </PopoverContent>
1057 </Popover>
1058 </div>
1059 <div className="flex items-center justify-end gap-1">
1060 <KeybindingConflictWarning labels={conflictLabels} />
1061 <Tooltip>
1062 <TooltipTrigger
1063 render={
1064 <Button
1065 type="button"
1066 variant="ghost"
1067 size="icon-sm"
1068 className="size-7 text-muted-foreground hover:text-foreground sm:size-7"
1069 disabled={isSaving}
1070 aria-label="Cancel new keybinding"
1071 onClick={onCancel}
1072 />
1075 <XIcon className="size-3.5" />
1076 </TooltipTrigger>
1077 <TooltipPopup side="top">Cancel</TooltipPopup>
1078 </Tooltip>
1079 </div>
1080 </div>
1081 );
1083​
1084export function KeybindingsSettingsPanel() {
1085 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
1086 const keybindingsConfigPath = useAtomValue(primaryServerKeybindingsConfigPathAtom);
1087 const availableEditors = useAtomValue(primaryServerAvailableEditorsAtom);
1088 const primaryEnvironment = usePrimaryEnvironment();
1089 const upsertKeybinding = useAtomCommand(serverEnvironment.upsertKeybinding, {
1090 reportFailure: false,
1091 });
1092 const removeKeybindingMutation = useAtomCommand(serverEnvironment.removeKeybinding, {
1093 reportFailure: false,
1094 });
1095 const openInPreferredEditor = useOpenInPreferredEditor(
1096 primaryEnvironment?.environmentId ?? null,
1097 availableEditors,
1098 );
1099 const [query, setQuery] = useState("");
1100 const [isSearchOpen, setIsSearchOpen] = useState(false);
1101 const searchInputRef = useRef<HTMLInputElement>(null);
1102 const [savingCommand, setSavingCommand] = useState<KeybindingCommand | null>(null);
1103 const [isAddingBinding, setIsAddingBinding] = useState(false);
1104 const rows = useMemo(() => buildKeybindingRows(keybindings, query), [keybindings, query]);
1105 const commandOptions = useMemo(() => buildKeybindingCommandOptions(keybindings), [keybindings]);
1106 const whenVariables = useMemo(() => buildWhenVariableOptions(), []);
1107​
1108 useEffect(() => {
1109 const handleKeyDown = (event: globalThis.KeyboardEvent) => {
1110 const isMod = event.metaKey || event.ctrlKey;
1111 if (!isMod || event.altKey || event.key.toLowerCase() !== "f") return;
1112​
1113 const target = event.target;
1114 if (
1115 target !== searchInputRef.current &&
1116 target instanceof HTMLElement &&
1117 (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable)
1118 ) {
1119 return;
1121​
1122 event.preventDefault();
1123 setIsSearchOpen(true);
1124 requestAnimationFrame(() => {
1125 searchInputRef.current?.focus();
1126 searchInputRef.current?.select();
1127 });
1128 };
1129 window.addEventListener("keydown", handleKeyDown);
1130 return () => window.removeEventListener("keydown", handleKeyDown);
1131 }, []);
1132​
1133 const openKeybindingsFile = useCallback(() => {
1134 if (!keybindingsConfigPath) return;
1135 void (async () => {
1136 const result = await openInPreferredEditor(keybindingsConfigPath);
1137 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
1138 return;
1140 const error = squashAtomCommandFailure(result);
1141 toastManager.add({
1142 title: "Unable to open keybindings file",
1143 description:
1144 error instanceof Error ? error.message : "The keybindings file was not opened.",
1145 type: "error",
1146 });
1147 })();
1148 }, [keybindingsConfigPath, openInPreferredEditor]);
1149​
1150 const saveKeybinding = useCallback(
1151 (input: ServerUpsertKeybindingInput) => {
1152 if (!primaryEnvironment) return;
1153 setSavingCommand(input.command);
1154 const payload: ServerUpsertKeybindingInput = {
1155 command: input.command,
1156 key: input.key.trim(),
1157 ...(input.when?.trim() ? { when: input.when.trim() } : {}),
1158 ...(input.replace ? { replace: input.replace } : {}),
1159 };
1160 void (async () => {
1161 const result = await upsertKeybinding({
1162 environmentId: primaryEnvironment.environmentId,
1163 input: payload,
1164 });
1165 setSavingCommand(null);
1166 if (result._tag === "Success") {
1167 setIsAddingBinding(false);
1168 return;
1170 if (!isAtomCommandInterrupted(result)) {
1171 const error = squashAtomCommandFailure(result);
1172 toastManager.add({
1173 title: "Unable to save keybinding",
1174 description: error instanceof Error ? error.message : "The keybinding was not saved.",
1175 type: "error",
1176 });
1178 })();
1179 },
1180 [primaryEnvironment, upsertKeybinding],
1181 );
1182​
1183 const removeKeybinding = useCallback(
1184 (row: KeybindingRow) => {
1185 if (!primaryEnvironment) return;
1186 setSavingCommand(row.command);
1187 void (async () => {
1188 const result = await removeKeybindingMutation({
1189 environmentId: primaryEnvironment.environmentId,
1190 input: rowKeybindingTarget(row),
1191 });
1192 setSavingCommand(null);
1193 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1194 const error = squashAtomCommandFailure(result);
1195 toastManager.add({
1196 title: "Unable to remove keybinding",
1197 description: error instanceof Error ? error.message : "The keybinding was not removed.",
1198 type: "error",
1199 });
1201 })();
1202 },
1203 [primaryEnvironment, removeKeybindingMutation],
1204 );
1205​
1206 const resetKeybinding = useCallback(
1207 (row: KeybindingRow) => {
1208 if (!row.defaultKey) return;
1209 saveKeybinding({
1210 command: row.command,
1211 key: row.defaultKey,
1212 when: row.defaultWhen.trim().length > 0 ? row.defaultWhen : undefined,
1213 replace: {
1214 command: row.command,
1215 key: row.key,
1216 ...(row.when.trim().length > 0 ? { when: row.when } : {}),
1217 },
1218 });
1219 },
1220 [saveKeybinding],
1221 );
1222​
1223 const bindingsCount = (
1224 <span className="text-[11px] text-muted-foreground">
1225 {rows.length + (isAddingBinding ? 1 : 0)}{" "}
1226 {rows.length + (isAddingBinding ? 1 : 0) === 1 ? "binding" : "bindings"}
1227 </span>
1228 );
1229​
1230 return (
1231 <SettingsPageContainer className="max-w-5xl">
1232 <SettingsSection
1233 title="Keybindings"
1234 headerAction={
1235 <div className="flex items-center gap-1.5">
1236 <ExpandableHeaderSearch
1237 query={query}
1238 onChange={setQuery}
1239 isOpen={isSearchOpen}
1240 onOpenChange={setIsSearchOpen}
1241 inputRef={searchInputRef}
1242 collapsedAccessory={bindingsCount}
1243 />
1244 <Tooltip>
1245 <TooltipTrigger
1246 render={
1247 <Button
1248 type="button"
1249 size="icon-xs"
1250 variant="ghost"
1251 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
1252 onClick={() => setIsAddingBinding(true)}
1253 aria-label="Add keybinding"
1255 <PlusIcon className="size-3" />
1256 </Button>
1258 />
1259 <TooltipPopup side="top">Add keybinding</TooltipPopup>
1260 </Tooltip>
1261 <Tooltip>
1262 <TooltipTrigger
1263 render={
1264 <Button
1265 type="button"
1266 size="icon-xs"
1267 variant="ghost"
1268 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
1269 disabled={!keybindingsConfigPath}
1270 onClick={openKeybindingsFile}
1271 aria-label="Open keybindings.json"
1273 <FileJsonIcon className="size-3" />
1274 </Button>
1276 />
1277 <TooltipPopup side="top">Open keybindings.json</TooltipPopup>
1278 </Tooltip>
1279 </div>
1282 {!isElectron ? (
1283 <div className="flex items-start gap-2 border-b border-warning/20 bg-warning/5 px-3 py-2.5 text-[12px] leading-relaxed text-muted-foreground sm:px-4">
1284 <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
1285 <p>
1286 Some shortcuts may be claimed by the browser before T3 Code sees them. Use the desktop
1287 app for better keybinding support.
1288 </p>
1289 </div>
1290 ) : null}
1291​
1292 <ScrollArea
1293 chainVerticalScroll
1294 scrollFade
1295 hideScrollbars
1296 className="w-full max-w-full rounded-none"
1298 <div className="grid min-w-[680px] grid-cols-[minmax(190px,1.1fr)_minmax(220px,0.85fr)_minmax(210px,1fr)_60px] border-b border-border/70 bg-muted/25 px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.07em] text-muted-foreground">
1299 <div>Command</div>
1300 <div>Keybinding</div>
1301 <div>When</div>
1302 <div>Status</div>
1303 </div>
1304 <div className="min-w-[680px] divide-y divide-border/60">
1305 {isAddingBinding ? (
1306 <NewKeybindingTableRow
1307 commandOptions={commandOptions}
1308 allRows={rows}
1309 variables={whenVariables}
1310 isSaving={savingCommand !== null}
1311 onSave={saveKeybinding}
1312 onCancel={() => setIsAddingBinding(false)}
1313 />
1314 ) : null}
1315 {rows.map((row) => (
1316 <KeybindingTableRow
1317 key={row.id}
1318 row={row}
1319 allRows={rows}
1320 variables={whenVariables}
1321 isSaving={savingCommand === row.command}
1322 onSave={saveKeybinding}
1323 onReset={resetKeybinding}
1324 onRemove={removeKeybinding}
1325 />
1326 ))}
1327 {rows.length === 0 && !isAddingBinding ? (
1328 <div className="px-4 py-12 text-center text-sm text-muted-foreground">
1329 No keybindings match your search.
1330 </div>
1331 ) : null}
1332 </div>
1333 </ScrollArea>
1334 </SettingsSection>
1335 </SettingsPageContainer>
1336 );