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

KeybindingsSettings.tsx

1,282 lines42.6 KB

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