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

KeybindingsSettings.tsx

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