TypeScript
feat(web): group keybindings settings by area with a page toolbar (#12822)
maria72d5c32ba679
diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.tsindex f790f368131..2e5f8807908 100644--- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts@@ -7,6 +7,7 @@ import {buildKeybindingCommandOptions,buildWhenVariableOptions,commandLabel,+ groupKeybindingRows,keybindingConflictLabels,keybindingFromKeyboardEvent,parseWhenExpressionDraft,@@ -58,6 +59,25 @@ describe("KeybindingsSettings.logic", () => {);},);+ it("groups rows by command area in page order and drops empty groups", () => {+ const groups = groupKeybindingRows(buildKeybindingRows(DEFAULT_RESOLVED_KEYBINDINGS, ""));+ expect(groups.map((group) => group.title)).toEqual([+ "Navigation",+ "Threads",+ "Composer",+ "Terminal",+ "Preview & diff",+ "Appearance",+ "Other",+ ]);+ const composer = groups.find((group) => group.id === "composer");+ expect(composer?.rows.map((row) => row.command)).toEqual(+ expect.arrayContaining(["composer.host", "modelPicker.toggle"]),+ );+ expect(groupKeybindingRows(buildKeybindingRows(DEFAULT_RESOLVED_KEYBINDINGS, "split"))).toEqual(+ [expect.objectContaining({ id: "terminal" })],+ );+ });it("orders Usage bindings and command choices like the page", () => {const expected = ["usage.open",diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.tsindex cbdd456a017..fde8f3419c0 100644--- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts@@ -201,6 +201,53 @@ export function keybindingConflictLabels(return [...new Set(conflicts)].toSorted();}+export interface KeybindingGroup {+ readonly id: string;+ readonly title: string;+ readonly rows: ReadonlyArray<KeybindingRow>;+}++/** Page sections in display order; a command joins the first group listing its prefix. */+const KEYBINDING_GROUPS = [+ {+ id: "navigation",+ title: "Navigation",+ prefixes: ["sidebar", "rightPanel", "commandPalette", "filePicker", "projectSearch", "editor"],+ },+ { id: "threads", title: "Threads", prefixes: ["thread", "chat", "pullRequest"] },+ { id: "composer", title: "Composer", prefixes: ["composer", "modelPicker"] },+ { id: "terminal", title: "Terminal", prefixes: ["terminal"] },+ { id: "preview", title: "Preview & diff", prefixes: ["preview", "diff"] },+ { id: "appearance", title: "Appearance", prefixes: ["theme", "appearance", "themeEditor"] },+ { id: "scripts", title: "Project scripts", prefixes: ["script"] },+] as const;+const OTHER_KEYBINDING_GROUP = { id: "other", title: "Other" } as const;++function keybindingGroupFor(command: KeybindingCommand): { id: string; title: string } {+ const prefix = String(command).split(".")[0] ?? "";+ return (+ KEYBINDING_GROUPS.find((group) => (group.prefixes as ReadonlyArray<string>).includes(prefix)) ??+ OTHER_KEYBINDING_GROUP+ );+}++/** Splits sorted rows into the page's sections, dropping sections with no rows. */+export function groupKeybindingRows(+ rows: ReadonlyArray<KeybindingRow>,+): ReadonlyArray<KeybindingGroup> {+ const rowsByGroup = new Map<string, Array<KeybindingRow>>();+ for (const row of rows) {+ const group = keybindingGroupFor(row.command);+ const bucket = rowsByGroup.get(group.id);+ if (bucket) bucket.push(row);+ else rowsByGroup.set(group.id, [row]);+ }+ return [...KEYBINDING_GROUPS, OTHER_KEYBINDING_GROUP].flatMap((group) => {+ const groupRows = rowsByGroup.get(group.id);+ return groupRows ? [{ id: group.id, title: group.title, rows: groupRows }] : [];+ });+}+export function buildKeybindingRows(keybindings: ResolvedKeybindingsConfig,query: string,diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsxindex bf14e709dda..b2660f8943e 100644--- a/apps/web/src/components/settings/KeybindingsSettings.tsx+++ b/apps/web/src/components/settings/KeybindingsSettings.tsx@@ -59,13 +59,16 @@ import {keybindingConflictLabels,keybindingFromKeyboardEvent,parseWhenExpressionDraft,+ groupKeybindingRows,type KeybindingCommandOption,+ type KeybindingGroup,type KeybindingRow,type WhenVariableOption,unknownWhenVariables,whenAstToExpression,whenNodeRemoveLabel,} from "./KeybindingsSettings.logic";+import { SettingsGroup } from "./SettingsGroup";import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";import { keybindingSearchAnchorId, searchableSetting } from "./settingsSearch";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";@@ -104,65 +107,33 @@ function KeybindingPill({ value }: { value: string }) {);}-function ExpandableHeaderSearch({+/** Filter box in the page toolbar; Mod+F focuses it from anywhere on the page. */+function KeybindingsSearchInput({query,onChange,- isOpen,- onOpenChange,inputRef,- collapsedAccessory,}: {query: string;onChange: (next: string) => void;- isOpen: boolean;- onOpenChange: (next: boolean) => void;- inputRef?: RefObject<HTMLInputElement | null>;- collapsedAccessory?: ReactNode;+ inputRef: RefObject<HTMLInputElement | null>;}) {- 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 (- <InputGroup className="w-44">+ <InputGroup className="min-w-0 basis-full **:[input]:h-9 sm:basis-0 sm:flex-1 sm:**:[input]:h-8"><InputGroupAddon>- <SearchIcon aria-hidden className="size-3" />+ <SearchIcon aria-hidden className="size-3.5" /></InputGroupAddon><InputGroupInputref={inputRef}- autoFocustype="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);- }+ // The settings route treats an unhandled Escape as "go back";+ // inside the search box it clears, then leaves the field.+ if (event.key !== "Escape") return;+ event.preventDefault();+ if (query.length > 0) onChange("");+ else event.currentTarget.blur();}}placeholder="Search keybindings"aria-label="Search keybindings"@@ -1232,7 +1203,7 @@ function NewKeybindingSettingsRow(props: NewKeybindingProps) {return (<SettingsRow- className="rounded-none bg-muted/15"+ className="bg-muted/15"title="New keybinding"description={<span className="flex h-6 items-center gap-1.5">@@ -1259,41 +1230,18 @@ function NewKeybindingSettingsRow(props: NewKeybindingProps) {);}-interface KeybindingsListProps extends KeybindingRowActions {- rows: ReadonlyArray<KeybindingRow>;- commandOptions: ReadonlyArray<KeybindingCommandOption>;+interface KeybindingsGroupsProps extends KeybindingRowActions {+ groups: ReadonlyArray<KeybindingGroup>;+ anchorIds: ReadonlyMap<string, string>;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,- };- // Settings search jumps to a command, so only its first row anchors.- const anchorIds = useMemo(() => {- const ids = new Map<string, string>();- const seen = new Set<KeybindingCommand>();- for (const row of rows) {- if (seen.has(row.command)) continue;- seen.add(row.command);- ids.set(row.id, keybindingSearchAnchorId(row.command));- }- return ids;- }, [rows]);- return (- <div>- {isAddingBinding ? <NewKeybindingSettingsRow {...newProps} /> : null}- {rows.map((row) => (+/** One titled section per command area, each holding its binding rows. */+function KeybindingsGroups(props: KeybindingsGroupsProps) {+ const { groups, anchorIds, savingCommand, ...rowActions } = props;+ return groups.map((group) => (+ <SettingsSection key={group.id} id={`keybindings-${group.id}`} title={group.title}>+ {group.rows.map((row) => (<KeybindingSettingsRowkey={row.id}row={row}@@ -1302,25 +1250,29 @@ function KeybindingsList(props: KeybindingsListProps) {{...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>- );+ </SettingsSection>+ ));}/** Shown in the browser build only; the desktop app receives every shortcut. */function BrowserKeybindingNotice() {+ // The label carries the whole sentence so assistive tech reads it without+ // opening the tooltip.+ const message = "The browser may claim some shortcuts first. The desktop app receives them all.";return (- <div className="flex items-center gap-2 px-3 py-2.5 text-xs leading-normal 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>+ <Tooltip>+ <TooltipTrigger+ delay={200}+ render={+ <Button size="icon-micro" variant="ghost-muted" aria-label={message}>+ <TriangleAlertIcon className="size-3.5 text-warning" />+ </Button>+ }+ />+ <TooltipPopup side="top" className="max-w-72">+ {message}+ </TooltipPopup>+ </Tooltip>);}@@ -1347,11 +1299,22 @@ export function KeybindingsSettingsPanel() {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 groups = useMemo(() => groupKeybindingRows(rows), [rows]);+ // Settings search jumps to a command, so only its first row anchors.+ const anchorIds = useMemo(() => {+ const ids = new Map<string, string>();+ const seen = new Set<KeybindingCommand>();+ for (const row of rows) {+ if (seen.has(row.command)) continue;+ seen.add(row.command);+ ids.set(row.id, keybindingSearchAnchorId(row.command));+ }+ return ids;+ }, [rows]);// The search-target context is provided by this panel's own page container,// so the jump target is read from the route hash here.const searchTargetId = useLocation({ select: (location) => location.hash.replace(/^#/, "") });@@ -1380,11 +1343,8 @@ export function KeybindingsSettingsPanel() {}event.preventDefault();- setIsSearchOpen(true);- requestAnimationFrame(() => {- searchInputRef.current?.focus();- searchInputRef.current?.select();- });+ searchInputRef.current?.focus();+ searchInputRef.current?.select();};window.addEventListener("keydown", handleKeyDown);return () => window.removeEventListener("keydown", handleKeyDown);@@ -1489,21 +1449,9 @@ export function KeybindingsSettingsPanel() {const cancelAdd = useCallback(() => setIsAddingBinding(false), []);- const bindingsCount = (- <span className="text-2xs text-muted-foreground">- {rows.length + (isAddingBinding ? 1 : 0)}{" "}- {rows.length + (isAddingBinding ? 1 : 0) === 1 ? "binding" : "bindings"}- </span>- );-- const listProps: KeybindingsListProps = {- rows,+ const rowActions: KeybindingRowActions = {allRows: rows,- commandOptions,variables: whenVariables,- savingCommand,- isAddingBinding,- onCancelAdd: cancelAdd,onSave: saveKeybinding,onReset: resetKeybinding,onRemove: removeKeybinding,@@ -1513,56 +1461,66 @@ export function KeybindingsSettingsPanel() {<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>- }+ headerAction={!isElectron ? <BrowserKeybindingNotice /> : null}>- {!isElectron ? <BrowserKeybindingNotice /> : null}-- <KeybindingsList {...listProps} />+ <div className="flex flex-wrap items-center gap-2 px-3 py-3 sm:px-4">+ <KeybindingsSearchInput query={query} onChange={setQuery} inputRef={searchInputRef} />+ <Button+ type="button"+ variant="outline"+ disabled={isAddingBinding}+ onClick={() => setIsAddingBinding(true)}+ >+ <PlusIcon aria-hidden className="size-4" />+ Add keybinding+ </Button>+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ type="button"+ variant="outline"+ size="icon"+ disabled={!keybindingsConfigPath}+ onClick={openKeybindingsFile}+ aria-label="Open keybindings.json"+ >+ <FileJsonIcon aria-hidden className="size-4" />+ </Button>+ }+ />+ <TooltipPopup side="top">Open keybindings.json</TooltipPopup>+ </Tooltip>+ </div></SettingsSection>++ {isAddingBinding ? (+ <SettingsGroup>+ <NewKeybindingSettingsRow+ commandOptions={commandOptions}+ allRows={rows}+ variables={whenVariables}+ isSaving={savingCommand !== null}+ onSave={saveKeybinding}+ onCancel={cancelAdd}+ />+ </SettingsGroup>+ ) : null}++ {groups.length > 0 ? (+ <KeybindingsGroups+ groups={groups}+ anchorIds={anchorIds}+ savingCommand={savingCommand}+ {...rowActions}+ />+ ) : (+ <SettingsGroup>+ <div className="px-4 py-12 text-center text-sm text-muted-foreground">+ No keybindings match your search.+ </div>+ </SettingsGroup>+ )}</SettingsPageContainer>);}