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