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 { 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 );
101}
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 );
168}
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 ];
181}
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 );
197}
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;
205}
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;
212}
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;
219}
220
221function defaultWhenCondition(): KeybindingWhenNode {
222 return { type: "identifier", name: DEFAULT_WHEN_VARIABLE };
223}
224
225function defaultWhenGroup(operator: BooleanOperator = "and"): KeybindingWhenNode {
226 return {
227 type: operator,
228 left: defaultWhenCondition(),
229 right: { type: "not", node: defaultWhenCondition() },
230 };
231}
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 );
265}
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 );
292}
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 );
338}
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 );
584}
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 );
729}
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 };
745}
746
747function keybindingRowDraftReducer(
748 state: KeybindingRowDraftState,
749 patch: Partial<KeybindingRowDraftState>,
750): KeybindingRowDraftState {
751 return { ...state, ...patch };
752}
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 };
760}
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 autoFocus={isRecording}
850 aria-label={`Keybinding for ${commandLabel(row.command)}`}
851 value={isRecording ? "" : keyDraft}
852 placeholder={isRecording ? "Press shortcut" : "Unassigned"}
853 className={cn(
854 "h-7 w-44 rounded-md font-mono text-[12px] sm:h-7",
855 isRecording && "border-primary/70 bg-primary/5",
856 )}
857 onFocus={() => setDraft({ isRecording: true })}
858 onBlur={() => setDraft({ isRecording: false })}
859 onChange={(event) => setDraft({ keyDraft: event.currentTarget.value })}
860 onKeyDown={captureKeybinding}
861 />
862 )}
863 {isDirty ? (
864 <Button
865 size="xs"
866 className="h-7 sm:h-7"
867 disabled={isSaving || keyDraft.trim().length === 0 || !isWhenDraftValid}
868 onClick={save}
869 >
870 {isSaving ? "Saving" : "Save"}
871 </Button>
872 ) : null}
873 </div>
874 <div className="pr-4">
875 <Popover>
876 <PopoverTrigger
877 className={cn(
878 "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",
879 !whenDraftExpression && "text-muted-foreground",
880 )}
881 aria-label={`Edit when clause for ${commandLabel(row.command)}`}
882 >
883 <span className="truncate">{whenDraftExpression || "Always"}</span>
884 <ChevronDownIcon className="size-3.5 shrink-0 opacity-60" />
885 </PopoverTrigger>
886 <PopoverContent align="start" sideOffset={6}>
887 <WhenExpressionBuilder
888 value={whenDraft}
889 variables={variables}
890 onChange={(nextWhenDraft) => setDraft({ whenDraft: nextWhenDraft })}
891 onValidityChange={(nextIsValid) => setDraft({ isWhenDraftValid: nextIsValid })}
892 />
893 </PopoverContent>
894 </Popover>
895 </div>
896 <div className="flex items-center justify-end gap-1">
897 <KeybindingConflictWarning labels={conflictLabels} />
898 {hasRowActions ? (
899 <Menu>
900 <MenuTrigger
901 render={
902 <Button
903 type="button"
904 variant="ghost"
905 size="icon-sm"
906 className="size-7 text-muted-foreground hover:text-foreground sm:size-7"
907 disabled={isSaving}
908 aria-label={`Actions for ${commandLabel(row.command)}`}
909 />
910 }
911 >
912 <EllipsisIcon className="size-3.5" />
913 </MenuTrigger>
914 <MenuPopup align="end" className="min-w-36">
915 {canReset ? (
916 <MenuItem disabled={isSaving} onClick={() => onReset(row)}>
917 Reset to default
918 </MenuItem>
919 ) : null}
920 {canRemove ? (
921 <MenuItem variant="destructive" disabled={isSaving} onClick={() => onRemove(row)}>
922 Remove
923 </MenuItem>
924 ) : null}
925 </MenuPopup>
926 </Menu>
927 ) : null}
928 <span className="sr-only">{displayShortcut}</span>
929 </div>
930 </div>
931 );
932}
933
934function NewKeybindingTableRow({
935 commandOptions,
936 allRows,
937 variables,
938 isSaving,
939 onSave,
940 onCancel,
941}: {
942 commandOptions: ReadonlyArray<KeybindingCommandOption>;
943 allRows: ReadonlyArray<KeybindingRow>;
944 variables: ReadonlyArray<WhenVariableOption>;
945 isSaving: boolean;
946 onSave: (input: ServerUpsertKeybindingInput) => void;
947 onCancel: () => void;
948}) {
949 const [commandDraft, setCommandDraft] = useState<KeybindingCommand | "">("");
950 const [draft, setDraft] = useReducer(keybindingRowDraftReducer, {
951 keyDraft: "",
952 whenDraft: undefined,
953 isRecording: false,
954 isWhenDraftValid: true,
955 });
956 const { keyDraft, whenDraft, isRecording, isWhenDraftValid } = draft;
957 const whenDraftExpression = whenAstToExpression(whenDraft);
958 const conflictLabels = keybindingConflictLabels(allRows, {
959 rowId: "new",
960 key: keyDraft,
961 when: whenDraftExpression,
962 });
963 const commandLabelText = commandDraft ? commandLabel(commandDraft) : "new keybinding";
964
965 const save = () => {
966 if (!commandDraft) return;
967 onSave({
968 command: commandDraft,
969 key: keyDraft,
970 ...(whenDraftExpression.trim().length > 0 ? { when: whenDraftExpression } : {}),
971 });
972 };
973
974 const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
975 if (event.key === "Tab") return;
976 event.preventDefault();
977 if (event.key === "Escape") {
978 setDraft({ keyDraft: "", isRecording: false });
979 return;
980 }
981 const next = keybindingFromKeyboardEvent(event.nativeEvent, navigator.platform);
982 if (!next) return;
983 setDraft({ keyDraft: next, isRecording: false });
984 };
985
986 return (
987 <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">
988 <div className="min-w-0 pr-4">
989 <Select
990 value={commandDraft}
991 onValueChange={(value) => setCommandDraft(value as KeybindingCommand)}
992 >
993 <SelectTrigger
994 size="xs"
995 className="h-7 min-h-7 w-full max-w-60 rounded-md text-xs sm:h-7"
996 >
997 <SelectValue placeholder="Command" />
998 </SelectTrigger>
999 <SelectContent
1000 alignItemWithTrigger={false}
1001 matchTriggerWidth={false}
1002 className="max-h-72 w-fit min-w-56"
1003 >
1004 {commandOptions.map((command) => (
1005 <SelectItem key={command} value={command} className="min-h-7 w-full py-1 text-[12px]">
1006 <span className="truncate">{commandLabel(command)}</span>
1007 </SelectItem>
1008 ))}
1009 </SelectContent>
1010 </Select>
1011 </div>
1012 <div className="flex min-w-0 items-center gap-2 pr-4">
1013 <Input
1014 aria-label={`Keybinding for ${commandLabelText}`}
1015 value={isRecording ? "" : keyDraft}
1016 placeholder={isRecording ? "Press shortcut" : "Unassigned"}
1017 className={cn(
1018 "h-7 w-44 rounded-md font-mono text-[12px] sm:h-7",
1019 isRecording && "border-primary/70 bg-primary/5",
1020 )}
1021 onFocus={() => setDraft({ isRecording: true })}
1022 onBlur={() => setDraft({ isRecording: false })}
1023 onChange={(event) => setDraft({ keyDraft: event.currentTarget.value })}
1024 onKeyDown={captureKeybinding}
1025 />
1026 <Button
1027 size="xs"
1028 className="h-7 sm:h-7"
1029 disabled={isSaving || !commandDraft || keyDraft.trim().length === 0 || !isWhenDraftValid}
1030 onClick={save}
1031 >
1032 {isSaving ? "Saving" : "Save"}
1033 </Button>
1034 </div>
1035 <div className="pr-4">
1036 <Popover>
1037 <PopoverTrigger
1038 className={cn(
1039 "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",
1040 !whenDraftExpression && "text-muted-foreground",
1041 )}
1042 aria-label={`Edit when clause for ${commandLabelText}`}
1043 >
1044 <span className="truncate">{whenDraftExpression || "Always"}</span>
1045 <ChevronDownIcon className="size-3.5 shrink-0 opacity-60" />
1046 </PopoverTrigger>
1047 <PopoverContent align="start" sideOffset={6}>
1048 <WhenExpressionBuilder
1049 value={whenDraft}
1050 variables={variables}
1051 onChange={(nextWhenDraft) => setDraft({ whenDraft: nextWhenDraft })}
1052 onValidityChange={(nextIsValid) => setDraft({ isWhenDraftValid: nextIsValid })}
1053 />
1054 </PopoverContent>
1055 </Popover>
1056 </div>
1057 <div className="flex items-center justify-end gap-1">
1058 <KeybindingConflictWarning labels={conflictLabels} />
1059 <Tooltip>
1060 <TooltipTrigger
1061 render={
1062 <Button
1063 type="button"
1064 variant="ghost"
1065 size="icon-sm"
1066 className="size-7 text-muted-foreground hover:text-foreground sm:size-7"
1067 disabled={isSaving}
1068 aria-label="Cancel new keybinding"
1069 onClick={onCancel}
1070 />
1071 }
1072 >
1073 <XIcon className="size-3.5" />
1074 </TooltipTrigger>
1075 <TooltipPopup side="top">Cancel</TooltipPopup>
1076 </Tooltip>
1077 </div>
1078 </div>
1079 );
1080}
1081
1082export function KeybindingsSettingsPanel() {
1083 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
1084 const keybindingsConfigPath = useAtomValue(primaryServerKeybindingsConfigPathAtom);
1085 const availableEditors = useAtomValue(primaryServerAvailableEditorsAtom);
1086 const primaryEnvironment = usePrimaryEnvironment();
1087 const upsertKeybinding = useAtomCommand(serverEnvironment.upsertKeybinding, {
1088 reportFailure: false,
1089 });
1090 const removeKeybindingMutation = useAtomCommand(serverEnvironment.removeKeybinding, {
1091 reportFailure: false,
1092 });
1093 const openInPreferredEditor = useOpenInPreferredEditor(
1094 primaryEnvironment?.environmentId ?? null,
1095 availableEditors,
1096 );
1097 const [query, setQuery] = useState("");
1098 const [isSearchOpen, setIsSearchOpen] = useState(false);
1099 const searchInputRef = useRef<HTMLInputElement>(null);
1100 const [savingCommand, setSavingCommand] = useState<KeybindingCommand | null>(null);
1101 const [isAddingBinding, setIsAddingBinding] = useState(false);
1102 const rows = useMemo(() => buildKeybindingRows(keybindings, query), [keybindings, query]);
1103 const commandOptions = useMemo(() => buildKeybindingCommandOptions(keybindings), [keybindings]);
1104 const whenVariables = useMemo(() => buildWhenVariableOptions(), []);
1105
1106 useEffect(() => {
1107 const handleKeyDown = (event: globalThis.KeyboardEvent) => {
1108 const isMod = event.metaKey || event.ctrlKey;
1109 if (!isMod || event.altKey || event.key.toLowerCase() !== "f") return;
1110
1111 const target = event.target;
1112 if (
1113 target !== searchInputRef.current &&
1114 target instanceof HTMLElement &&
1115 (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable)
1116 ) {
1117 return;
1118 }
1119
1120 event.preventDefault();
1121 setIsSearchOpen(true);
1122 requestAnimationFrame(() => {
1123 searchInputRef.current?.focus();
1124 searchInputRef.current?.select();
1125 });
1126 };
1127 window.addEventListener("keydown", handleKeyDown);
1128 return () => window.removeEventListener("keydown", handleKeyDown);
1129 }, []);
1130
1131 const openKeybindingsFile = useCallback(() => {
1132 if (!keybindingsConfigPath) return;
1133 void (async () => {
1134 const result = await openInPreferredEditor(keybindingsConfigPath);
1135 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
1136 return;
1137 }
1138 const error = squashAtomCommandFailure(result);
1139 toastManager.add({
1140 title: "Unable to open keybindings file",
1141 description:
1142 error instanceof Error ? error.message : "The keybindings file was not opened.",
1143 type: "error",
1144 });
1145 })();
1146 }, [keybindingsConfigPath, openInPreferredEditor]);
1147
1148 const saveKeybinding = useCallback(
1149 (input: ServerUpsertKeybindingInput) => {
1150 if (!primaryEnvironment) return;
1151 setSavingCommand(input.command);
1152 const payload: ServerUpsertKeybindingInput = {
1153 command: input.command,
1154 key: input.key.trim(),
1155 ...(input.when?.trim() ? { when: input.when.trim() } : {}),
1156 ...(input.replace ? { replace: input.replace } : {}),
1157 };
1158 void (async () => {
1159 const result = await upsertKeybinding({
1160 environmentId: primaryEnvironment.environmentId,
1161 input: payload,
1162 });
1163 setSavingCommand(null);
1164 if (result._tag === "Success") {
1165 setIsAddingBinding(false);
1166 return;
1167 }
1168 if (!isAtomCommandInterrupted(result)) {
1169 const error = squashAtomCommandFailure(result);
1170 toastManager.add({
1171 title: "Unable to save keybinding",
1172 description: error instanceof Error ? error.message : "The keybinding was not saved.",
1173 type: "error",
1174 });
1175 }
1176 })();
1177 },
1178 [primaryEnvironment, upsertKeybinding],
1179 );
1180
1181 const removeKeybinding = useCallback(
1182 (row: KeybindingRow) => {
1183 if (!primaryEnvironment) return;
1184 setSavingCommand(row.command);
1185 void (async () => {
1186 const result = await removeKeybindingMutation({
1187 environmentId: primaryEnvironment.environmentId,
1188 input: rowKeybindingTarget(row),
1189 });
1190 setSavingCommand(null);
1191 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1192 const error = squashAtomCommandFailure(result);
1193 toastManager.add({
1194 title: "Unable to remove keybinding",
1195 description: error instanceof Error ? error.message : "The keybinding was not removed.",
1196 type: "error",
1197 });
1198 }
1199 })();
1200 },
1201 [primaryEnvironment, removeKeybindingMutation],
1202 );
1203
1204 const resetKeybinding = useCallback(
1205 (row: KeybindingRow) => {
1206 if (!row.defaultKey) return;
1207 saveKeybinding({
1208 command: row.command,
1209 key: row.defaultKey,
1210 when: row.defaultWhen.trim().length > 0 ? row.defaultWhen : undefined,
1211 replace: {
1212 command: row.command,
1213 key: row.key,
1214 ...(row.when.trim().length > 0 ? { when: row.when } : {}),
1215 },
1216 });
1217 },
1218 [saveKeybinding],
1219 );
1220
1221 const bindingsCount = (
1222 <span className="text-[11px] text-muted-foreground">
1223 {rows.length + (isAddingBinding ? 1 : 0)}{" "}
1224 {rows.length + (isAddingBinding ? 1 : 0) === 1 ? "binding" : "bindings"}
1225 </span>
1226 );
1227
1228 return (
1229 <SettingsPageContainer className="max-w-5xl">
1230 <SettingsSection
1231 title="Keybindings"
1232 headerAction={
1233 <div className="flex items-center gap-1.5">
1234 <ExpandableHeaderSearch
1235 query={query}
1236 onChange={setQuery}
1237 isOpen={isSearchOpen}
1238 onOpenChange={setIsSearchOpen}
1239 inputRef={searchInputRef}
1240 collapsedAccessory={bindingsCount}
1241 />
1242 <Tooltip>
1243 <TooltipTrigger
1244 render={
1245 <Button
1246 type="button"
1247 size="icon-xs"
1248 variant="ghost"
1249 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
1250 onClick={() => setIsAddingBinding(true)}
1251 aria-label="Add keybinding"
1252 >
1253 <PlusIcon className="size-3" />
1254 </Button>
1255 }
1256 />
1257 <TooltipPopup side="top">Add keybinding</TooltipPopup>
1258 </Tooltip>
1259 <Tooltip>
1260 <TooltipTrigger
1261 render={
1262 <Button
1263 type="button"
1264 size="icon-xs"
1265 variant="ghost"
1266 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
1267 disabled={!keybindingsConfigPath}
1268 onClick={openKeybindingsFile}
1269 aria-label="Open keybindings.json"
1270 >
1271 <FileJsonIcon className="size-3" />
1272 </Button>
1273 }
1274 />
1275 <TooltipPopup side="top">Open keybindings.json</TooltipPopup>
1276 </Tooltip>
1277 </div>
1278 }
1279 >
1280 {!isElectron ? (
1281 <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">
1282 <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
1283 <p>
1284 Some shortcuts may be claimed by the browser before T3 Code sees them. Use the desktop
1285 app for better keybinding support.
1286 </p>
1287 </div>
1288 ) : null}
1289
1290 <ScrollArea
1291 chainVerticalScroll
1292 scrollFade
1293 hideScrollbars
1294 className="w-full max-w-full rounded-none"
1295 >
1296 <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">
1297 <div>Command</div>
1298 <div>Keybinding</div>
1299 <div>When</div>
1300 <div>Status</div>
1301 </div>
1302 <div className="min-w-[680px] divide-y divide-border/60">
1303 {isAddingBinding ? (
1304 <NewKeybindingTableRow
1305 commandOptions={commandOptions}
1306 allRows={rows}
1307 variables={whenVariables}
1308 isSaving={savingCommand !== null}
1309 onSave={saveKeybinding}
1310 onCancel={() => setIsAddingBinding(false)}
1311 />
1312 ) : null}
1313 {rows.map((row) => (
1314 <KeybindingTableRow
1315 key={row.id}
1316 row={row}
1317 allRows={rows}
1318 variables={whenVariables}
1319 isSaving={savingCommand === row.command}
1320 onSave={saveKeybinding}
1321 onReset={resetKeybinding}
1322 onRemove={removeKeybinding}
1323 />
1324 ))}
1325 {rows.length === 0 && !isAddingBinding ? (
1326 <div className="px-4 py-12 text-center text-sm text-muted-foreground">
1327 No keybindings match your search.
1328 </div>
1329 ) : null}
1330 </div>
1331 </ScrollArea>
1332 </SettingsSection>
1333 </SettingsPageContainer>
1334 );
1335}