TypeScript
fix(web): stop the settings sidebar shifting when switching pages (#10705)
Theo Browned6dbe8dd67fa
diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsxindex e1993eb6125..75624792c5d 100644--- a/apps/web/src/components/settings/SettingsSidebarNav.tsx+++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx@@ -8,7 +8,6 @@ import {useState,type ComponentType,type KeyboardEvent,- type ReactNode,} from "react";import {ArchiveIcon,@@ -24,13 +23,11 @@ import {Settings2Icon,XIcon,} from "lucide-react";-import { useLocation, useNavigate, useRouterState } from "@tanstack/react-router";+import { useLocation, useNavigate } from "@tanstack/react-router";import { Button } from "../ui/button";-import { Collapsible, CollapsiblePanel } from "../ui/collapsible";import { Input } from "../ui/input";import { Kbd } from "../ui/kbd";-import { cn } from "../../lib/utils";import {SidebarContent,SidebarFooter,@@ -38,18 +35,10 @@ import {SidebarMenu,SidebarMenuButton,SidebarMenuItem,- SidebarMenuSub,- SidebarMenuSubButton,- SidebarMenuSubItem,useSidebar,} from "../ui/sidebar";import { SidebarUtilityMenu } from "../sidebar/SidebarChrome";import { scrollToSettingsTarget } from "./settingsLayout";-import {- getVisibleSettingsSectionIds,- observeSettingsSectionVisibility,- type SettingsSectionVisibilityState,-} from "./settingsSectionVisibility";import {searchSettings,SETTINGS_SECTION_LABELS,@@ -106,102 +95,22 @@ const SETTINGS_NAV_ITEMS: ReadonlyArray<{icon: SETTINGS_SECTION_ICONS[to],}));-const SETTINGS_PAGE_SECTIONS: Partial<- Readonly<Record<SettingsPath, ReadonlyArray<{ label: string; targetId: string }>>>-> = {- "/settings/general": [- { label: "Organization", targetId: "organization" },- { label: "Behavior", targetId: "behavior" },- { label: "Projects & threads", targetId: "projects-and-threads" },- { label: "Confirmations", targetId: "confirmations" },- { label: "Text generation", targetId: "text-generation" },- { label: "About", targetId: "about" },- { label: "Legacy features", targetId: "legacy-features" },- ],- "/settings/appearance": [- { label: "Colors & themes", targetId: "appearance" },- { label: "Interface", targetId: "appearance-interface" },- { label: "Motion", targetId: "motion" },- { label: "Typography", targetId: "typography" },- ],- "/settings/source-control": [- { label: "Version control", targetId: "source-control" },- { label: "Text generation", targetId: "source-control-text-generation" },- ],- "/settings/connections": [- { label: "This environment", targetId: "connections-environment" },- { label: "Remote environments", targetId: "remote-environments" },- ],-};-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" />;}-function SettingsSubmenuCollapse({- open,- children,-}: {- readonly open: boolean;- readonly children: ReactNode;-}) {- return (- <Collapsible open={open}>- <CollapsiblePanel className="duration-150 ease-out motion-reduce:transition-none">- {children}- </CollapsiblePanel>- </Collapsible>- );-}-export function SettingsSidebarNav({ pathname }: { pathname: string }) {const navigate = useNavigate();const currentHash = useLocation({ select: (location) => location.hash });- const resolvedPathname = useRouterState({- select: (state) => state.resolvedLocation?.pathname,- });const { isMobile, setOpenMobile, open, setOpen } = useSidebar();const searchInputRef = useRef<HTMLInputElement>(null);const [query, setQuery] = useState("");const [activeResultIndex, setActiveResultIndex] = useState(0);- const [sectionVisibility, setSectionVisibility] = useState<SettingsSectionVisibilityState | null>(- null,- );const searchableItems = useAvailableSettingsSearchItems();const results = useMemo(() => searchSettings(query, searchableItems), [query, searchableItems]);const isSearching = query.trim().length > 0;const hasResults = results.length > 0;- const activeSettingsPath = SETTINGS_NAV_ITEMS.find(- (item) => pathname === item.to || pathname.startsWith(`${item.to}/`),- )?.to;- const observedVisibilityScope = useMemo(() => {- const path = SETTINGS_NAV_ITEMS.find(- (item) =>- resolvedPathname === item.to || resolvedPathname?.startsWith(`${item.to}/`) === true,- )?.to;- const pageSections = path ? SETTINGS_PAGE_SECTIONS[path] : undefined;- return path && pageSections ? { path, pageSections } : null;- }, [resolvedPathname]);- const visiblePageSectionIds = getVisibleSettingsSectionIds({- activePath: activeSettingsPath,- scope: observedVisibilityScope,- visibility: sectionVisibility,- });-- useEffect(() => {- if (!observedVisibilityScope) return;- const container = document.querySelector<HTMLElement>("[data-settings-page-layout]");- if (!container) return;-- return observeSettingsSectionVisibility({- container,- targetIds: observedVisibilityScope.pageSections.map((section) => section.targetId),- onChange(targetIds) {- setSectionVisibility({ scope: observedVisibilityScope, targetIds: new Set(targetIds) });- },- });- }, [observedVisibilityScope]);useEffect(() => {setActiveResultIndex((index) => Math.min(index, Math.max(results.length - 1, 0)));@@ -261,24 +170,6 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {},[isMobile, navigate, setOpenMobile],);- const handlePageSectionClick = useCallback(- (to: SettingsPath, targetId: string) => {- if (isMobile) {- setOpenMobile(false);- }- if (pathname === to && scrollToSettingsTarget(targetId, { highlight: false })) {- return;- }- void navigate({- to,- hash: targetId,- replace: true,- hashScrollIntoView: false,- state: { settingsTargetHighlight: false },- });- },- [isMobile, navigate, pathname, setOpenMobile],- );const clearSearch = useCallback(() => {setQuery("");setActiveResultIndex(0);@@ -430,8 +321,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {<SidebarMenu className="ps-px">{SETTINGS_NAV_ITEMS.map((item) => {const Icon = item.icon;- const pageSections = SETTINGS_PAGE_SECTIONS[item.to];- const isActive = activeSettingsPath === item.to;+ const isActive = pathname === item.to || pathname.startsWith(`${item.to}/`);return (<SidebarMenuItem key={item.to}><SidebarMenuButton@@ -441,29 +331,6 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {<Icon /><span className="truncate">{item.label}</span></SidebarMenuButton>- {pageSections ? (- <SettingsSubmenuCollapse open={isActive}>- <SidebarMenuSub className="border-l-0">- {pageSections.map((section) => (- <SidebarMenuSubItem key={section.targetId}>- <SidebarMenuSubButton- render={<button type="button" />}- size="sm"- data-visible={visiblePageSectionIds.has(section.targetId)}- className={cn(- "w-full text-sidebar-muted-foreground/65",- visiblePageSectionIds.has(section.targetId) &&- "font-medium text-sidebar-foreground",- )}- onClick={() => handlePageSectionClick(item.to, section.targetId)}- >- <span className="ms-0.5">{section.label}</span>- </SidebarMenuSubButton>- </SidebarMenuSubItem>- ))}- </SidebarMenuSub>- </SettingsSubmenuCollapse>- ) : null}</SidebarMenuItem>);})}diff --git a/apps/web/src/components/settings/settingsSectionVisibility.test.ts b/apps/web/src/components/settings/settingsSectionVisibility.test.tsdeleted file mode 100644index 90656ad7073..00000000000--- a/apps/web/src/components/settings/settingsSectionVisibility.test.ts+++ /dev/null@@ -1,245 +0,0 @@-import { describe, expect, it, vi } from "vite-plus/test";--import {- getVisibleSettingsSectionIds,- observeSettingsSectionVisibility,- type SettingsSectionVisibilityEnvironment,-} from "./settingsSectionVisibility";--type VisibilityEntry = Pick<- IntersectionObserverEntry,- "intersectionRatio" | "isIntersecting" | "target"->;--function createHarness(- targetIds: ReadonlyArray<string>,- initialRoot: Element | null = { name: "initial-root" } as unknown as Element,-) {- const targets = new Map(- targetIds.map((targetId) => [targetId, { targetId } as unknown as Element]),- );- const observed = new Set<Element>();- const unobserve = vi.fn((target: Element) => observed.delete(target));- const disconnectIntersections = vi.fn();- const disconnectMutations = vi.fn();- const intersectionCallbacks: Array<(entries: ReadonlyArray<VisibilityEntry>) => void> = [];- const intersectionRoots: Element[] = [];- let root = initialRoot;- let onMutation = () => {};-- const environment: SettingsSectionVisibilityEnvironment = {- findRoot: () => root,- findTarget: (_root, targetId) => targets.get(targetId) ?? null,- createIntersectionObserver(callback, observedRoot) {- intersectionCallbacks.push(callback);- intersectionRoots.push(observedRoot);- return {- observe: (target) => observed.add(target),- unobserve,- disconnect: disconnectIntersections,- };- },- createMutationObserver(callback) {- onMutation = callback;- return { disconnect: disconnectMutations };- },- };-- return {- environment,- targets,- observed,- unobserve,- disconnectIntersections,- disconnectMutations,- intersectionCallbacks,- intersectionRoots,- intersect(entries: ReadonlyArray<VisibilityEntry>) {- intersectionCallbacks.at(-1)?.(entries);- },- mutate() {- onMutation();- },- replaceRoot(nextRoot: Element | null) {- root = nextRoot;- onMutation();- },- };-}--function visibleEntry(- target: Element,- { isIntersecting = true, intersectionRatio = 1 } = {},-): VisibilityEntry {- return { target, isIntersecting, intersectionRatio };-}--describe("settings section visibility", () => {- it("does not reuse visibility when returning to the same sectioned route", () => {- const firstGeneralVisit = { path: "/settings/general" };- const firstVisibility = {- scope: firstGeneralVisit,- targetIds: new Set(["text-generation"]),- };-- expect(- getVisibleSettingsSectionIds({- activePath: "/settings/general",- scope: firstGeneralVisit,- visibility: firstVisibility,- }),- ).toEqual(new Set(["text-generation"]));- expect(- getVisibleSettingsSectionIds({- activePath: "/settings/providers",- scope: null,- visibility: firstVisibility,- }),- ).toEqual(new Set());-- const secondGeneralVisit = { path: "/settings/general" };- expect(- getVisibleSettingsSectionIds({- activePath: "/settings/general",- scope: secondGeneralVisit,- visibility: firstVisibility,- }),- ).toEqual(new Set());- });-- it("accumulates visible sections and emits them in sidebar order", () => {- const harness = createHarness(["one", "two", "three"]);- const emissions: ReadonlyArray<string>[] = [];- observeSettingsSectionVisibility({- container: {} as Element,- targetIds: ["one", "two", "three"],- onChange: (visible) => emissions.push(visible),- environment: harness.environment,- });-- harness.intersect([visibleEntry(harness.targets.get("two")!)]);- harness.intersect([visibleEntry(harness.targets.get("one")!)]);-- expect(emissions).toEqual([[], ["two"], ["one", "two"]]);- });-- it("treats zero-ratio and non-intersecting entries as hidden", () => {- const harness = createHarness(["one", "two"]);- const emissions: ReadonlyArray<string>[] = [];- observeSettingsSectionVisibility({- container: {} as Element,- targetIds: ["one", "two"],- onChange: (visible) => emissions.push(visible),- environment: harness.environment,- });-- const one = harness.targets.get("one")!;- const two = harness.targets.get("two")!;- harness.intersect([visibleEntry(one), visibleEntry(two)]);- harness.intersect([visibleEntry(one, { intersectionRatio: 0 })]);- harness.intersect([visibleEntry(two, { isIntersecting: false })]);-- expect(emissions).toEqual([[], ["one", "two"], ["two"], []]);- });-- it("resyncs replaced and removed targets without retaining stale visibility", () => {- const harness = createHarness(["dynamic"]);- const emissions: ReadonlyArray<string>[] = [];- observeSettingsSectionVisibility({- container: {} as Element,- targetIds: ["dynamic"],- onChange: (visible) => emissions.push(visible),- environment: harness.environment,- });-- const firstTarget = harness.targets.get("dynamic")!;- harness.intersect([visibleEntry(firstTarget)]);- const replacementTarget = { targetId: "dynamic-replacement" } as unknown as Element;- harness.targets.set("dynamic", replacementTarget);- harness.mutate();-- expect(harness.unobserve).toHaveBeenCalledWith(firstTarget);- expect(harness.observed.has(replacementTarget)).toBe(true);- expect(emissions.at(-1)).toEqual([]);-- harness.intersect([visibleEntry(firstTarget)]);- expect(emissions.at(-1)).toEqual([]);- harness.intersect([visibleEntry(replacementTarget)]);- expect(emissions.at(-1)).toEqual(["dynamic"]);-- harness.targets.delete("dynamic");- harness.mutate();- expect(harness.unobserve).toHaveBeenCalledWith(replacementTarget);- expect(emissions.at(-1)).toEqual([]);- });-- it("rebinds when navigation replaces the settings scroll root", () => {- const harness = createHarness(["section"]);- const emissions: ReadonlyArray<string>[] = [];- observeSettingsSectionVisibility({- container: {} as Element,- targetIds: ["section"],- onChange: (visible) => emissions.push(visible),- environment: harness.environment,- });-- const firstTarget = harness.targets.get("section")!;- harness.intersect([visibleEntry(firstTarget)]);- const firstObserverCallback = harness.intersectionCallbacks[0]!;- const nextRoot = { name: "next-root" } as unknown as Element;- const nextTarget = { targetId: "next-section" } as unknown as Element;- harness.targets.set("section", nextTarget);- harness.replaceRoot(nextRoot);-- expect(harness.disconnectIntersections).toHaveBeenCalledOnce();- expect(harness.intersectionRoots.at(-1)).toBe(nextRoot);- expect(harness.observed.has(nextTarget)).toBe(true);- expect(emissions.at(-1)).toEqual([]);-- firstObserverCallback([visibleEntry(firstTarget)]);- expect(emissions.at(-1)).toEqual([]);- harness.intersect([visibleEntry(nextTarget)]);- expect(emissions.at(-1)).toEqual(["section"]);- });-- it("starts observing when the settings scroll root mounts later", () => {- const harness = createHarness(["section"], null);- const emissions: ReadonlyArray<string>[] = [];- observeSettingsSectionVisibility({- container: {} as Element,- targetIds: ["section"],- onChange: (visible) => emissions.push(visible),- environment: harness.environment,- });-- expect(emissions).toEqual([[]]);- expect(harness.intersectionRoots).toEqual([]);-- const root = { name: "mounted-root" } as unknown as Element;- harness.replaceRoot(root);- harness.intersect([visibleEntry(harness.targets.get("section")!)]);-- expect(harness.intersectionRoots).toEqual([root]);- expect(emissions.at(-1)).toEqual(["section"]);- });-- it("disconnects both observers and ignores callbacks after cleanup", () => {- const harness = createHarness(["one"]);- const onChange = vi.fn();- const cleanup = observeSettingsSectionVisibility({- container: {} as Element,- targetIds: ["one"],- onChange,- environment: harness.environment,- });-- cleanup();- harness.intersect([visibleEntry(harness.targets.get("one")!)]);- harness.mutate();-- expect(harness.disconnectIntersections).toHaveBeenCalledOnce();- expect(harness.disconnectMutations).toHaveBeenCalledOnce();- expect(onChange).toHaveBeenCalledTimes(1);- expect(onChange).toHaveBeenLastCalledWith([]);- });-});diff --git a/apps/web/src/components/settings/settingsSectionVisibility.ts b/apps/web/src/components/settings/settingsSectionVisibility.tsdeleted file mode 100644index 76b1fc94325..00000000000--- a/apps/web/src/components/settings/settingsSectionVisibility.ts+++ /dev/null@@ -1,186 +0,0 @@-type VisibilityEntry = Pick<- IntersectionObserverEntry,- "intersectionRatio" | "isIntersecting" | "target"->;--export type SettingsSectionVisibilityScope = {- readonly path: string;-};--export type SettingsSectionVisibilityState = {- readonly scope: SettingsSectionVisibilityScope;- readonly targetIds: ReadonlySet<string>;-};--const EMPTY_VISIBLE_SETTINGS_SECTION_IDS: ReadonlySet<string> = new Set();--export function getVisibleSettingsSectionIds({- activePath,- scope,- visibility,-}: {- readonly activePath: string | undefined;- readonly scope: SettingsSectionVisibilityScope | null;- readonly visibility: SettingsSectionVisibilityState | null;-}): ReadonlySet<string> {- if (!scope || activePath !== scope.path || visibility?.scope !== scope) {- return EMPTY_VISIBLE_SETTINGS_SECTION_IDS;- }- return visibility.targetIds;-}--type ElementObserver = {- observe(target: Element): void;- unobserve(target: Element): void;- disconnect(): void;-};--type MutationSubscription = {- disconnect(): void;-};--export type SettingsSectionVisibilityEnvironment = {- findRoot(container: Element): Element | null;- findTarget(root: Element, targetId: string): Element | null;- createIntersectionObserver(- onEntries: (entries: ReadonlyArray<VisibilityEntry>) => void,- root: Element,- ): ElementObserver;- createMutationObserver(onMutation: () => void, container: Element): MutationSubscription;-};--function createBrowserEnvironment(): SettingsSectionVisibilityEnvironment {- return {- findRoot(container) {- return container.querySelector("[data-settings-page-scroll]");- },- findTarget(root, targetId) {- const target = root.ownerDocument.getElementById(targetId);- return target && root.contains(target) ? target : null;- },- createIntersectionObserver(onEntries, scrollRoot) {- const observer = new IntersectionObserver(onEntries, {- root: scrollRoot,- threshold: 0,- });- return observer;- },- createMutationObserver(onMutation, container) {- const observer = new MutationObserver(onMutation);- observer.observe(container, { childList: true, subtree: true });- return observer;- },- };-}--export function observeSettingsSectionVisibility({- container,- targetIds,- onChange,- environment = createBrowserEnvironment(),-}: {- readonly container: Element;- readonly targetIds: ReadonlyArray<string>;- readonly onChange: (visibleTargetIds: ReadonlyArray<string>) => void;- readonly environment?: SettingsSectionVisibilityEnvironment;-}): () => void {- const orderedTargetIds = [...new Set(targetIds)];- const targetsById = new Map<string, Element>();- const targetIdsByElement = new Map<Element, string>();- const visibleTargetIds = new Set<string>();- let lastEmission: string | null = null;- let stopped = false;- let root: Element | null = null;- let intersectionObserver: ElementObserver | null = null;- let observerGeneration = 0;-- const emit = () => {- const visibleInOrder = orderedTargetIds.filter((targetId) => visibleTargetIds.has(targetId));- const emissionKey = visibleInOrder.join("\0");- if (emissionKey === lastEmission) return;- lastEmission = emissionKey;- onChange(visibleInOrder);- };-- const handleEntries = (entries: ReadonlyArray<VisibilityEntry>, generation: number) => {- if (stopped || generation !== observerGeneration) return;- let changed = false;- for (const entry of entries) {- const targetId = targetIdsByElement.get(entry.target);- if (!targetId || targetsById.get(targetId) !== entry.target) continue;- const visible = entry.isIntersecting && entry.intersectionRatio > 0;- if (visible === visibleTargetIds.has(targetId)) continue;- changed = true;- if (visible) {- visibleTargetIds.add(targetId);- } else {- visibleTargetIds.delete(targetId);- }- }- if (changed) emit();- };-- const syncTargets = () => {- if (stopped) return;- let changed = false;- const nextRoot = environment.findRoot(container);-- if (nextRoot !== root) {- observerGeneration += 1;- intersectionObserver?.disconnect();- intersectionObserver = null;- root = nextRoot;- targetsById.clear();- targetIdsByElement.clear();- changed = visibleTargetIds.size > 0;- visibleTargetIds.clear();-- if (root) {- const generation = observerGeneration;- intersectionObserver = environment.createIntersectionObserver(- (entries) => handleEntries(entries, generation),- root,- );- }- }-- if (!root || !intersectionObserver) {- if (changed) emit();- return;- }-- for (const targetId of orderedTargetIds) {- const previousTarget = targetsById.get(targetId) ?? null;- const nextTarget = environment.findTarget(root, targetId);- if (previousTarget === nextTarget) continue;-- if (previousTarget) {- intersectionObserver.unobserve(previousTarget);- targetsById.delete(targetId);- targetIdsByElement.delete(previousTarget);- changed = visibleTargetIds.delete(targetId) || changed;- }- if (nextTarget) {- targetsById.set(targetId, nextTarget);- targetIdsByElement.set(nextTarget, targetId);- intersectionObserver.observe(nextTarget);- }- }-- if (changed) emit();- };-- const mutationObserver = environment.createMutationObserver(syncTargets, container);- syncTargets();- emit();-- return () => {- stopped = true;- observerGeneration += 1;- intersectionObserver?.disconnect();- mutationObserver.disconnect();- targetsById.clear();- targetIdsByElement.clear();- visibleTargetIds.clear();- };-}diff --git a/apps/web/src/routes/settings.tsx b/apps/web/src/routes/settings.tsxindex 696ad200f3b..5e921fca5c2 100644--- a/apps/web/src/routes/settings.tsx+++ b/apps/web/src/routes/settings.tsx@@ -69,10 +69,7 @@ function SettingsContentLayout() {}, [navigateBackWithinApp]);return (- <SidebarInset- className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate"- data-settings-page-layout- >+ <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate"><div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground"><WorkspacePageHeader electron={isElectron}><div className="flex w-full items-center gap-3">