TypeScript
fix(web): make Changes and PR Code file lists resizable (#28244)
Lukas9ff0fac0f489
diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsxindex 7785c025e0f..0f1d1e9e283 100644--- a/apps/web/src/components/DiffPanel.tsx+++ b/apps/web/src/components/DiffPanel.tsx@@ -67,6 +67,7 @@ import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./Difimport { DiffStatLabel } from "./chat/DiffStatLabel";import { AnnotatableCodeView } from "./diffs/AnnotatableCodeView";import { DiffFileTree } from "./diffs/DiffFileTree";+import { FileExplorerPane } from "./files/FileExplorerPane";import { diffFileTreeEntries } from "./diffs/diffFileTree.logic";import { Button } from "./ui/button";import { MorphIcon } from "~/components/MorphIcon";@@ -1451,7 +1452,12 @@ export default function DiffPanel({/></div>{fileTreeOpen ? (- <aside className="flex w-[min(16rem,40%)] min-w-40 shrink-0 border-l border-border/60">+ <FileExplorerPane+ resizable+ storageKey="t3code:diff-file-tree-width"+ defaultWidthFraction={0.4}+ resizeLabel="Resize Changes files"+ ><DiffFileTreeariaLabel={`${reviewSectionTitle} files`}entries={fileTreeEntries}@@ -1459,7 +1465,7 @@ export default function DiffPanel({revealRequestId={selectedFileRevealRequestId}onSelectFile={revealDiffFile}/>- </aside>+ </FileExplorerPane>) : null}</div>) : (diff --git a/apps/web/src/components/files/FileExplorerPane.browser.test.tsx b/apps/web/src/components/files/FileExplorerPane.browser.test.tsxnew file mode 100644index 00000000000..58f1064beed--- /dev/null+++ b/apps/web/src/components/files/FileExplorerPane.browser.test.tsx@@ -0,0 +1,45 @@+import { describe, expect, it } from "vite-plus/test";++import { render } from "../../../test/render";+import { FileExplorerPane } from "./FileExplorerPane";++const STORAGE_KEY = "test:file-explorer-default";++describe("FileExplorerPane", () => {+ it.each([+ { view: "Changes", defaultWidth: 256, defaultWidthFraction: 0.4, minWidth: 160, expected: 168 },+ { view: "PR Code", defaultWidth: 320, defaultWidthFraction: 0.4, minWidth: 192, expected: 192 },+ {+ view: "Files",+ defaultWidth: 256,+ minWidth: 160,+ expected: 164,+ },+ ])(+ "preserves the $view initial width in a 420px row",+ async ({ expected, view: _, ...sizing }) => {+ const previous = localStorage.getItem(STORAGE_KEY);+ localStorage.removeItem(STORAGE_KEY);+ try {+ // This layout has no navigation or links.+ await using screen = await render(+ <div style={{ display: "flex", width: 420 }}>+ <FileExplorerPane resizable storageKey={STORAGE_KEY} {...sizing}>+ File tree+ </FileExplorerPane>+ </div>,+ { router: false },+ );+ await expect+ .element(screen.getByRole("separator"))+ .toHaveAttribute("aria-valuenow", String(expected));+ expect(screen.container.querySelector("aside")!.getBoundingClientRect().width).toBe(+ expected,+ );+ } finally {+ if (previous === null) localStorage.removeItem(STORAGE_KEY);+ else localStorage.setItem(STORAGE_KEY, previous);+ }+ },+ );+});diff --git a/apps/web/src/components/files/FileExplorerPane.tsx b/apps/web/src/components/files/FileExplorerPane.tsxindex c13a814f630..f88a9fdc8bb 100644--- a/apps/web/src/components/files/FileExplorerPane.tsx+++ b/apps/web/src/components/files/FileExplorerPane.tsx@@ -9,18 +9,33 @@ const MIN_WIDTH = 160;const MAX_WIDTH = 560;const FILE_CONTENT_MIN_WIDTH = 256;+/** A persisted, resizable file-tree column; fills the row when resizing is disabled.+ * Callers can retain a responsive initial width via defaultWidthFraction (a fraction of the row),+ * and use a separate saved width, minimum and resize label. A chosen width overrides the default.+ */export function FileExplorerPane({resizable,children,+ storageKey = "t3code.fileExplorerWidth",+ defaultWidth = 256,+ defaultWidthFraction,+ minWidth = MIN_WIDTH,+ resizeLabel = "Resize file explorer",}: {resizable: boolean;children: ReactNode;+ storageKey?: string;+ defaultWidth?: number;+ defaultWidthFraction?: number;+ minWidth?: number;+ resizeLabel?: string;}) {const [maxWidth, setMaxWidth] = useState(MAX_WIDTH);+ const [responsiveDefaultWidth, setResponsiveDefaultWidth] = useState(defaultWidth);const { width, setWidth, handlers } = useResizableWidth({- storageKey: "t3code.fileExplorerWidth",- defaultWidth: 256,- minWidth: MIN_WIDTH,+ storageKey,+ defaultWidth: responsiveDefaultWidth,+ minWidth,maxWidth,edge: "left",});@@ -30,10 +45,19 @@ export function FileExplorerPane({ref={(host) => {const row = host?.parentElement;if (!row || !resizable) return;- const measure = () =>- setMaxWidth(- Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, row.clientWidth - FILE_CONTENT_MIN_WIDTH)),+ const measure = () => {+ const initialWidth = Math.max(+ minWidth,+ Math.min(defaultWidth, row.clientWidth * (defaultWidthFraction ?? 1)),);+ // A responsive default must not shrink to make room for the content reserve.+ const availableWidth = Math.max(+ row.clientWidth - FILE_CONTENT_MIN_WIDTH,+ defaultWidthFraction === undefined ? minWidth : initialWidth,+ );+ setMaxWidth(Math.max(minWidth, Math.min(MAX_WIDTH, availableWidth)));+ setResponsiveDefaultWidth(initialWidth);+ };measure();return observeResize(row, measure);}}@@ -54,10 +78,10 @@ export function FileExplorerPane({{resizable ? (<RightPanelResizeHandlehandlers={handlers}- label="Resize file explorer"+ label={resizeLabel}tabIndex={0}aria-valuenow={width}- aria-valuemin={MIN_WIDTH}+ aria-valuemin={minWidth}aria-valuemax={maxWidth}onKeyDown={(event) => {if (event.altKey || event.ctrlKey || event.metaKey) return;@@ -70,7 +94,7 @@ export function FileExplorerPane({nextWidth = width - 16;break;case "Home":- nextWidth = MIN_WIDTH;+ nextWidth = minWidth;break;case "End":nextWidth = maxWidth;diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsxindex 94f4ccda825..86e2e27b983 100644--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx@@ -81,6 +81,7 @@ import { DiffPanelLoadingState } from "../DiffPanelShell";import { useDiffWorkerPool } from "../DiffWorkerPoolProvider";import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";import { DiffFileTree } from "../diffs/DiffFileTree";+import { FileExplorerPane } from "../files/FileExplorerPane";import { useCodeViewFileReveal } from "../diffs/useCodeViewFileReveal";import { useHideTestFiles } from "../diffs/useHideTestFiles";import { diffFileTreeEntries, orderDiffFilesLikeTree } from "../diffs/diffFileTree.logic";@@ -1515,7 +1516,14 @@ function PullRequestCodeTab({</FileViewedToggleContext></div>{fileTreeOpen ? (- <aside className="flex w-[min(20rem,40%)] min-w-48 shrink-0 border-l border-border/60">+ <FileExplorerPane+ resizable+ storageKey="t3code:diff-file-tree-width"+ defaultWidth={320}+ defaultWidthFraction={0.4}+ minWidth={192}+ resizeLabel="Resize PR Code files"+ ><DiffFileTreeariaLabel={`${capitalizeTerm(term)} #${detail.number} files`}entries={fileTreeEntries}@@ -1541,7 +1549,7 @@ function PullRequestCodeTab({)}/>- </aside>+ </FileExplorerPane>) : null}</div>{unstructured}diff --git a/apps/web/src/hooks/useResizableWidth.browser.test.tsx b/apps/web/src/hooks/useResizableWidth.browser.test.tsxnew file mode 100644index 00000000000..a34c985f8c1--- /dev/null+++ b/apps/web/src/hooks/useResizableWidth.browser.test.tsx@@ -0,0 +1,85 @@+import { describe, expect, it, vi } from "vite-plus/test";++import { act, render } from "../../test/render";+import { RESIZABLE_WIDTH_PROPERTY, useResizableWidth } from "./useResizableWidth";++const STORAGE_KEY = "test:responsive-panel-width";++function Panel({ defaultWidth }: { defaultWidth: number }) {+ const { width, setWidth, handlers } = useResizableWidth({+ storageKey: STORAGE_KEY,+ defaultWidth,+ minWidth: 160,+ maxWidth: 560,+ edge: "left",+ });+ return (+ <>+ <button onClick={() => setWidth(350)}>{width}</button>+ <div role="separator" style={{ width: 8, height: 40 }} {...handlers} />+ </>+ );+}++describe("useResizableWidth", () => {+ it("follows a responsive default until the user saves a width", async () => {+ const previous = localStorage.getItem(STORAGE_KEY);+ localStorage.removeItem(STORAGE_KEY);+ try {+ // This hook only needs browser storage and React; no navigation is involved.+ await using screen = await render(<Panel defaultWidth={320} />, { router: false });+ expect(screen.container.textContent).toBe("320");+ await screen.rerender(<Panel defaultWidth={200} />);+ expect(screen.container.textContent).toBe("200");++ await act(() => screen.container.querySelector("button")!.click());+ await screen.rerender(<Panel defaultWidth={180} />);+ expect(screen.container.textContent).toBe("350");++ await screen.unmount();+ await using restored = await render(<Panel defaultWidth={200} />, { router: false });+ expect(restored.container.textContent).toBe("350");+ } finally {+ if (previous === null) localStorage.removeItem(STORAGE_KEY);+ else localStorage.setItem(STORAGE_KEY, previous);+ }+ });++ it("keeps the default responsive after a stationary click and persists an actual drag", async () => {+ const previous = localStorage.getItem(STORAGE_KEY);+ localStorage.removeItem(STORAGE_KEY);+ try {+ // This hook only needs browser storage and React; no navigation is involved.+ await using screen = await render(<Panel defaultWidth={240} />, { router: false });+ await screen.getByRole("separator").click();+ expect(localStorage.getItem(STORAGE_KEY)).toBeNull();+ await screen.rerender(<Panel defaultWidth={256} />);+ expect(screen.container.textContent).toBe("256");++ const handle = screen.container.querySelector<HTMLElement>('[role="separator"]')!;+ // Synthetic drag events have no active browser pointer to capture.+ using _capture = vi.spyOn(handle, "setPointerCapture").mockImplementation(() => {});+ const pointer = { bubbles: true, pointerId: 1, button: 0 };+ await act(() => {+ handle.dispatchEvent(new PointerEvent("pointerdown", { ...pointer, clientX: 500 }));+ });+ await screen.rerender(<Panel defaultWidth={280} />);+ await act(() => {+ handle.dispatchEvent(new PointerEvent("pointerup", { ...pointer, clientX: 500 }));+ });+ expect(localStorage.getItem(STORAGE_KEY)).toBeNull();+ expect(screen.container.style.getPropertyValue(RESIZABLE_WIDTH_PROPERTY)).toBe("280px");++ await act(() => {+ handle.dispatchEvent(new PointerEvent("pointerdown", { ...pointer, clientX: 500 }));+ handle.dispatchEvent(new PointerEvent("pointerup", { ...pointer, clientX: 450 }));+ });+ expect(localStorage.getItem(STORAGE_KEY)).toBe("330");+ await screen.rerender(<Panel defaultWidth={200} />);+ expect(screen.container.textContent).toBe("330");+ } finally {+ if (previous === null) localStorage.removeItem(STORAGE_KEY);+ else localStorage.setItem(STORAGE_KEY, previous);+ }+ });+});diff --git a/apps/web/src/hooks/useResizableWidth.ts b/apps/web/src/hooks/useResizableWidth.tsindex 50fdba38a9f..dc5fe8569d0 100644--- a/apps/web/src/hooks/useResizableWidth.ts+++ b/apps/web/src/hooks/useResizableWidth.ts@@ -3,6 +3,7 @@ import { type PointerEvent as ReactPointerEvent, useLayoutEffect, useState } froimport { getLocalStorageItem, setLocalStorageItem } from "./useLocalStorage";import { useResizeDrag } from "./useResizeDrag";+import { useStableCallback } from "./useStableCallback";const WidthSchema = Schema.Finite;@@ -26,7 +27,7 @@ export interface ResizableWidthHandlers {readonly onLostPointerCapture: (event: ReactPointerEvent<HTMLElement>) => void;}-/** Persist on drag end to avoid a storage write on every animation frame. */+/** Uses the current default until a width is chosen; persists on drag end, not every frame. */export function useResizableWidth(options: UseResizableWidthOptions): {readonly width: number;readonly setWidth: (width: number) => void;@@ -39,14 +40,14 @@ export function useResizableWidth(options: UseResizableWidthOptions): {return Math.max(minWidth, Math.min(maxWidth, value));};- const readWidth = () => {- if (typeof window === "undefined") return defaultWidth;+ const readWidth = (): number | null => {+ if (typeof window === "undefined") return null;try {const stored = getLocalStorageItem(storageKey, WidthSchema);- return clamp(stored ?? defaultWidth);+ return stored === null ? null : clamp(stored);} catch (error) {console.error("Could not read persisted panel width.", error);- return defaultWidth;+ return null;}};const [widthState, setWidthState] = useState(() => ({ storageKey, width: readWidth() }));@@ -54,7 +55,10 @@ export function useResizableWidth(options: UseResizableWidthOptions): {setWidthState({ storageKey, width: readWidth() });}- const clampedWidth = clamp(widthState.width);+ const clampedWidth = clamp(widthState.width ?? defaultWidth);+ const restoreWidth = useStableCallback((host: HTMLElement | null) => {+ host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${clampedWidth}px`);+ });const commitWidth = (nextStorageKey: string, nextWidth: number) => {// Resizing remains usable for this session when browser storage is unavailable.@@ -82,8 +86,9 @@ export function useResizableWidth(options: UseResizableWidthOptions): {host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${nextWidth}px`);return nextWidth;},- finish(finalWidth) {- commitWidth(startStorageKey, finalWidth);+ finish(finalWidth, moved) {+ if (moved) commitWidth(startStorageKey, finalWidth);+ else restoreWidth(host);},cleanup(committed) {host?.style.removeProperty("transition-property");