feat(web): add settings sidebar search (#4682)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
shivamandClaude Fable 5 authored and GitHub committed 2026-07-31 18:11:27 -04:00
1 parent bfc31507f8
commit e5c7547067
12 files changed
+807 -83

No files matched your search

-3
View File
@@ -165,7 +165,6 @@ import {
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarSeparator,
useSidebar,
} from "./ui/sidebar";
import { useThreadSelectionStore } from "../threadSelectionStore";
@@ -3631,8 +3630,6 @@ export default function Sidebar() {
attachProjectListAutoAnimateRef={attachProjectListAutoAnimateRef}
projectsLength={projects.length}
/>
<SidebarSeparator />
<SidebarChromeFooter />
</>
)}
@@ -8,6 +8,7 @@ import {
import { Input } from "../ui/input";
import { Switch } from "../ui/switch";
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
const AUTO_SETTLE_MIN_DAYS = 1;
const AUTO_SETTLE_MAX_DAYS = 90;
@@ -65,7 +66,7 @@ export function BetaSettingsPanel() {
<SettingsPageContainer>
<SettingsSection title="Beta features">
<SettingsRow
title="Sidebar v2"
{...searchableSetting("sidebar-v2")}
description="One flat thread list in creation order. Active work renders as rich cards; settled threads collapse to compact rows. Settling requires an up-to-date server — on older servers threads simply stay active. Switch back any time."
control={
<Switch
@@ -85,7 +86,7 @@ export function BetaSettingsPanel() {
{sidebarV2Enabled ? (
<>
<SettingsRow
title="Auto-settle inactive threads"
title={searchableSetting("auto-settle-inactive-threads").title}
description="Threads with no activity for this long settle automatically. Threads on merged or closed PRs always settle."
control={
<Switch
@@ -49,6 +49,7 @@ import {
SettingsSection,
useRelativeTimeTick,
} from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
import { Input } from "../ui/input";
import { Checkbox } from "../ui/checkbox";
import {
@@ -3351,7 +3352,7 @@ export function ConnectionsSettings() {
)}
<SettingsSection
title="Remote environments"
{...searchableSetting("remote-environments")}
headerAction={
<Dialog
open={addBackendDialogOpen}
@@ -70,6 +70,7 @@ import {
whenAstToExpression,
} from "./KeybindingsSettings.logic";
import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { useAtomCommand } from "../../state/use-atom-command";
@@ -1230,7 +1231,7 @@ export function KeybindingsSettingsPanel() {
return (
<SettingsPageContainer className="max-w-5xl">
<SettingsSection
title="Keybindings"
{...searchableSetting("keybindings")}
headerAction={
<div className="flex items-center gap-1.5">
<ExpandableHeaderSearch
@@ -136,6 +136,7 @@ import {
SettingsSection,
useRelativeTimeTick,
} from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
import { ProjectFavicon } from "../ProjectFavicon";
import { useAtomCommand } from "../../state/use-atom-command";
@@ -963,9 +964,9 @@ export function AppearanceSettingsPanel() {
return (
<SettingsPageContainer>
<SettingsSection title="Appearance">
<SettingsSection id="appearance" title="Appearance">
<SettingsRow
title="Theme"
{...searchableSetting("theme")}
description="Choose how T3 Code looks across the app."
resetAction={
theme !== "system" ? (
@@ -998,7 +999,7 @@ export function AppearanceSettingsPanel() {
/>
<SettingsRow
title="Glass opacity"
{...searchableSetting("setting-glass-opacity")}
description="Control how transparent glass surfaces are. Higher values make menus, dialogs, and the composer more solid."
resetAction={
settings.glassOpacity !== DEFAULT_UNIFIED_SETTINGS.glassOpacity ? (
@@ -1045,7 +1046,7 @@ export function AppearanceSettingsPanel() {
{showEnvironmentIdentification ? (
<SettingsRow
title="Environment identification"
{...searchableSetting("environment-identification")}
description="Choose how Dev and Nightly environments are identified."
resetAction={
settings.environmentIdentificationMode !== DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE ? (
@@ -1086,7 +1087,7 @@ export function AppearanceSettingsPanel() {
) : null}
<SettingsRow
title="Word wrap"
{...searchableSetting("word-wrap")}
description="Wrap long lines in code blocks, tables, diffs, and file previews by default."
resetAction={
settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? (
@@ -1170,7 +1171,7 @@ export function GeneralSettingsPanel() {
<SettingsPageContainer>
<SettingsSection title="General">
<SettingsRow
title="Project Grouping"
{...searchableSetting("project-grouping")}
description="Combine matching repositories across environments."
resetAction={
settings.sidebarProjectGroupingMode !==
@@ -1200,13 +1201,13 @@ export function GeneralSettingsPanel() {
),
});
}}
aria-label="Project Grouping"
aria-label="Project grouping"
/>
}
/>
<SettingsRow
title="Time format"
{...searchableSetting("time-format")}
description="System default follows your browser or OS clock preference."
resetAction={
settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat ? (
@@ -1248,7 +1249,7 @@ export function GeneralSettingsPanel() {
/>
<SettingsRow
title="Hide whitespace changes"
{...searchableSetting("hide-whitespace-changes")}
description="Set whether the diff panel ignores whitespace-only edits by default."
resetAction={
settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace ? (
@@ -1274,7 +1275,7 @@ export function GeneralSettingsPanel() {
/>
<SettingsRow
title="Assistant output"
{...searchableSetting("assistant-output")}
description="Show token-by-token output while a response is in progress."
resetAction={
settings.enableAssistantStreaming !==
@@ -1301,7 +1302,7 @@ export function GeneralSettingsPanel() {
/>
<SettingsRow
title="Provider update checks"
{...searchableSetting("provider-update-checks")}
description="Check installed provider CLIs for newer available versions."
resetAction={
settings.enableProviderUpdateChecks !==
@@ -1410,7 +1411,7 @@ export function GeneralSettingsPanel() {
/>
<SettingsRow
title="Auto-open task panel"
{...searchableSetting("auto-open-task-panel")}
description="Open the right-side plan and task panel automatically when steps appear."
resetAction={
settings.autoOpenPlanSidebar !== DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar ? (
@@ -1436,7 +1437,7 @@ export function GeneralSettingsPanel() {
/>
<SettingsRow
title="New threads"
{...searchableSetting("new-threads")}
description="Pick the default workspace mode for newly created draft threads."
resetAction={
settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode ||
@@ -1483,7 +1484,7 @@ export function GeneralSettingsPanel() {
{settings.defaultThreadEnvMode === "worktree" ? (
<SettingsRow
className="bg-muted/20 sm:pl-9"
title="Start from origin"
title={searchableSetting("start-from-origin").title}
description="Creates the worktree from the latest matching branch on origin instead of your local branch."
resetAction={
settings.newWorktreesStartFromOrigin !==
@@ -1512,7 +1513,7 @@ export function GeneralSettingsPanel() {
) : null}
<SettingsRow
title="Add project starts in"
{...searchableSetting("add-project-starts-in")}
description='Leave empty to use "~/" when the Add Project browser opens.'
resetAction={
settings.addProjectBaseDirectory !==
@@ -1540,7 +1541,7 @@ export function GeneralSettingsPanel() {
/>
<SettingsRow
title="Archive confirmation"
{...searchableSetting("archive-confirmation")}
description="Require a second click on the inline archive action before a thread is archived."
resetAction={
settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive ? (
@@ -1566,7 +1567,7 @@ export function GeneralSettingsPanel() {
/>
<SettingsRow
title="Delete confirmation"
{...searchableSetting("delete-confirmation")}
description="Ask before deleting a thread and its chat history."
resetAction={
settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete ? (
@@ -1592,7 +1593,7 @@ export function GeneralSettingsPanel() {
/>
<SettingsRow
title="Text generation model"
{...searchableSetting("text-generation-model")}
description="Default model for generated text like thread titles and source control content. Source control settings can override it with a dedicated source control writer model."
resetAction={
isTextGenerationModelDirty ? (
@@ -1676,7 +1677,7 @@ export function GeneralSettingsPanel() {
/>
)}
<SettingsRow
title="Diagnostics"
{...searchableSetting("diagnostics")}
description={diagnosticsDescription}
control={
<Button render={<Link to="/settings/diagnostics" />} size="xs" variant="outline">
@@ -1991,7 +1992,7 @@ export function ProviderSettingsPanel() {
return (
<SettingsPageContainer>
<SettingsSection
title="Providers"
{...searchableSetting("providers")}
headerAction={
<div className="flex items-center gap-1.5">
<ProviderLastChecked lastCheckedAt={lastCheckedAt} />
@@ -2320,7 +2321,10 @@ export function ArchivedThreadsPanel() {
return (
<SettingsPageContainer>
{archivedGroups.length === 0 ? (
<SettingsSection title="Archived threads">
<SettingsSection
id={isLoadingArchive ? undefined : searchableSetting("archive").id}
title={searchableSetting("archive").title}
>
<SettingsRow
title={
<span className="inline-flex items-center gap-2">
@@ -2344,9 +2348,10 @@ export function ArchivedThreadsPanel() {
/>
</SettingsSection>
) : (
archivedGroups.map(({ project, threads: projectThreads }) => (
archivedGroups.map(({ project, threads: projectThreads }, index) => (
<SettingsSection
key={project.id}
id={index === 0 ? searchableSetting("archive").id : undefined}
title={project.name}
icon={<ProjectFavicon environmentId={project.environmentId} cwd={project.cwd} />}
>
@@ -1,4 +1,12 @@
import { useCallback, type ComponentType } from "react";
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ComponentType,
type KeyboardEvent,
} from "react";
import {
ArchiveIcon,
ArrowLeftIcon,
@@ -8,10 +16,15 @@ import {
KeyboardIcon,
Link2Icon,
PaletteIcon,
SearchIcon,
Settings2Icon,
XIcon,
} from "lucide-react";
import { useCanGoBack, useNavigate } from "@tanstack/react-router";
import { useCanGoBack, useLocation, useNavigate } from "@tanstack/react-router";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Kbd } from "../ui/kbd";
import {
SidebarContent,
SidebarFooter,
@@ -22,45 +35,149 @@ import {
useSidebar,
} from "../ui/sidebar";
import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3ConnectSidebarSignIn";
import { scrollToSettingsTarget } from "./settingsLayout";
import {
searchSettings,
SETTINGS_SECTION_LABELS,
type SettingsPath,
type SettingsSearchItem,
} from "./settingsSearch";
export type SettingsSectionPath =
| "/settings/general"
| "/settings/appearance"
| "/settings/keybindings"
| "/settings/providers"
| "/settings/source-control"
| "/settings/connections"
| "/settings/beta"
| "/settings/archived";
const SETTINGS_SECTION_ICONS: Readonly<
Record<SettingsPath, ComponentType<{ className?: string }>>
> = {
"/settings/general": Settings2Icon,
"/settings/appearance": PaletteIcon,
"/settings/keybindings": KeyboardIcon,
"/settings/providers": BotIcon,
"/settings/source-control": GitBranchIcon,
"/settings/connections": Link2Icon,
"/settings/beta": FlaskConicalIcon,
"/settings/archived": ArchiveIcon,
};
export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
label: string;
to: SettingsSectionPath;
to: SettingsPath;
icon: ComponentType<{ className?: string }>;
}> = [
{ label: "General", to: "/settings/general", icon: Settings2Icon },
{ label: "Appearance", to: "/settings/appearance", icon: PaletteIcon },
{ label: "Keybindings", to: "/settings/keybindings", icon: KeyboardIcon },
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
{ label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon },
{ label: "Connections", to: "/settings/connections", icon: Link2Icon },
{ label: "Beta", to: "/settings/beta", icon: FlaskConicalIcon },
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
];
}> = (Object.keys(SETTINGS_SECTION_LABELS) as SettingsPath[]).map((to) => ({
to,
label: SETTINGS_SECTION_LABELS[to],
icon: SETTINGS_SECTION_ICONS[to],
}));
function SettingsSectionIcon({ to }: { to: SettingsPath }) {
const Icon = SETTINGS_SECTION_ICONS[to];
return <Icon className="mt-0.5 size-3.5 shrink-0 text-sidebar-muted-foreground/60" />;
}
export function SettingsSidebarNav({ pathname }: { pathname: string }) {
const navigate = useNavigate();
const currentHash = useLocation({ select: (location) => location.hash });
const canGoBack = useCanGoBack();
const { isMobile, setOpenMobile } = useSidebar();
const { isMobile, setOpenMobile, open, setOpen } = useSidebar();
const searchInputRef = useRef<HTMLInputElement>(null);
const [query, setQuery] = useState("");
const [activeResultIndex, setActiveResultIndex] = useState(0);
const results = useMemo(() => searchSettings(query), [query]);
const isSearching = query.trim().length > 0;
const hasResults = results.length > 0;
useEffect(() => {
const result = results[activeResultIndex];
if (!result) return;
document
.getElementById(`settings-search-result-${result.id}`)
?.scrollIntoView({ block: "nearest" });
}, [activeResultIndex, results]);
useEffect(() => {
const handleKeyDown = (event: globalThis.KeyboardEvent) => {
if (event.key !== "/" || event.metaKey || event.ctrlKey || event.altKey) return;
const target = event.target;
if (
target instanceof HTMLElement &&
(target.tagName === "INPUT" ||
target.tagName === "TEXTAREA" ||
target.isContentEditable ||
// Keep focus inside open dialogs and popups instead of escaping
// their focus trap into the sidebar search.
target.closest('[role="dialog"], [aria-modal="true"], [data-slot$="popup"]') !== null)
) {
return;
}
event.preventDefault();
if (isMobile) {
setOpenMobile(true);
} else if (!open) {
setOpen(true);
}
requestAnimationFrame(() => {
searchInputRef.current?.focus();
searchInputRef.current?.select();
});
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [isMobile, open, setOpen, setOpenMobile]);
const handleSectionClick = useCallback(
(to: SettingsSectionPath) => {
(to: SettingsPath) => {
if (isMobile) {
setOpenMobile(false);
}
void navigate({ to, replace: true });
void navigate({ to, hash: "", replace: true, hashScrollIntoView: false });
},
[isMobile, navigate, setOpenMobile],
);
const clearSearch = useCallback(() => {
setQuery("");
setActiveResultIndex(0);
}, []);
const handleSearchResultClick = useCallback(
(item: SettingsSearchItem) => {
clearSearch();
if (isMobile) {
setOpenMobile(false);
}
const targetId = item.targetId ?? item.id;
if (pathname === item.to && currentHash.replace(/^#/, "") === targetId) {
scrollToSettingsTarget(targetId);
return;
}
void navigate({ to: item.to, hash: targetId, replace: true, hashScrollIntoView: false });
},
[clearSearch, currentHash, isMobile, navigate, pathname, setOpenMobile],
);
const handleSearchKeyDown = useCallback(
(event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Escape" && isSearching) {
event.preventDefault();
event.stopPropagation();
clearSearch();
return;
}
if (results.length === 0) return;
if (event.key === "ArrowDown") {
event.preventDefault();
setActiveResultIndex((index) => (index + 1) % results.length);
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
setActiveResultIndex((index) => (index - 1 + results.length) % results.length);
return;
}
if (event.key === "Enter") {
event.preventDefault();
const result = results[activeResultIndex];
if (result) handleSearchResultClick(result);
}
},
[activeResultIndex, clearSearch, handleSearchResultClick, isSearching, results],
);
const handleBackClick = useCallback(() => {
if (isMobile) {
setOpenMobile(false);
@@ -75,23 +192,107 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
return (
<>
<SidebarContent className="overflow-x-hidden">
<SidebarGroup className="p-[var(--sidebar-content-inset)]">
<SidebarMenu>
{SETTINGS_NAV_ITEMS.map((item) => {
const Icon = item.icon;
const isActive = pathname === item.to;
return (
<SidebarMenuItem key={item.to}>
<SidebarMenuButton
isActive={isActive}
onClick={() => handleSectionClick(item.to)}
>
<Icon />
<span className="truncate">{item.label}</span>
</SidebarMenuButton>
</SidebarMenuItem>
);
})}
<SidebarGroup className="gap-2 p-[var(--sidebar-content-inset)]">
<div className="flex h-8 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground">
<SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
<Input
ref={searchInputRef}
nativeInput
unstyled
type="search"
value={query}
onChange={(event) => {
setQuery(event.currentTarget.value);
setActiveResultIndex(0);
}}
onKeyDown={handleSearchKeyDown}
placeholder="Search"
aria-label="Search settings"
role="combobox"
aria-autocomplete="list"
aria-expanded={isSearching && hasResults}
aria-controls={isSearching && hasResults ? "settings-search-results" : undefined}
aria-activedescendant={
isSearching && results[activeResultIndex]
? `settings-search-result-${results[activeResultIndex].id}`
: undefined
}
className="min-w-0 flex-1 [&_[data-slot=input]]:h-auto [&_[data-slot=input]]:p-0 [&_[data-slot=input]]:leading-normal [&_[data-slot=input]]:text-sm [&_[data-slot=input]]:font-medium [&_[data-slot=input]]:text-sidebar-foreground [&_[data-slot=input]]:placeholder:text-sidebar-muted-foreground"
/>
{isSearching ? (
<Button
type="button"
size="icon-xs"
variant="ghost"
className="size-5 shrink-0 rounded-sm text-sidebar-muted-foreground hover:bg-sidebar-control-surface hover:text-sidebar-foreground"
aria-label="Clear settings search"
onClick={() => {
clearSearch();
searchInputRef.current?.focus();
}}
>
<XIcon className="size-3" />
</Button>
) : (
<Kbd className="mr-px h-4 min-w-0 rounded-sm bg-sidebar-control-surface px-1.5 text-[10px] text-sidebar-muted-foreground ring-1 ring-sidebar-border">
/
</Kbd>
)}
</div>
{isSearching && results.length === 0 ? (
<p
role="status"
className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground"
>
No settings found
</p>
) : null}
<SidebarMenu
id={isSearching && hasResults ? "settings-search-results" : undefined}
role={isSearching && hasResults ? "listbox" : undefined}
aria-label={isSearching && hasResults ? "Settings search results" : undefined}
>
{isSearching
? results.map((item, index) => (
<SidebarMenuItem key={item.id} role="presentation">
<SidebarMenuButton
id={`settings-search-result-${item.id}`}
role="option"
aria-selected={index === activeResultIndex}
tabIndex={-1}
size="sm"
isActive={index === activeResultIndex}
className="h-auto min-h-10 items-start gap-2 rounded-md px-2 py-2 text-left hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
onMouseMove={() => setActiveResultIndex(index)}
onClick={() => handleSearchResultClick(item)}
>
<SettingsSectionIcon to={item.to} />
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-sidebar-foreground">
{item.title}
</span>
<span className="block truncate text-[11px] text-sidebar-muted-foreground/75">
{SETTINGS_SECTION_LABELS[item.to]}
</span>
</span>
</SidebarMenuButton>
</SidebarMenuItem>
))
: SETTINGS_NAV_ITEMS.map((item) => {
const Icon = item.icon;
const isActive = pathname === item.to;
return (
<SidebarMenuItem key={item.to}>
<SidebarMenuButton
isActive={isActive}
onClick={() => handleSectionClick(item.to)}
>
<Icon />
<span className="truncate">{item.label}</span>
</SidebarMenuButton>
</SidebarMenuItem>
);
})}
</SidebarMenu>
</SidebarGroup>
</SidebarContent>
@@ -55,6 +55,7 @@ import {
import { RedactedSensitiveText } from "./RedactedSensitiveText";
import { SourceControlWritingSettingsSection } from "./SourceControlWritingSettings";
import { SettingResetButton, SettingsPageContainer, SettingsSection } from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
versionControlSystems: [],
@@ -474,7 +475,7 @@ function EmptySourceControlDiscovery({
const hasError = error !== null;
return (
<SettingsSection title="Server environment">
<SettingsSection id={searchableSetting("source-control").id} title="Server environment">
<Empty className="min-h-88">
<EmptyMedia variant="icon">
<GitPullRequestIcon />
@@ -517,8 +518,8 @@ export function SourceControlSettingsPanel() {
}),
);
const result = discovery.data ?? EMPTY_DISCOVERY_RESULT;
const hasDiscoveryItems =
result.versionControlSystems.length > 0 || result.sourceControlProviders.length > 0;
const hasVersionControlSystems = result.versionControlSystems.length > 0;
const hasDiscoveryItems = hasVersionControlSystems || result.sourceControlProviders.length > 0;
const isInitialScanPending = discovery.isPending && discovery.data === null;
const handleScan = () => {
discovery.refresh();
@@ -552,8 +553,12 @@ export function SourceControlSettingsPanel() {
</>
) : hasDiscoveryItems ? (
<>
{result.versionControlSystems.length > 0 ? (
<SettingsSection title="Version Control" headerAction={scanButton}>
{hasVersionControlSystems ? (
<SettingsSection
id={searchableSetting("source-control").id}
title="Version Control"
headerAction={scanButton}
>
{result.versionControlSystems.map((item) => (
<DiscoveryItemRow key={`vcs:${item.kind}`} item={item}>
{item.kind === "git" ? <GitFetchIntervalSettings /> : undefined}
@@ -564,8 +569,9 @@ export function SourceControlSettingsPanel() {
{result.sourceControlProviders.length > 0 ? (
<SettingsSection
id={hasVersionControlSystems ? undefined : searchableSetting("source-control").id}
title="Source Control Providers"
headerAction={result.versionControlSystems.length === 0 ? scanButton : null}
headerAction={hasVersionControlSystems ? null : scanButton}
>
{result.sourceControlProviders.map((item) => (
<DiscoveryItemRow key={`provider:${item.kind}`} item={item} />
@@ -0,0 +1,100 @@
import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import {
scrollToSettingsTarget,
SettingsRow,
SettingsSearchTargetProvider,
} from "./settingsLayout";
afterEach(() => {
vi.unstubAllGlobals();
});
describe("settings search targets", () => {
it("does not persist destination styling in the rendered row", () => {
const markup = renderToStaticMarkup(
<SettingsSearchTargetProvider targetId="word-wrap">
<SettingsRow id="word-wrap" title="Word wrap" description="Wrap long lines." />
<SettingsRow id="time-format" title="Time format" description="Choose a clock." />
</SettingsSearchTargetProvider>,
);
expect(markup).toContain('id="word-wrap" tabindex="-1"');
expect(markup).not.toContain("data-settings-search-target");
expect(markup).not.toContain("settings-search-target-pulse");
});
it("scrolls directly to a section header and restarts the destination pulse", () => {
const sectionScrollIntoView = vi.fn();
const headerScrollIntoView = vi.fn();
const focus = vi.fn();
const remove = vi.fn();
const add = vi.fn();
const addEventListener = vi.fn();
const target = {
tagName: "SECTION",
firstElementChild: { scrollIntoView: headerScrollIntoView },
scrollIntoView: sectionScrollIntoView,
focus,
classList: { remove, add },
addEventListener,
offsetWidth: 100,
} as unknown as HTMLElement;
vi.stubGlobal("document", {
getElementById: vi.fn(() => target),
});
vi.stubGlobal("window", {
matchMedia: vi.fn(() => ({ matches: false })),
});
expect(scrollToSettingsTarget("providers")).toBe(true);
expect(headerScrollIntoView).toHaveBeenCalledWith({
behavior: "smooth",
block: "center",
});
expect(sectionScrollIntoView).not.toHaveBeenCalled();
expect(focus).toHaveBeenCalledWith({ preventScroll: true });
expect(remove).toHaveBeenCalledWith("settings-search-target-pulse");
expect(add).toHaveBeenCalledWith("settings-search-target-pulse");
expect(addEventListener).toHaveBeenCalledWith("blur", expect.any(Function), { once: true });
});
it("does not animate the destination when reduced motion is requested", () => {
const scrollIntoView = vi.fn();
const focus = vi.fn();
const remove = vi.fn();
const add = vi.fn();
const target = {
tagName: "DIV",
firstElementChild: null,
scrollIntoView,
focus,
classList: { remove, add },
offsetWidth: 100,
} as unknown as HTMLElement;
vi.stubGlobal("document", {
getElementById: vi.fn(() => target),
});
vi.stubGlobal("window", {
matchMedia: vi.fn(() => ({ matches: true })),
});
expect(scrollToSettingsTarget("word-wrap")).toBe(true);
expect(scrollIntoView).toHaveBeenCalledWith({
behavior: "auto",
block: "center",
});
expect(focus).toHaveBeenCalledWith({ preventScroll: true });
expect(remove).toHaveBeenCalledWith("settings-search-target-pulse");
expect(add).not.toHaveBeenCalled();
});
it("leaves not-yet-mounted destinations to their mount lifecycle", () => {
vi.stubGlobal("document", {
getElementById: vi.fn(() => null),
});
expect(scrollToSettingsTarget("archive")).toBe(false);
});
});
@@ -1,10 +1,83 @@
import { Undo2Icon } from "lucide-react";
import { type ComponentPropsWithoutRef, type ReactNode, useEffect, useState } from "react";
import { useLocation, useNavigate } from "@tanstack/react-router";
import {
createContext,
type ComponentPropsWithoutRef,
type ReactNode,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from "react";
import { cn } from "../../lib/utils";
import { Button } from "../ui/button";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
interface SettingsSearchTargetContextValue {
readonly targetId: string | null;
readonly onTargetHandled: () => void;
}
const noop = () => undefined;
const SettingsSearchTargetContext = createContext<SettingsSearchTargetContextValue>({
targetId: null,
onTargetHandled: noop,
});
export function SettingsSearchTargetProvider({
targetId,
onTargetHandled = noop,
children,
}: {
targetId: string | null;
onTargetHandled?: () => void;
children: ReactNode;
}) {
const value = useMemo(() => ({ targetId, onTargetHandled }), [onTargetHandled, targetId]);
return <SettingsSearchTargetContext value={value}>{children}</SettingsSearchTargetContext>;
}
function scrollAndFocusSettingsTarget(target: HTMLElement): void {
const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const scrollTarget =
target.tagName === "SECTION" && target.firstElementChild
? (target.firstElementChild as HTMLElement)
: target;
scrollTarget.scrollIntoView({
behavior: prefersReducedMotion ? "auto" : "smooth",
block: "center",
});
target.focus({ preventScroll: true });
target.classList.remove("settings-search-target-pulse");
if (prefersReducedMotion) return;
void target.offsetWidth;
target.classList.add("settings-search-target-pulse");
// The class also suppresses the focus outline (the pulse is the destination
// indicator), so drop it once the element is no longer the destination.
target.addEventListener("blur", () => target.classList.remove("settings-search-target-pulse"), {
once: true,
});
}
function useSettingsSearchTarget<T extends HTMLElement>(id: string | undefined) {
const { targetId, onTargetHandled } = useContext(SettingsSearchTargetContext);
const isSearchTarget = id !== undefined && id === targetId;
const targetRef = useCallback(
(target: T | null) => {
if (target && isSearchTarget) {
scrollAndFocusSettingsTarget(target);
onTargetHandled();
}
},
[isSearchTarget, onTargetHandled],
);
return targetRef;
}
/** Re-render every `intervalMs`; return a stable timestamp snapshot for render-time relative labels. */
export function useRelativeTimeTick(intervalMs = 1_000) {
const [nowMs, setNowMs] = useState(() => Date.now());
@@ -28,8 +101,15 @@ export function SettingsSection({
headerAction?: ReactNode;
children: ReactNode;
}) {
const targetRef = useSettingsSearchTarget<HTMLElement>(sectionProps.id);
return (
<section {...sectionProps} className={cn("space-y-3", className)}>
<section
{...sectionProps}
ref={targetRef}
tabIndex={sectionProps.id ? -1 : sectionProps.tabIndex}
className={cn("space-y-3", className)}
>
<div className="flex min-h-8 items-center justify-between gap-4 px-3 sm:px-4">
<h2 className="flex items-center gap-2 text-lg font-semibold tracking-[-0.025em] text-foreground">
{icon}
@@ -59,9 +139,13 @@ export function SettingsRow({
control?: ReactNode;
children?: ReactNode;
}) {
const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);
return (
<div
{...rowProps}
ref={targetRef}
tabIndex={rowProps.id ? -1 : rowProps.tabIndex}
className={cn("rounded-xl px-3 sm:px-4", children ? "pt-3 pb-1" : "py-3", className)}
>
<div className="flex flex-col gap-3 sm:grid sm:grid-cols-[minmax(0,1fr)_minmax(10rem,auto)] sm:items-center sm:gap-8">
@@ -119,11 +203,27 @@ export function SettingsPageContainer({
children: ReactNode;
className?: string;
}) {
const navigate = useNavigate();
const hash = useLocation({ select: (location) => location.hash });
const targetId = hash.replace(/^#/, "") || null;
const clearTargetHash = useCallback(() => {
void navigate({ hash: "", replace: true, resetScroll: false, hashScrollIntoView: false });
}, [navigate]);
return (
<div className="settings-page-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto px-4 pt-10 pb-7 sm:px-8 sm:pt-12 sm:pb-10">
<div className={cn("mx-auto flex w-full max-w-4xl flex-col gap-12", className)}>
{children}
<SettingsSearchTargetProvider targetId={targetId} onTargetHandled={clearTargetHash}>
<div className="settings-page-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto px-4 pt-10 pb-7 sm:px-8 sm:pt-12 sm:pb-10">
<div className={cn("mx-auto flex w-full max-w-4xl flex-col gap-12", className)}>
{children}
</div>
</div>
</div>
</SettingsSearchTargetProvider>
);
}
export function scrollToSettingsTarget(targetId: string): boolean {
const target = document.getElementById(targetId);
if (!target) return false;
scrollAndFocusSettingsTarget(target);
return true;
}
@@ -0,0 +1,87 @@
import { describe, expect, it } from "vite-plus/test";
import {
searchableSetting,
searchSettings,
SETTINGS_SEARCH_ITEMS,
type SettingsSearchItem,
} from "./settingsSearch";
const ITEMS: ReadonlyArray<SettingsSearchItem> = [
{
id: "word-wrap",
title: "Word wrap",
to: "/settings/general",
},
{
id: "network-access",
title: "Network access",
to: "/settings/connections",
},
{
id: "providers",
title: "Providers",
to: "/settings/providers",
},
{
id: "provider-updates",
title: "Update checks",
to: "/settings/general",
},
{
id: "automatic-updates",
title: "Automatic updates",
to: "/settings/general",
},
];
describe("searchSettings", () => {
it("matches only setting titles", () => {
expect(searchSettings("word", ITEMS).map((item) => item.id)).toEqual(["word-wrap"]);
expect(searchSettings("network", ITEMS).map((item) => item.id)).toEqual(["network-access"]);
expect(searchSettings("connections", ITEMS)).toEqual([]);
expect(searchSettings("claude", ITEMS)).toEqual([]);
});
it("matches normalized title substrings", () => {
expect(searchSettings(" WORD WRAP ", ITEMS).map((item) => item.id)).toEqual(["word-wrap"]);
expect(searchSettings("work")).toEqual([]);
});
it("keeps catalog order for multiple title matches", () => {
expect(searchSettings("update", ITEMS).map((item) => item.id)).toEqual([
"provider-updates",
"automatic-updates",
]);
});
it("returns no results for an empty query", () => {
expect(searchSettings(" ", ITEMS)).toEqual([]);
});
it("keeps catalog result ids unique", () => {
const ids = SETTINGS_SEARCH_ITEMS.map((item) => item.id);
expect(new Set(ids).size).toBe(ids.length);
});
it("serves anchor props to panels from the catalog", () => {
expect(searchableSetting("word-wrap")).toEqual({ id: "word-wrap", title: "Word wrap" });
expect(searchableSetting("archive")).toEqual({ id: "archive", title: "Archived threads" });
});
it("routes appearance settings to their current section", () => {
expect(searchSettings("theme")[0]).toMatchObject({
id: "theme",
to: "/settings/appearance",
});
expect(searchSettings("word wrap")[0]).toMatchObject({
id: "word-wrap",
to: "/settings/appearance",
});
expect(searchSettings("environment identification")[0]).toMatchObject({
id: "environment-identification",
to: "/settings/appearance",
targetId: "appearance",
});
});
});
@@ -0,0 +1,203 @@
export type SettingsPath =
| "/settings/general"
| "/settings/appearance"
| "/settings/keybindings"
| "/settings/providers"
| "/settings/source-control"
| "/settings/connections"
| "/settings/beta"
| "/settings/archived";
export interface SettingsSearchItem {
readonly id: string;
readonly title: string;
readonly to: SettingsPath;
readonly targetId?: string;
}
/**
* Section labels in sidebar order. The sidebar nav and the search-result
* subtitles both render from this record, so each label exists once.
*/
export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
"/settings/general": "General",
"/settings/appearance": "Appearance",
"/settings/keybindings": "Keybindings",
"/settings/providers": "Providers",
"/settings/source-control": "Source Control",
"/settings/connections": "Connections",
"/settings/beta": "Beta",
"/settings/archived": "Archive",
};
/**
* Every searchable setting, in result order. This catalog is the single
* source of truth for anchor ids and visible titles: panels render both via
* `searchableSetting`, so a retitle (or, later, a translation pass) happens
* here once instead of separately in the panel and the index.
*/
export const SETTINGS_SEARCH_ITEMS = [
{
id: "theme",
title: "Theme",
to: "/settings/appearance",
},
{
// Prefixed because the slider control already owns the `glass-opacity` id.
id: "setting-glass-opacity",
title: "Glass opacity",
to: "/settings/appearance",
},
{
id: "environment-identification",
title: "Environment identification",
to: "/settings/appearance",
// The setting is stage-dependent, so its parent section is the stable destination.
targetId: "appearance",
},
{
id: "word-wrap",
title: "Word wrap",
to: "/settings/appearance",
},
{
id: "project-grouping",
title: "Project grouping",
to: "/settings/general",
},
{
id: "time-format",
title: "Time format",
to: "/settings/general",
},
{
id: "hide-whitespace-changes",
title: "Hide whitespace changes",
to: "/settings/general",
},
{
id: "assistant-output",
title: "Assistant output",
to: "/settings/general",
},
{
id: "provider-update-checks",
title: "Provider update checks",
to: "/settings/general",
},
{
id: "auto-open-task-panel",
title: "Auto-open task panel",
to: "/settings/general",
},
{
id: "new-threads",
title: "New threads",
to: "/settings/general",
},
{
id: "start-from-origin",
title: "Start from origin",
to: "/settings/general",
targetId: "new-threads",
},
{
id: "add-project-starts-in",
title: "Add project starts in",
to: "/settings/general",
},
{
id: "archive-confirmation",
title: "Archive confirmation",
to: "/settings/general",
},
{
id: "delete-confirmation",
title: "Delete confirmation",
to: "/settings/general",
},
{
id: "text-generation-model",
title: "Text generation model",
to: "/settings/general",
},
{
id: "diagnostics",
title: "Diagnostics",
to: "/settings/general",
},
{
id: "keybindings",
title: "Keybindings",
to: "/settings/keybindings",
},
{
id: "providers",
title: "Providers",
to: "/settings/providers",
},
{
id: "source-control",
title: "Source control",
to: "/settings/source-control",
},
{
id: "remote-environments",
title: "Remote environments",
to: "/settings/connections",
},
{
id: "sidebar-v2",
title: "Sidebar v2",
to: "/settings/beta",
},
{
id: "auto-settle-inactive-threads",
title: "Auto-settle inactive threads",
to: "/settings/beta",
targetId: "sidebar-v2",
},
{
id: "archive",
title: "Archived threads",
to: "/settings/archived",
},
] as const satisfies ReadonlyArray<SettingsSearchItem>;
export type SettingsSearchItemId = (typeof SETTINGS_SEARCH_ITEMS)[number]["id"];
const SEARCH_ITEMS_BY_ID = Object.fromEntries(
SETTINGS_SEARCH_ITEMS.map((item) => [item.id, item]),
) as Readonly<Record<SettingsSearchItemId, SettingsSearchItem>>;
/**
* `id` and `title` props for the element a search item anchors to. Panels
* spread (or pick from) this instead of restating the strings, so the catalog
* and the rendered settings cannot drift apart.
*/
export function searchableSetting(id: SettingsSearchItemId): {
readonly id: string;
readonly title: string;
} {
const { id: anchorId, title } = SEARCH_ITEMS_BY_ID[id];
return { id: anchorId, title };
}
function normalizeSearchText(value: string): string {
return value
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.toLocaleLowerCase()
.replace(/\s+/g, " ")
.trim();
}
export function searchSettings(
query: string,
items: ReadonlyArray<SettingsSearchItem> = SETTINGS_SEARCH_ITEMS,
): ReadonlyArray<SettingsSearchItem> {
const normalizedQuery = normalizeSearchText(query);
if (normalizedQuery.length === 0) return [];
return items.filter((item) => normalizeSearchText(item.title).includes(normalizedQuery));
}
+22
View File
@@ -370,6 +370,28 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
var(--app-scrollbar-width) 100%;
}
@keyframes settings-search-target-pulse {
0%,
100% {
box-shadow: 0 0 0 0 transparent;
}
50% {
box-shadow: 0 0 0 2px color-mix(in oklab, var(--color-primary) 70%, transparent);
}
}
.settings-page-scroll-fade div.settings-search-target-pulse,
.settings-page-scroll-fade section.settings-search-target-pulse > div:first-child {
animation: settings-search-target-pulse 650ms ease-in-out 2;
border-radius: 0.75rem;
}
/* The pulse is the destination indicator; without it (reduced motion), the
focus outline takes over, so exactly one indicator shows at a time. */
.settings-page-scroll-fade .settings-search-target-pulse:focus {
outline: none;
}
.workspace-titlebar-controls {
position: absolute;
top: var(--workspace-controls-top);