1555 lines
47 KiB
TypeScript
1555 lines
47 KiB
TypeScript
import {
|
|
ChevronDownIcon,
|
|
CircleXIcon,
|
|
EllipsisIcon,
|
|
FileJsonIcon,
|
|
MinusIcon,
|
|
PlusIcon,
|
|
SearchIcon,
|
|
TriangleAlertIcon,
|
|
XIcon,
|
|
} from "lucide-react";
|
|
import {
|
|
type KeyboardEvent,
|
|
type ReactNode,
|
|
type RefObject,
|
|
useCallback,
|
|
useEffect,
|
|
useMemo,
|
|
useReducer,
|
|
useRef,
|
|
useState,
|
|
} from "react";
|
|
import {
|
|
type KeybindingCommand,
|
|
type KeybindingWhenNode,
|
|
type ServerRemoveKeybindingInput,
|
|
type ServerUpsertKeybindingInput,
|
|
} from "@t3tools/contracts";
|
|
import { useAtomValue } from "@effect/atom-react";
|
|
import {
|
|
isAtomCommandInterrupted,
|
|
squashAtomCommandFailure,
|
|
} from "@t3tools/client-runtime/state/runtime";
|
|
|
|
import { isElectron } from "../../env";
|
|
import { useOpenInPreferredEditor } from "../../editorPreferences";
|
|
import { formatShortcutLabel } from "../../keybindings";
|
|
import { cn } from "../../lib/utils";
|
|
import {
|
|
primaryServerAvailableEditorsAtom,
|
|
primaryServerKeybindingsAtom,
|
|
primaryServerKeybindingsConfigPathAtom,
|
|
serverEnvironment,
|
|
} from "../../state/server";
|
|
import { usePrimaryEnvironment } from "../../state/environments";
|
|
import { Badge } from "../ui/badge";
|
|
import { Button } from "../ui/button";
|
|
import { Input } from "../ui/input";
|
|
import { Kbd, KbdGroup } from "../ui/kbd";
|
|
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
|
|
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
|
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
|
|
import { Toggle } from "../ui/toggle";
|
|
import { toastManager } from "../ui/toast";
|
|
import {
|
|
buildKeybindingRows,
|
|
buildKeybindingCommandOptions,
|
|
buildWhenVariableOptions,
|
|
commandLabel,
|
|
DEFAULT_WHEN_VARIABLE,
|
|
isKnownWhenVariable,
|
|
keybindingConflictLabels,
|
|
keybindingFromKeyboardEvent,
|
|
parseWhenExpressionDraft,
|
|
type KeybindingCommandOption,
|
|
type KeybindingRow,
|
|
type WhenVariableOption,
|
|
unknownWhenVariables,
|
|
whenAstToExpression,
|
|
whenNodeRemoveLabel,
|
|
} from "./KeybindingsSettings.logic";
|
|
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
|
|
import { searchableSetting } from "./settingsSearch";
|
|
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
|
import { useAtomCommand } from "../../state/use-atom-command";
|
|
|
|
function KeybindingPill({ value }: { value: string }) {
|
|
// Keys dedupe repeated parts; a literal "+" in a shortcut splits into empty strings.
|
|
const seenParts = new Map<string, number>();
|
|
const parts = value.split("+").map((part) => {
|
|
const seen = seenParts.get(part) ?? 0;
|
|
seenParts.set(part, seen + 1);
|
|
return { part, key: seen === 0 ? part : `${part}-${seen}` };
|
|
});
|
|
return (
|
|
<KbdGroup className="bg-transparent p-0 shadow-none">
|
|
{parts.map(({ part, key }) => (
|
|
<Kbd key={key} className="min-w-6 justify-center px-1.5">
|
|
{part === "mod"
|
|
? navigator.platform.toLowerCase().includes("mac")
|
|
? "⌘"
|
|
: "Ctrl"
|
|
: part === "shift"
|
|
? "⇧"
|
|
: part === "alt"
|
|
? navigator.platform.toLowerCase().includes("mac")
|
|
? "⌥"
|
|
: "Alt"
|
|
: part === "ctrl"
|
|
? "⌃"
|
|
: part.length === 1
|
|
? part.toUpperCase()
|
|
: part}
|
|
</Kbd>
|
|
))}
|
|
</KbdGroup>
|
|
);
|
|
}
|
|
|
|
function ExpandableHeaderSearch({
|
|
query,
|
|
onChange,
|
|
isOpen,
|
|
onOpenChange,
|
|
inputRef,
|
|
collapsedAccessory,
|
|
}: {
|
|
query: string;
|
|
onChange: (next: string) => void;
|
|
isOpen: boolean;
|
|
onOpenChange: (next: boolean) => void;
|
|
inputRef?: RefObject<HTMLInputElement | null>;
|
|
collapsedAccessory?: ReactNode;
|
|
}) {
|
|
if (!isOpen) {
|
|
return (
|
|
<>
|
|
{collapsedAccessory}
|
|
<Tooltip>
|
|
<TooltipTrigger
|
|
render={
|
|
<Button
|
|
type="button"
|
|
size="icon-xs"
|
|
variant="ghost-muted"
|
|
onClick={() => onOpenChange(true)}
|
|
aria-label="Search keybindings"
|
|
>
|
|
<SearchIcon />
|
|
</Button>
|
|
}
|
|
/>
|
|
<TooltipPopup side="top">Search keybindings</TooltipPopup>
|
|
</Tooltip>
|
|
</>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="relative">
|
|
<SearchIcon className="pointer-events-none absolute top-1/2 left-2 size-3 -translate-y-1/2 text-muted-foreground" />
|
|
<Input
|
|
ref={inputRef}
|
|
autoFocus
|
|
type="search"
|
|
value={query}
|
|
onChange={(event) => onChange(event.currentTarget.value)}
|
|
onBlur={() => {
|
|
if (query.length === 0) onOpenChange(false);
|
|
}}
|
|
onKeyDown={(event) => {
|
|
if (event.key === "Escape") {
|
|
event.preventDefault();
|
|
onChange("");
|
|
onOpenChange(false);
|
|
}
|
|
}}
|
|
placeholder="Search keybindings"
|
|
aria-label="Search keybindings"
|
|
className="w-44 [&_[data-slot=input]]:pl-7"
|
|
size="sm"
|
|
/>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
type BooleanOperator = "and" | "or";
|
|
|
|
function flattenWhenChildren(
|
|
node: KeybindingWhenNode,
|
|
operator: BooleanOperator,
|
|
): KeybindingWhenNode[] {
|
|
if (node.type !== operator) return [node];
|
|
return [
|
|
...flattenWhenChildren(node.left, operator),
|
|
...flattenWhenChildren(node.right, operator),
|
|
];
|
|
}
|
|
|
|
function buildWhenExpressionGroup(
|
|
children: readonly KeybindingWhenNode[],
|
|
operator: BooleanOperator,
|
|
): KeybindingWhenNode | undefined {
|
|
const first = children[0];
|
|
if (!first) return undefined;
|
|
return children.slice(1).reduce<KeybindingWhenNode>(
|
|
(left, right) => ({
|
|
type: operator,
|
|
left,
|
|
right,
|
|
}),
|
|
first,
|
|
);
|
|
}
|
|
|
|
function conditionParts(node: KeybindingWhenNode): { identifier: string; negated: boolean } | null {
|
|
if (node.type === "identifier") return { identifier: node.name, negated: false };
|
|
if (node.type === "not" && node.node.type === "identifier") {
|
|
return { identifier: node.node.name, negated: true };
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function setConditionIdentifier(node: KeybindingWhenNode, identifier: string): KeybindingWhenNode {
|
|
const parts = conditionParts(node);
|
|
if (!parts) return node;
|
|
const next: KeybindingWhenNode = { type: "identifier", name: identifier };
|
|
return parts.negated ? { type: "not", node: next } : next;
|
|
}
|
|
|
|
function setConditionNegated(node: KeybindingWhenNode, negated: boolean): KeybindingWhenNode {
|
|
const parts = conditionParts(node);
|
|
if (!parts) return negated ? { type: "not", node } : node;
|
|
const identifier: KeybindingWhenNode = { type: "identifier", name: parts.identifier };
|
|
return negated ? { type: "not", node: identifier } : identifier;
|
|
}
|
|
|
|
function defaultWhenCondition(): KeybindingWhenNode {
|
|
return { type: "identifier", name: DEFAULT_WHEN_VARIABLE };
|
|
}
|
|
|
|
function defaultWhenGroup(operator: BooleanOperator = "and"): KeybindingWhenNode {
|
|
return {
|
|
type: operator,
|
|
left: defaultWhenCondition(),
|
|
right: { type: "not", node: defaultWhenCondition() },
|
|
};
|
|
}
|
|
|
|
/** Warning glyph whose explanation lives in a tooltip; the one owner of that affordance here. */
|
|
function WarningTooltipIcon({
|
|
label,
|
|
focusable = true,
|
|
className,
|
|
children,
|
|
}: {
|
|
label: string;
|
|
focusable?: boolean;
|
|
className?: string | undefined;
|
|
children: ReactNode;
|
|
}) {
|
|
return (
|
|
<Tooltip>
|
|
<TooltipTrigger
|
|
render={
|
|
<span
|
|
tabIndex={focusable ? 0 : undefined}
|
|
aria-label={label}
|
|
className={cn(
|
|
"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",
|
|
className,
|
|
)}
|
|
/>
|
|
}
|
|
>
|
|
<TriangleAlertIcon className="size-3.5" />
|
|
</TooltipTrigger>
|
|
<TooltipPopup side="top" className="max-w-72 whitespace-normal leading-relaxed">
|
|
{children}
|
|
</TooltipPopup>
|
|
</Tooltip>
|
|
);
|
|
}
|
|
|
|
function UnknownWhenVariableWarning({
|
|
identifiers,
|
|
focusable = true,
|
|
}: {
|
|
identifiers: ReadonlyArray<string>;
|
|
focusable?: boolean;
|
|
}) {
|
|
if (identifiers.length === 0) return null;
|
|
const label =
|
|
identifiers.length === 1
|
|
? `Unknown condition: ${identifiers[0]}`
|
|
: `Unknown conditions: ${identifiers.join(", ")}`;
|
|
|
|
return (
|
|
<WarningTooltipIcon label={label} focusable={focusable} className="size-4.5">
|
|
T3 Code does not recognize this condition yet. It can still be saved, but it may not match
|
|
unless the runtime provides it.
|
|
</WarningTooltipIcon>
|
|
);
|
|
}
|
|
|
|
function KeybindingConflictWarning({ labels }: { labels: ReadonlyArray<string> }) {
|
|
if (labels.length === 0) return null;
|
|
const description =
|
|
labels.length === 1
|
|
? `Conflicts with ${labels[0]}.`
|
|
: `Conflicts with ${labels.slice(0, 3).join(", ")}${labels.length > 3 ? ", and more" : ""}.`;
|
|
|
|
return (
|
|
<WarningTooltipIcon label={description}>
|
|
{description} The most recent matching binding wins when both conditions can apply.
|
|
</WarningTooltipIcon>
|
|
);
|
|
}
|
|
|
|
function WhenVariableSelect({
|
|
value,
|
|
variables,
|
|
unknownIdentifiers,
|
|
onChange,
|
|
}: {
|
|
value: string;
|
|
variables: ReadonlyArray<WhenVariableOption>;
|
|
unknownIdentifiers?: ReadonlyArray<string>;
|
|
onChange: (value: string) => void;
|
|
}) {
|
|
const selected = variables.find((option) => option === value);
|
|
const options =
|
|
selected || variables.some((option) => option === value) ? variables : [value, ...variables];
|
|
|
|
return (
|
|
<Select value={value} onValueChange={(nextValue) => nextValue && onChange(nextValue)}>
|
|
<SelectTrigger size="compact" className="min-w-0 flex-1 font-mono">
|
|
<SelectValue placeholder="Condition" className="leading-7" />
|
|
{unknownIdentifiers && unknownIdentifiers.length > 0 ? (
|
|
<UnknownWhenVariableWarning identifiers={unknownIdentifiers} focusable={false} />
|
|
) : null}
|
|
</SelectTrigger>
|
|
<SelectContent
|
|
alignItemWithTrigger={false}
|
|
matchTriggerWidth={false}
|
|
popupClassName="w-fit"
|
|
className="max-h-72 w-fit min-w-44"
|
|
>
|
|
{options.map((option) => (
|
|
<SelectItem
|
|
key={option}
|
|
value={option}
|
|
className="min-h-7 w-full py-1 font-mono text-[12px]"
|
|
>
|
|
<span className="truncate">{option}</span>
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
);
|
|
}
|
|
|
|
function WhenExpressionRemoveButton({
|
|
label,
|
|
className,
|
|
onRemove,
|
|
}: {
|
|
label: string;
|
|
className?: string | undefined;
|
|
onRemove: () => void;
|
|
}) {
|
|
return (
|
|
<Tooltip>
|
|
<TooltipTrigger
|
|
delay={200}
|
|
render={
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon-sm"
|
|
className={cn("size-7", className)}
|
|
aria-label={label}
|
|
onClick={onRemove}
|
|
/>
|
|
}
|
|
>
|
|
<MinusIcon aria-hidden className="size-3.5" />
|
|
</TooltipTrigger>
|
|
<TooltipPopup side="top">{label}</TooltipPopup>
|
|
</Tooltip>
|
|
);
|
|
}
|
|
|
|
function WhenExpressionNodeEditor({
|
|
node,
|
|
variables,
|
|
depth = 0,
|
|
onChange,
|
|
onRemove,
|
|
}: {
|
|
node: KeybindingWhenNode;
|
|
variables: ReadonlyArray<WhenVariableOption>;
|
|
depth?: number;
|
|
onChange: (node: KeybindingWhenNode) => void;
|
|
onRemove?: () => void;
|
|
}) {
|
|
const condition = conditionParts(node);
|
|
|
|
if (condition) {
|
|
const unknownIdentifiers = isKnownWhenVariable(condition.identifier)
|
|
? []
|
|
: [condition.identifier];
|
|
|
|
return (
|
|
<div className="flex items-center gap-2 rounded-md border border-border/70 bg-background/60 px-2 py-2">
|
|
<Toggle
|
|
pressed={condition.negated}
|
|
onPressedChange={(pressed) => onChange(setConditionNegated(node, pressed))}
|
|
aria-label={`Negate ${condition.identifier}`}
|
|
variant="outline"
|
|
size="compact"
|
|
className="min-w-10"
|
|
>
|
|
Not
|
|
</Toggle>
|
|
<WhenVariableSelect
|
|
value={condition.identifier}
|
|
variables={variables}
|
|
unknownIdentifiers={unknownIdentifiers}
|
|
onChange={(value) => onChange(setConditionIdentifier(node, value))}
|
|
/>
|
|
{onRemove ? (
|
|
<WhenExpressionRemoveButton
|
|
label={whenNodeRemoveLabel(node, depth)}
|
|
onRemove={onRemove}
|
|
/>
|
|
) : null}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (node.type === "not") {
|
|
return (
|
|
<div
|
|
className={cn(
|
|
"space-y-2 rounded-lg border border-border/70 bg-muted/20 p-2",
|
|
depth > 0 && "border-border/50 bg-background/50",
|
|
)}
|
|
>
|
|
<div className="flex items-center gap-2">
|
|
<Toggle
|
|
pressed
|
|
onPressedChange={(pressed) => onChange(pressed ? node : node.node)}
|
|
aria-label="Negate group"
|
|
variant="outline"
|
|
size="compact"
|
|
className="min-w-10"
|
|
>
|
|
Not
|
|
</Toggle>
|
|
{onRemove ? (
|
|
<WhenExpressionRemoveButton
|
|
label={whenNodeRemoveLabel(node, depth)}
|
|
className="ml-auto"
|
|
onRemove={onRemove}
|
|
/>
|
|
) : null}
|
|
</div>
|
|
<div className="relative pl-4">
|
|
<span className="absolute top-0 bottom-0 left-1.5 w-px bg-border/70" aria-hidden />
|
|
<span className="absolute top-4 left-1.5 h-px w-2.5 bg-border/70" aria-hidden />
|
|
<WhenExpressionNodeEditor
|
|
node={node.node}
|
|
variables={variables}
|
|
depth={depth + 1}
|
|
onChange={(next) => onChange({ type: "not", node: next })}
|
|
/>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
const operator: BooleanOperator = node.type === "or" ? "or" : "and";
|
|
const children = flattenWhenChildren(node, operator);
|
|
const childKeyCounts = new Map<string, number>();
|
|
const childEntries = children.map((child) => {
|
|
const baseKey = `${child.type}-${whenAstToExpression(child)}`;
|
|
const count = childKeyCounts.get(baseKey) ?? 0;
|
|
childKeyCounts.set(baseKey, count + 1);
|
|
return { child, key: count === 0 ? baseKey : `${baseKey}-${count}` };
|
|
});
|
|
|
|
const updateChild = (target: KeybindingWhenNode, next: KeybindingWhenNode) => {
|
|
let didUpdate = false;
|
|
const nextChildren = children.map((child) => {
|
|
if (!didUpdate && child === target) {
|
|
didUpdate = true;
|
|
return next;
|
|
}
|
|
return child;
|
|
});
|
|
const nextNode = buildWhenExpressionGroup(nextChildren, operator);
|
|
if (nextNode) onChange(nextNode);
|
|
};
|
|
|
|
const removeChild = (target: KeybindingWhenNode) => {
|
|
let didRemove = false;
|
|
const nextChildren = children.filter((child) => {
|
|
if (!didRemove && child === target) {
|
|
didRemove = true;
|
|
return false;
|
|
}
|
|
return true;
|
|
});
|
|
const nextNode = buildWhenExpressionGroup(nextChildren, operator);
|
|
if (nextNode) {
|
|
onChange(nextNode);
|
|
} else {
|
|
onChange(defaultWhenCondition());
|
|
}
|
|
};
|
|
|
|
const setOperator = (nextOperator: BooleanOperator) => {
|
|
if (nextOperator === operator) return;
|
|
const nextNode = buildWhenExpressionGroup(children, nextOperator);
|
|
if (nextNode) onChange(nextNode);
|
|
};
|
|
|
|
const addCondition = () => {
|
|
const nextNode = buildWhenExpressionGroup([...children, defaultWhenCondition()], operator);
|
|
if (nextNode) onChange(nextNode);
|
|
};
|
|
|
|
const addGroup = () => {
|
|
const nestedOperator: BooleanOperator = operator === "and" ? "or" : "and";
|
|
const group: KeybindingWhenNode = {
|
|
type: nestedOperator,
|
|
left: defaultWhenCondition(),
|
|
right: { type: "not", node: defaultWhenCondition() },
|
|
};
|
|
const nextNode = buildWhenExpressionGroup([...children, group], operator);
|
|
if (nextNode) onChange(nextNode);
|
|
};
|
|
|
|
return (
|
|
<div
|
|
className={cn(
|
|
"space-y-2 rounded-lg border border-border/60 bg-muted/10 p-2",
|
|
depth > 0 && "border-border/70 bg-background/55",
|
|
)}
|
|
>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<Select value={operator} onValueChange={(value) => setOperator(value as BooleanOperator)}>
|
|
<SelectTrigger size="compact" className="w-24">
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent
|
|
alignItemWithTrigger={false}
|
|
matchTriggerWidth={false}
|
|
popupClassName="w-fit"
|
|
className="w-fit min-w-24"
|
|
>
|
|
<SelectItem value="and" className="min-h-7 py-1 font-mono text-[12px]">
|
|
and
|
|
</SelectItem>
|
|
<SelectItem value="or" className="min-h-7 py-1 font-mono text-[12px]">
|
|
or
|
|
</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
<Button type="button" variant="outline" size="compact" onClick={addCondition}>
|
|
<PlusIcon className="size-3.5" />
|
|
Condition
|
|
</Button>
|
|
<Button type="button" variant="outline" size="compact" onClick={addGroup}>
|
|
<PlusIcon className="size-3.5" />
|
|
Group
|
|
</Button>
|
|
{onRemove ? (
|
|
<WhenExpressionRemoveButton
|
|
label={whenNodeRemoveLabel(node, depth)}
|
|
className="ml-auto"
|
|
onRemove={onRemove}
|
|
/>
|
|
) : null}
|
|
</div>
|
|
<div className="space-y-2">
|
|
{childEntries.map(({ child, key }) => (
|
|
<div key={key} className="relative pl-4">
|
|
<span
|
|
className={cn(
|
|
"absolute top-0 bottom-0 left-1.5 w-px",
|
|
depth === 0 ? "bg-border" : "bg-border/70",
|
|
)}
|
|
aria-hidden
|
|
/>
|
|
<span
|
|
className={cn(
|
|
"absolute top-4 left-1.5 h-px w-2.5",
|
|
depth === 0 ? "bg-border" : "bg-border/70",
|
|
)}
|
|
aria-hidden
|
|
/>
|
|
<WhenExpressionNodeEditor
|
|
node={child}
|
|
variables={variables}
|
|
depth={depth + 1}
|
|
onChange={(next) => updateChild(child, next)}
|
|
onRemove={() => removeChild(child)}
|
|
/>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function WhenExpressionBuilder({
|
|
value,
|
|
variables,
|
|
onChange,
|
|
onValidityChange,
|
|
}: {
|
|
value: KeybindingWhenNode | undefined;
|
|
variables: ReadonlyArray<WhenVariableOption>;
|
|
onChange: (value: KeybindingWhenNode | undefined) => void;
|
|
onValidityChange?: (valid: boolean) => void;
|
|
}) {
|
|
const expression = whenAstToExpression(value);
|
|
const [expressionDraft, setExpressionDraft] = useState(expression);
|
|
const parseResult = useMemo(() => parseWhenExpressionDraft(expressionDraft), [expressionDraft]);
|
|
const parseError = parseResult.ok ? null : parseResult.message;
|
|
const unknownIdentifiers = parseResult.ok ? unknownWhenVariables(parseResult.value) : [];
|
|
|
|
const updateExpressionDraft = (nextExpression: string) => {
|
|
setExpressionDraft(nextExpression);
|
|
const nextResult = parseWhenExpressionDraft(nextExpression);
|
|
onValidityChange?.(nextResult.ok);
|
|
if (nextResult.ok) {
|
|
onChange(nextResult.value);
|
|
}
|
|
};
|
|
|
|
const updateExpressionValue = (nextValue: KeybindingWhenNode | undefined) => {
|
|
setExpressionDraft(whenAstToExpression(nextValue));
|
|
onValidityChange?.(true);
|
|
onChange(nextValue);
|
|
};
|
|
|
|
const addRootCondition = () => {
|
|
if (!value) {
|
|
updateExpressionValue(defaultWhenCondition());
|
|
return;
|
|
}
|
|
updateExpressionValue({ type: "and", left: value, right: defaultWhenCondition() });
|
|
};
|
|
|
|
const addRootGroup = () => {
|
|
const group = defaultWhenGroup("or");
|
|
if (!value) {
|
|
updateExpressionValue(group);
|
|
return;
|
|
}
|
|
updateExpressionValue({ type: "and", left: value, right: group });
|
|
};
|
|
|
|
return (
|
|
<div className="w-[min(34rem,calc(100vw-2rem))] space-y-3">
|
|
<div className="flex items-start justify-between gap-3">
|
|
<div className="min-w-0">
|
|
<div className="text-sm font-medium text-foreground">When</div>
|
|
</div>
|
|
<div className="flex shrink-0 items-center gap-2">
|
|
<Button type="button" variant="outline" size="compact" onClick={addRootCondition}>
|
|
<PlusIcon className="size-3.5" />
|
|
Condition
|
|
</Button>
|
|
<Button type="button" variant="outline" size="compact" onClick={addRootGroup}>
|
|
<PlusIcon className="size-3.5" />
|
|
Group
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-1.5">
|
|
<div className="relative">
|
|
<Input
|
|
value={expressionDraft}
|
|
onChange={(event) => updateExpressionDraft(event.currentTarget.value)}
|
|
placeholder="Always"
|
|
aria-invalid={Boolean(parseError)}
|
|
aria-label="When expression"
|
|
className={cn(
|
|
"h-7 rounded-md font-mono text-[12px] leading-7 sm:h-7 sm:leading-7",
|
|
unknownIdentifiers.length > 0 && "pr-9",
|
|
parseError && "border-destructive/70 focus-visible:border-destructive",
|
|
)}
|
|
/>
|
|
{unknownIdentifiers.length > 0 ? (
|
|
<span className="absolute inset-y-0 right-2 flex items-center">
|
|
<UnknownWhenVariableWarning identifiers={unknownIdentifiers} />
|
|
</span>
|
|
) : null}
|
|
</div>
|
|
{parseError ? (
|
|
<div className="flex items-center gap-1.5 text-[11px] text-destructive">
|
|
<CircleXIcon className="size-3.5" />
|
|
{parseError}
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
|
|
<div className="relative">
|
|
{value ? (
|
|
<WhenExpressionNodeEditor
|
|
node={value}
|
|
variables={variables}
|
|
onChange={updateExpressionValue}
|
|
onRemove={() => updateExpressionValue(undefined)}
|
|
/>
|
|
) : (
|
|
<div className="rounded-md border border-dashed border-border/80 bg-muted/15 p-3">
|
|
<div className="flex flex-wrap gap-2">
|
|
<Button type="button" size="compact" onClick={addRootCondition}>
|
|
<PlusIcon className="size-3.5" />
|
|
Condition
|
|
</Button>
|
|
<Button type="button" variant="outline" size="compact" onClick={addRootGroup}>
|
|
<PlusIcon className="size-3.5" />
|
|
Group
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
{parseError ? (
|
|
<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]">
|
|
Fix the expression above to continue editing visually.
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
type KeybindingRowDraftState = {
|
|
keyDraft: string;
|
|
whenDraft: KeybindingWhenNode | undefined;
|
|
isRecording: boolean;
|
|
isWhenDraftValid: boolean;
|
|
};
|
|
|
|
function createKeybindingRowDraft(row: KeybindingRow): KeybindingRowDraftState {
|
|
return {
|
|
keyDraft: row.key,
|
|
whenDraft: row.binding.whenAst,
|
|
isRecording: false,
|
|
isWhenDraftValid: true,
|
|
};
|
|
}
|
|
|
|
function keybindingRowDraftReducer(
|
|
state: KeybindingRowDraftState,
|
|
patch: Partial<KeybindingRowDraftState>,
|
|
): KeybindingRowDraftState {
|
|
return { ...state, ...patch };
|
|
}
|
|
|
|
function rowKeybindingTarget(row: KeybindingRow): ServerRemoveKeybindingInput {
|
|
return {
|
|
command: row.command,
|
|
key: row.key,
|
|
...(row.when.trim().length > 0 ? { when: row.when } : {}),
|
|
};
|
|
}
|
|
|
|
/** Draft state and actions for editing one existing binding; layouts decide how to render it. */
|
|
function useKeybindingRowEditor({
|
|
row,
|
|
allRows,
|
|
onSave,
|
|
}: {
|
|
row: KeybindingRow;
|
|
allRows: ReadonlyArray<KeybindingRow>;
|
|
onSave: (input: ServerUpsertKeybindingInput) => void;
|
|
}) {
|
|
const [draft, setDraft] = useReducer(keybindingRowDraftReducer, row, createKeybindingRowDraft);
|
|
const { keyDraft, whenDraft, isRecording, isWhenDraftValid } = draft;
|
|
const whenDraftExpression = whenAstToExpression(whenDraft);
|
|
const isDirty = keyDraft !== row.key || whenDraftExpression !== row.when;
|
|
const conflictLabels = keybindingConflictLabels(allRows, {
|
|
rowId: row.id,
|
|
key: keyDraft,
|
|
when: whenDraftExpression,
|
|
});
|
|
|
|
const save = () => {
|
|
onSave({
|
|
command: row.command,
|
|
key: keyDraft,
|
|
when: whenDraftExpression.trim().length > 0 ? whenDraftExpression : undefined,
|
|
replace: rowKeybindingTarget(row),
|
|
});
|
|
};
|
|
|
|
const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
|
|
if (event.key === "Tab") return;
|
|
event.preventDefault();
|
|
if (event.key === "Escape") {
|
|
setDraft({ keyDraft: row.key, isRecording: false });
|
|
return;
|
|
}
|
|
const next = keybindingFromKeyboardEvent(event.nativeEvent, navigator.platform);
|
|
if (!next) return;
|
|
setDraft({ keyDraft: next, isRecording: false });
|
|
};
|
|
|
|
return {
|
|
keyDraft,
|
|
whenDraft,
|
|
isRecording,
|
|
isWhenDraftValid,
|
|
whenDraftExpression,
|
|
isDirty,
|
|
conflictLabels,
|
|
setDraft,
|
|
save,
|
|
captureKeybinding,
|
|
};
|
|
}
|
|
|
|
type KeybindingRowEditor = ReturnType<typeof useKeybindingRowEditor>;
|
|
|
|
interface KeybindingRowActions {
|
|
allRows: ReadonlyArray<KeybindingRow>;
|
|
variables: ReadonlyArray<WhenVariableOption>;
|
|
onSave: (input: ServerUpsertKeybindingInput) => void;
|
|
onReset: (row: KeybindingRow) => void;
|
|
onRemove: (row: KeybindingRow) => void;
|
|
}
|
|
|
|
type KeybindingRowProps = KeybindingRowActions & { row: KeybindingRow; isSaving: boolean };
|
|
|
|
/** Shortcut pill that turns into a capture input when clicked, plus Save once the draft changes. */
|
|
function KeybindingKeyControl({
|
|
row,
|
|
editor,
|
|
isSaving,
|
|
pillClassName,
|
|
}: {
|
|
row: KeybindingRow;
|
|
editor: KeybindingRowEditor;
|
|
isSaving: boolean;
|
|
pillClassName?: string | undefined;
|
|
}) {
|
|
const { keyDraft, isRecording, isDirty, isWhenDraftValid, setDraft, save, captureKeybinding } =
|
|
editor;
|
|
const showPill = !isRecording && keyDraft === row.key && row.key.length > 0 && !isDirty;
|
|
|
|
return (
|
|
<>
|
|
{isDirty ? (
|
|
<Button
|
|
size="sm"
|
|
disabled={isSaving || keyDraft.trim().length === 0 || !isWhenDraftValid}
|
|
onClick={save}
|
|
>
|
|
{isSaving ? "Saving" : "Save"}
|
|
</Button>
|
|
) : null}
|
|
{showPill ? (
|
|
<button
|
|
type="button"
|
|
onClick={() => setDraft({ isRecording: true })}
|
|
aria-label={`Edit shortcut for ${commandLabel(row.command)}: ${formatShortcutLabel(row.binding.shortcut)}`}
|
|
className={cn(
|
|
"inline-flex h-8 cursor-pointer items-center rounded-md border border-transparent px-1.5 sm:h-7 outline-none transition-colors hover:border-border/70 hover:bg-accent focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/24",
|
|
pillClassName,
|
|
)}
|
|
>
|
|
<KeybindingPill value={row.key} />
|
|
</button>
|
|
) : (
|
|
<Input
|
|
data-keybinding-capture=""
|
|
autoFocus={isRecording}
|
|
aria-label={`Keybinding for ${commandLabel(row.command)}`}
|
|
value={isRecording ? "" : keyDraft}
|
|
placeholder={isRecording ? "Press shortcut" : "Unassigned"}
|
|
size="sm"
|
|
className={cn("w-44 font-mono", isRecording && "border-primary/70 bg-primary/5")}
|
|
onFocus={() => setDraft({ isRecording: true })}
|
|
onBlur={() => setDraft({ isRecording: false })}
|
|
onChange={(event) => setDraft({ keyDraft: event.currentTarget.value })}
|
|
onKeyDown={captureKeybinding}
|
|
/>
|
|
)}
|
|
</>
|
|
);
|
|
}
|
|
|
|
/** Quiet inline trigger showing the when clause; opens the expression builder. */
|
|
function WhenClauseControl({
|
|
label,
|
|
expression,
|
|
value,
|
|
variables,
|
|
onChange,
|
|
onValidityChange,
|
|
}: {
|
|
label: string;
|
|
expression: string;
|
|
value: KeybindingWhenNode | undefined;
|
|
variables: ReadonlyArray<WhenVariableOption>;
|
|
onChange: (value: KeybindingWhenNode | undefined) => void;
|
|
onValidityChange: (valid: boolean) => void;
|
|
}) {
|
|
return (
|
|
<Popover>
|
|
<PopoverTrigger
|
|
render={
|
|
<Button
|
|
variant={expression ? "ghost" : "ghost-muted"}
|
|
size="micro"
|
|
className="min-w-0 shrink font-mono"
|
|
/>
|
|
}
|
|
aria-label={`Edit when clause for ${label}`}
|
|
>
|
|
<span className="truncate">{expression || "Always"}</span>
|
|
<ChevronDownIcon className="size-3.5 shrink-0 opacity-60" />
|
|
</PopoverTrigger>
|
|
<PopoverContent align="start" sideOffset={6}>
|
|
<WhenExpressionBuilder
|
|
value={value}
|
|
variables={variables}
|
|
onChange={onChange}
|
|
onValidityChange={onValidityChange}
|
|
/>
|
|
</PopoverContent>
|
|
</Popover>
|
|
);
|
|
}
|
|
|
|
function KeybindingRowMenu({
|
|
row,
|
|
isSaving,
|
|
onReset,
|
|
onRemove,
|
|
}: {
|
|
row: KeybindingRow;
|
|
isSaving: boolean;
|
|
onReset: (row: KeybindingRow) => void;
|
|
onRemove: (row: KeybindingRow) => void;
|
|
}) {
|
|
const canReset = row.source === "Custom" && row.defaultKey !== null;
|
|
const canRemove = row.source !== "Default";
|
|
if (!canReset && !canRemove) return null;
|
|
|
|
return (
|
|
<Menu>
|
|
<MenuTrigger
|
|
render={
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon-sm"
|
|
className="text-muted-foreground hover:text-foreground"
|
|
disabled={isSaving}
|
|
aria-label={`Actions for ${commandLabel(row.command)}`}
|
|
/>
|
|
}
|
|
>
|
|
<EllipsisIcon className="size-3.5" />
|
|
</MenuTrigger>
|
|
<MenuPopup align="end" className="min-w-36">
|
|
{canReset ? (
|
|
<MenuItem disabled={isSaving} onClick={() => onReset(row)}>
|
|
Reset to default
|
|
</MenuItem>
|
|
) : null}
|
|
{canRemove ? (
|
|
<MenuItem variant="destructive" disabled={isSaving} onClick={() => onRemove(row)}>
|
|
Remove
|
|
</MenuItem>
|
|
) : null}
|
|
</MenuPopup>
|
|
</Menu>
|
|
);
|
|
}
|
|
|
|
function KeybindingSourceBadge({ source }: { source: KeybindingRow["source"] }) {
|
|
if (source === "Default") return null;
|
|
return (
|
|
<Badge variant="outline" size="sm" className="font-normal text-muted-foreground">
|
|
{source}
|
|
</Badge>
|
|
);
|
|
}
|
|
|
|
function KeybindingRowTitle({ row }: { row: KeybindingRow }) {
|
|
return (
|
|
<Tooltip>
|
|
<TooltipTrigger render={<span className="flex items-center gap-2" />}>
|
|
{commandLabel(row.command)}
|
|
<KeybindingSourceBadge source={row.source} />
|
|
</TooltipTrigger>
|
|
<TooltipPopup side="top">{row.command}</TooltipPopup>
|
|
</Tooltip>
|
|
);
|
|
}
|
|
|
|
function KeybindingRowWhen({
|
|
row,
|
|
editor,
|
|
variables,
|
|
}: {
|
|
row: KeybindingRow;
|
|
editor: KeybindingRowEditor;
|
|
variables: ReadonlyArray<WhenVariableOption>;
|
|
}) {
|
|
return (
|
|
<span className="flex h-6 items-center gap-1.5">
|
|
<span className="text-[12px] leading-none text-muted-foreground/70">When</span>
|
|
<WhenClauseControl
|
|
label={commandLabel(row.command)}
|
|
expression={editor.whenDraftExpression}
|
|
value={editor.whenDraft}
|
|
variables={variables}
|
|
onChange={(whenDraft) => editor.setDraft({ whenDraft })}
|
|
onValidityChange={(isWhenDraftValid) => editor.setDraft({ isWhenDraftValid })}
|
|
/>
|
|
</span>
|
|
);
|
|
}
|
|
|
|
/** Row actions that stay hidden until the row is hovered or holds focus. */
|
|
function KeybindingHoverRowMenu(props: {
|
|
row: KeybindingRow;
|
|
isSaving: boolean;
|
|
onReset: (row: KeybindingRow) => void;
|
|
onRemove: (row: KeybindingRow) => void;
|
|
}) {
|
|
return (
|
|
<span className="flex items-center opacity-0 transition-opacity group-focus-within/row:opacity-100 group-hover/row:opacity-100 has-data-popup-open:opacity-100 pointer-coarse:opacity-100">
|
|
<KeybindingRowMenu {...props} />
|
|
</span>
|
|
);
|
|
}
|
|
|
|
/** One binding as a settings row: pills flush right, actions fading in beside them on hover. */
|
|
function KeybindingSettingsRow(props: KeybindingRowProps) {
|
|
const { row, isSaving, allRows, variables, onSave, onReset, onRemove } = props;
|
|
const editor = useKeybindingRowEditor({ row, allRows, onSave });
|
|
|
|
return (
|
|
<SettingsRow
|
|
className="group/row rounded-none"
|
|
title={<KeybindingRowTitle row={row} />}
|
|
description={<KeybindingRowWhen row={row} editor={editor} variables={variables} />}
|
|
control={
|
|
<div className="flex flex-wrap items-center justify-end gap-1.5">
|
|
<KeybindingConflictWarning labels={editor.conflictLabels} />
|
|
<KeybindingHoverRowMenu
|
|
row={row}
|
|
isSaving={isSaving}
|
|
onReset={onReset}
|
|
onRemove={onRemove}
|
|
/>
|
|
<KeybindingKeyControl
|
|
row={row}
|
|
editor={editor}
|
|
isSaving={isSaving}
|
|
pillClassName="-mr-1.5"
|
|
/>
|
|
</div>
|
|
}
|
|
/>
|
|
);
|
|
}
|
|
|
|
/** Draft state for a binding that does not exist yet. */
|
|
function useNewKeybindingDraft({
|
|
allRows,
|
|
onSave,
|
|
}: {
|
|
allRows: ReadonlyArray<KeybindingRow>;
|
|
onSave: (input: ServerUpsertKeybindingInput) => void;
|
|
}) {
|
|
const [commandDraft, setCommandDraft] = useState<KeybindingCommand | "">("");
|
|
const [draft, setDraft] = useReducer(keybindingRowDraftReducer, {
|
|
keyDraft: "",
|
|
whenDraft: undefined,
|
|
isRecording: false,
|
|
isWhenDraftValid: true,
|
|
});
|
|
const { keyDraft, whenDraft, isRecording, isWhenDraftValid } = draft;
|
|
const whenDraftExpression = whenAstToExpression(whenDraft);
|
|
const conflictLabels = keybindingConflictLabels(allRows, {
|
|
rowId: "new",
|
|
key: keyDraft,
|
|
when: whenDraftExpression,
|
|
});
|
|
const commandLabelText = commandDraft ? commandLabel(commandDraft) : "new keybinding";
|
|
const canSave = Boolean(commandDraft) && keyDraft.trim().length > 0 && isWhenDraftValid;
|
|
|
|
const save = () => {
|
|
if (!commandDraft) return;
|
|
onSave({
|
|
command: commandDraft,
|
|
key: keyDraft,
|
|
...(whenDraftExpression.trim().length > 0 ? { when: whenDraftExpression } : {}),
|
|
});
|
|
};
|
|
|
|
const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
|
|
if (event.key === "Tab") return;
|
|
event.preventDefault();
|
|
if (event.key === "Escape") {
|
|
setDraft({ keyDraft: "", isRecording: false });
|
|
return;
|
|
}
|
|
const next = keybindingFromKeyboardEvent(event.nativeEvent, navigator.platform);
|
|
if (!next) return;
|
|
setDraft({ keyDraft: next, isRecording: false });
|
|
};
|
|
|
|
return {
|
|
commandDraft,
|
|
setCommandDraft,
|
|
keyDraft,
|
|
whenDraft,
|
|
whenDraftExpression,
|
|
isRecording,
|
|
conflictLabels,
|
|
commandLabelText,
|
|
canSave,
|
|
setDraft,
|
|
save,
|
|
captureKeybinding,
|
|
};
|
|
}
|
|
|
|
type NewKeybindingDraft = ReturnType<typeof useNewKeybindingDraft>;
|
|
|
|
interface NewKeybindingProps {
|
|
commandOptions: ReadonlyArray<KeybindingCommandOption>;
|
|
allRows: ReadonlyArray<KeybindingRow>;
|
|
variables: ReadonlyArray<WhenVariableOption>;
|
|
isSaving: boolean;
|
|
onSave: (input: ServerUpsertKeybindingInput) => void;
|
|
onCancel: () => void;
|
|
}
|
|
|
|
function NewKeybindingCommandSelect({
|
|
draft,
|
|
commandOptions,
|
|
className,
|
|
}: {
|
|
draft: NewKeybindingDraft;
|
|
commandOptions: ReadonlyArray<KeybindingCommandOption>;
|
|
className?: string | undefined;
|
|
}) {
|
|
return (
|
|
<Select
|
|
value={draft.commandDraft}
|
|
onValueChange={(value) => draft.setCommandDraft(value as KeybindingCommand)}
|
|
>
|
|
<SelectTrigger size="sm" className={className}>
|
|
<SelectValue placeholder="Command" />
|
|
</SelectTrigger>
|
|
<SelectContent
|
|
alignItemWithTrigger={false}
|
|
matchTriggerWidth={false}
|
|
className="max-h-72 w-fit min-w-56"
|
|
>
|
|
{commandOptions.map((command) => (
|
|
<SelectItem key={command} value={command} className="min-h-7 w-full py-1 text-[12px]">
|
|
<span className="truncate">{commandLabel(command)}</span>
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
);
|
|
}
|
|
|
|
function NewKeybindingKeyInput({
|
|
draft,
|
|
autoFocus = false,
|
|
className,
|
|
}: {
|
|
draft: NewKeybindingDraft;
|
|
autoFocus?: boolean;
|
|
className?: string | undefined;
|
|
}) {
|
|
return (
|
|
<Input
|
|
data-keybinding-capture=""
|
|
autoFocus={autoFocus}
|
|
aria-label={`Keybinding for ${draft.commandLabelText}`}
|
|
value={draft.isRecording ? "" : draft.keyDraft}
|
|
placeholder={draft.isRecording ? "Press shortcut" : "Unassigned"}
|
|
size="sm"
|
|
className={cn("font-mono", draft.isRecording && "border-primary/70 bg-primary/5", className)}
|
|
onFocus={() => draft.setDraft({ isRecording: true })}
|
|
onBlur={() => draft.setDraft({ isRecording: false })}
|
|
onChange={(event) => draft.setDraft({ keyDraft: event.currentTarget.value })}
|
|
onKeyDown={draft.captureKeybinding}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function NewKeybindingWhen({
|
|
draft,
|
|
variables,
|
|
}: {
|
|
draft: NewKeybindingDraft;
|
|
variables: ReadonlyArray<WhenVariableOption>;
|
|
}) {
|
|
return (
|
|
<WhenClauseControl
|
|
label={draft.commandLabelText}
|
|
expression={draft.whenDraftExpression}
|
|
value={draft.whenDraft}
|
|
variables={variables}
|
|
onChange={(whenDraft) => draft.setDraft({ whenDraft })}
|
|
onValidityChange={(isWhenDraftValid) => draft.setDraft({ isWhenDraftValid })}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function NewKeybindingCancelIcon({
|
|
isSaving,
|
|
onCancel,
|
|
}: {
|
|
isSaving: boolean;
|
|
onCancel: () => void;
|
|
}) {
|
|
return (
|
|
<Tooltip>
|
|
<TooltipTrigger
|
|
render={
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon-sm"
|
|
className="text-muted-foreground hover:text-foreground"
|
|
disabled={isSaving}
|
|
aria-label="Cancel new keybinding"
|
|
onClick={onCancel}
|
|
/>
|
|
}
|
|
>
|
|
<XIcon className="size-3.5" />
|
|
</TooltipTrigger>
|
|
<TooltipPopup side="top">Cancel</TooltipPopup>
|
|
</Tooltip>
|
|
);
|
|
}
|
|
|
|
/** Add-binding form shaped like the binding rows below it. */
|
|
function NewKeybindingSettingsRow(props: NewKeybindingProps) {
|
|
const { commandOptions, allRows, variables, isSaving, onSave, onCancel } = props;
|
|
const draft = useNewKeybindingDraft({ allRows, onSave });
|
|
|
|
return (
|
|
<SettingsRow
|
|
className="rounded-none bg-muted/15"
|
|
title="New keybinding"
|
|
description={
|
|
<span className="flex h-6 items-center gap-1.5">
|
|
<span className="text-[12px] leading-none text-muted-foreground/70">When</span>
|
|
<NewKeybindingWhen draft={draft} variables={variables} />
|
|
</span>
|
|
}
|
|
control={
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<NewKeybindingCommandSelect
|
|
draft={draft}
|
|
commandOptions={commandOptions}
|
|
className="w-56"
|
|
/>
|
|
<KeybindingConflictWarning labels={draft.conflictLabels} />
|
|
<NewKeybindingKeyInput draft={draft} className="w-44" />
|
|
<Button size="sm" disabled={isSaving || !draft.canSave} onClick={draft.save}>
|
|
{isSaving ? "Saving" : "Save"}
|
|
</Button>
|
|
<NewKeybindingCancelIcon isSaving={isSaving} onCancel={onCancel} />
|
|
</div>
|
|
}
|
|
/>
|
|
);
|
|
}
|
|
|
|
interface KeybindingsListProps extends KeybindingRowActions {
|
|
rows: ReadonlyArray<KeybindingRow>;
|
|
commandOptions: ReadonlyArray<KeybindingCommandOption>;
|
|
savingCommand: KeybindingCommand | null;
|
|
isAddingBinding: boolean;
|
|
onCancelAdd: () => void;
|
|
}
|
|
|
|
/** The add-binding row, one settings row per binding, and the empty state. */
|
|
function KeybindingsList(props: KeybindingsListProps) {
|
|
const { rows, commandOptions, savingCommand, isAddingBinding, onCancelAdd, ...rowActions } =
|
|
props;
|
|
const newProps: NewKeybindingProps = {
|
|
commandOptions,
|
|
allRows: rows,
|
|
variables: rowActions.variables,
|
|
isSaving: savingCommand !== null,
|
|
onSave: rowActions.onSave,
|
|
onCancel: onCancelAdd,
|
|
};
|
|
return (
|
|
<div>
|
|
{isAddingBinding ? <NewKeybindingSettingsRow {...newProps} /> : null}
|
|
{rows.map((row) => (
|
|
<KeybindingSettingsRow
|
|
key={row.id}
|
|
row={row}
|
|
isSaving={savingCommand === row.command}
|
|
{...rowActions}
|
|
/>
|
|
))}
|
|
{rows.length === 0 && !isAddingBinding ? (
|
|
<div className="px-4 py-12 text-center text-sm text-muted-foreground">
|
|
No keybindings match your search.
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** Shown in the browser build only; the desktop app receives every shortcut. */
|
|
function BrowserKeybindingNotice() {
|
|
return (
|
|
<div className="flex items-center gap-1.5 px-3 pb-2 text-[12px] text-muted-foreground sm:px-4">
|
|
<TriangleAlertIcon className="size-3.5 shrink-0 text-warning" aria-hidden />
|
|
<span>
|
|
Some shortcuts may be claimed by the browser before T3 Code sees them. Use the desktop app
|
|
for better keybinding support.
|
|
</span>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function KeybindingsSettingsPanel() {
|
|
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
|
const keybindingsConfigPath = useAtomValue(primaryServerKeybindingsConfigPathAtom);
|
|
const availableEditors = useAtomValue(primaryServerAvailableEditorsAtom);
|
|
const primaryEnvironment = usePrimaryEnvironment();
|
|
const upsertKeybinding = useAtomCommand(serverEnvironment.upsertKeybinding, {
|
|
reportFailure: false,
|
|
});
|
|
const removeKeybindingMutation = useAtomCommand(serverEnvironment.removeKeybinding, {
|
|
reportFailure: false,
|
|
});
|
|
const openInPreferredEditor = useOpenInPreferredEditor(
|
|
primaryEnvironment?.environmentId ?? null,
|
|
availableEditors,
|
|
);
|
|
const [query, setQuery] = useState("");
|
|
const [isSearchOpen, setIsSearchOpen] = useState(false);
|
|
const searchInputRef = useRef<HTMLInputElement>(null);
|
|
const [savingCommand, setSavingCommand] = useState<KeybindingCommand | null>(null);
|
|
const [isAddingBinding, setIsAddingBinding] = useState(false);
|
|
const rows = useMemo(() => buildKeybindingRows(keybindings, query), [keybindings, query]);
|
|
const commandOptions = useMemo(() => buildKeybindingCommandOptions(keybindings), [keybindings]);
|
|
const whenVariables = useMemo(() => buildWhenVariableOptions(), []);
|
|
|
|
useEffect(() => {
|
|
const handleKeyDown = (event: globalThis.KeyboardEvent) => {
|
|
const isMod = event.metaKey || event.ctrlKey;
|
|
if (!isMod || event.altKey || event.key.toLowerCase() !== "f") return;
|
|
|
|
const target = event.target;
|
|
if (
|
|
target !== searchInputRef.current &&
|
|
target instanceof HTMLElement &&
|
|
(target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable)
|
|
) {
|
|
return;
|
|
}
|
|
|
|
event.preventDefault();
|
|
setIsSearchOpen(true);
|
|
requestAnimationFrame(() => {
|
|
searchInputRef.current?.focus();
|
|
searchInputRef.current?.select();
|
|
});
|
|
};
|
|
window.addEventListener("keydown", handleKeyDown);
|
|
return () => window.removeEventListener("keydown", handleKeyDown);
|
|
}, []);
|
|
|
|
const openKeybindingsFile = useCallback(() => {
|
|
if (!keybindingsConfigPath) return;
|
|
void (async () => {
|
|
const result = await openInPreferredEditor(keybindingsConfigPath);
|
|
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
|
|
return;
|
|
}
|
|
const error = squashAtomCommandFailure(result);
|
|
toastManager.add({
|
|
title: "Unable to open keybindings file",
|
|
description:
|
|
error instanceof Error ? error.message : "The keybindings file was not opened.",
|
|
type: "error",
|
|
});
|
|
})();
|
|
}, [keybindingsConfigPath, openInPreferredEditor]);
|
|
|
|
const saveKeybinding = useCallback(
|
|
(input: ServerUpsertKeybindingInput) => {
|
|
if (!primaryEnvironment) return;
|
|
setSavingCommand(input.command);
|
|
const payload: ServerUpsertKeybindingInput = {
|
|
command: input.command,
|
|
key: input.key.trim(),
|
|
...(input.when?.trim() ? { when: input.when.trim() } : {}),
|
|
...(input.replace ? { replace: input.replace } : {}),
|
|
};
|
|
void (async () => {
|
|
const result = await upsertKeybinding({
|
|
environmentId: primaryEnvironment.environmentId,
|
|
input: payload,
|
|
});
|
|
setSavingCommand(null);
|
|
if (result._tag === "Success") {
|
|
setIsAddingBinding(false);
|
|
return;
|
|
}
|
|
if (!isAtomCommandInterrupted(result)) {
|
|
const error = squashAtomCommandFailure(result);
|
|
toastManager.add({
|
|
title: "Unable to save keybinding",
|
|
description: error instanceof Error ? error.message : "The keybinding was not saved.",
|
|
type: "error",
|
|
});
|
|
}
|
|
})();
|
|
},
|
|
[primaryEnvironment, upsertKeybinding],
|
|
);
|
|
|
|
const removeKeybinding = useCallback(
|
|
(row: KeybindingRow) => {
|
|
if (!primaryEnvironment) return;
|
|
setSavingCommand(row.command);
|
|
void (async () => {
|
|
const result = await removeKeybindingMutation({
|
|
environmentId: primaryEnvironment.environmentId,
|
|
input: rowKeybindingTarget(row),
|
|
});
|
|
setSavingCommand(null);
|
|
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
|
const error = squashAtomCommandFailure(result);
|
|
toastManager.add({
|
|
title: "Unable to remove keybinding",
|
|
description: error instanceof Error ? error.message : "The keybinding was not removed.",
|
|
type: "error",
|
|
});
|
|
}
|
|
})();
|
|
},
|
|
[primaryEnvironment, removeKeybindingMutation],
|
|
);
|
|
|
|
const resetKeybinding = useCallback(
|
|
(row: KeybindingRow) => {
|
|
if (!row.defaultKey) return;
|
|
saveKeybinding({
|
|
command: row.command,
|
|
key: row.defaultKey,
|
|
when: row.defaultWhen.trim().length > 0 ? row.defaultWhen : undefined,
|
|
replace: {
|
|
command: row.command,
|
|
key: row.key,
|
|
...(row.when.trim().length > 0 ? { when: row.when } : {}),
|
|
},
|
|
});
|
|
},
|
|
[saveKeybinding],
|
|
);
|
|
|
|
const cancelAdd = useCallback(() => setIsAddingBinding(false), []);
|
|
|
|
const bindingsCount = (
|
|
<span className="text-[11px] text-muted-foreground">
|
|
{rows.length + (isAddingBinding ? 1 : 0)}{" "}
|
|
{rows.length + (isAddingBinding ? 1 : 0) === 1 ? "binding" : "bindings"}
|
|
</span>
|
|
);
|
|
|
|
const listProps: KeybindingsListProps = {
|
|
rows,
|
|
allRows: rows,
|
|
commandOptions,
|
|
variables: whenVariables,
|
|
savingCommand,
|
|
isAddingBinding,
|
|
onCancelAdd: cancelAdd,
|
|
onSave: saveKeybinding,
|
|
onReset: resetKeybinding,
|
|
onRemove: removeKeybinding,
|
|
};
|
|
|
|
return (
|
|
<SettingsPageContainer>
|
|
<SettingsSection
|
|
{...searchableSetting("keybindings")}
|
|
headerAction={
|
|
<div className="flex items-center gap-1.5">
|
|
<ExpandableHeaderSearch
|
|
query={query}
|
|
onChange={setQuery}
|
|
isOpen={isSearchOpen}
|
|
onOpenChange={setIsSearchOpen}
|
|
inputRef={searchInputRef}
|
|
collapsedAccessory={bindingsCount}
|
|
/>
|
|
<Tooltip>
|
|
<TooltipTrigger
|
|
render={
|
|
<Button
|
|
type="button"
|
|
size="icon-xs"
|
|
variant="ghost-muted"
|
|
onClick={() => setIsAddingBinding(true)}
|
|
aria-label="Add keybinding"
|
|
>
|
|
<PlusIcon />
|
|
</Button>
|
|
}
|
|
/>
|
|
<TooltipPopup side="top">Add keybinding</TooltipPopup>
|
|
</Tooltip>
|
|
<Tooltip>
|
|
<TooltipTrigger
|
|
render={
|
|
<Button
|
|
type="button"
|
|
size="icon-xs"
|
|
variant="ghost-muted"
|
|
disabled={!keybindingsConfigPath}
|
|
onClick={openKeybindingsFile}
|
|
aria-label="Open keybindings.json"
|
|
>
|
|
<FileJsonIcon />
|
|
</Button>
|
|
}
|
|
/>
|
|
<TooltipPopup side="top">Open keybindings.json</TooltipPopup>
|
|
</Tooltip>
|
|
</div>
|
|
}
|
|
>
|
|
{!isElectron ? <BrowserKeybindingNotice /> : null}
|
|
|
|
<KeybindingsList {...listProps} />
|
|
</SettingsSection>
|
|
</SettingsPageContainer>
|
|
);
|
|
}
|