TypeScript
fix(web): make the diff layout toggle a persisted setting (#9326)
Julius Marminge9409dd20a9fb
diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.tsindex 0bddf23e46e..0976ef48975 100644--- a/apps/desktop/src/settings/DesktopClientSettings.test.ts+++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts@@ -29,6 +29,7 @@ const clientSettings: ClientSettings = {contextWindowMeterEnabled: false,dismissedProviderUpdateNotificationKeys: [],diffIgnoreWhitespace: true,+ diffLayout: "stacked",environmentIdentificationMode: "artwork",favorites: [],fontFamilyCode: "",diff --git a/apps/web/src/clientPersistenceStorage.test.ts b/apps/web/src/clientPersistenceStorage.test.tsindex 8f849a6e7b3..db69fe96c80 100644--- a/apps/web/src/clientPersistenceStorage.test.ts+++ b/apps/web/src/clientPersistenceStorage.test.ts@@ -90,4 +90,17 @@ describe("clientPersistenceStorage", () => {expect(settings).not.toHaveProperty("chatWordWrap");expect(settings).not.toHaveProperty("diffWordWrap");});++ it("keeps the diff layout across reloads and defaults it to stacked", async () => {+ const testWindow = getTestWindow();+ const { readBrowserClientSettings, writeBrowserClientSettings } =+ await import("./clientPersistenceStorage");++ expect(readBrowserClientSettings()).toBeNull();+ testWindow.localStorage.setItem("t3code:client-settings:v1", JSON.stringify({}));+ expect(readBrowserClientSettings()?.diffLayout).toBe("stacked");++ writeBrowserClientSettings({ ...DEFAULT_CLIENT_SETTINGS, diffLayout: "split" });+ expect(readBrowserClientSettings()?.diffLayout).toBe("split");+ });});diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsxindex acdc54bb2f4..c55eaa09478 100644--- a/apps/web/src/components/DiffPanel.tsx+++ b/apps/web/src/components/DiffPanel.tsx@@ -44,7 +44,7 @@ import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";import { useProject, useThread } from "../state/entities";import { resolveThreadRouteRef } from "../threadRoutes";-import { useClientSettings } from "../hooks/useSettings";+import { useClientSettings, useUpdateClientSettings } from "../hooks/useSettings";import { formatShortTimestamp } from "../timestampFormat";import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton";import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";@@ -108,8 +108,8 @@ export default function DiffPanel({const { resolvedTheme } = useTheme();const settings = useClientSettings();const [initialGitScope] = useState(initialGitScopeProp);- const diffRenderMode = useDiffPanelStore((state) => state.diffRenderMode);- const setDiffRenderMode = useDiffPanelStore((state) => state.setDiffRenderMode);+ const diffLayout = settings.diffLayout;+ const updateClientSettings = useUpdateClientSettings();const [wordWrap, setWordWrap] = useState(settings.wordWrap);const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);const [baseRefQuery, setBaseRefQuery] = useState("");@@ -768,11 +768,11 @@ export default function DiffPanel({<ToggleGroupclassName="shrink-0 gap-1"size="sm"- value={[diffRenderMode]}+ value={[diffLayout]}onValueChange={(value) => {const next = value[0];if (next === "stacked" || next === "split") {- setDiffRenderMode(next);+ updateClientSettings({ diffLayout: next });}}}>@@ -959,7 +959,7 @@ export default function DiffPanel({);}}options={{- diffStyle: diffRenderMode === "split" ? "split" : "unified",+ diffStyle: diffLayout === "split" ? "split" : "unified",lineDiffType: "none",overflow: wordWrap ? "wrap" : "scroll",theme: resolveDiffThemeName(resolvedTheme),diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsxindex d9f1e7af716..ebae8847bf3 100644--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx@@ -26,7 +26,7 @@ import {import { useAtomRefresh } from "@effect/atom-react";import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";-import { useClientSettings } from "~/hooks/useSettings";+import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";import { useTheme } from "~/hooks/useTheme";import { areAllDiffFilesCollapsed } from "~/lib/diffCollapse";import { pullRequestFindingKey, type PullRequestFinding } from "./pullRequestDetail.logic";@@ -217,7 +217,8 @@ export function PullRequestCodeTab({const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE);/** Set once the reader has asked for every file at once, until they pick a file apart again. */const [foldOverride, setFoldOverride] = useState<DiffFoldOverride>(null);- const [diffRenderMode, setDiffRenderMode] = useState<"stacked" | "split">("stacked");+ const diffLayout = settings.diffLayout;+ const updateClientSettings = useUpdateClientSettings();const [wordWrap, setWordWrap] = useState(settings.wordWrap);const [selectedLines, setSelectedLines] = useState<{id: string;@@ -740,7 +741,7 @@ export function PullRequestCodeTab({const diffViewOptions = useMemo(() => ({- diffStyle: diffRenderMode === "split" ? ("split" as const) : ("unified" as const),+ diffStyle: diffLayout === "split" ? ("split" as const) : ("unified" as const),lineDiffType: "none" as const,overflow: wordWrap ? ("wrap" as const) : ("scroll" as const),theme: resolveDiffThemeName(resolvedTheme),@@ -757,15 +758,7 @@ export function PullRequestCodeTab({onGutterUtilityClick: beginComment,onLineSelectionEnd: beginComment,}),- [- diffRenderMode,- wordWrap,- resolvedTheme,- loadDiffFiles,- canCommentOnLines,- draft,- beginComment,- ],+ [diffLayout, wordWrap, resolvedTheme, loadDiffFiles, canCommentOnLines, draft, beginComment],);const runThreadCommand = useCallback(@@ -1122,11 +1115,11 @@ export function PullRequestCodeTab({<ToggleGroupclassName="shrink-0 gap-1"size="sm"- value={[diffRenderMode]}+ value={[diffLayout]}onValueChange={(value) => {const next = value[0];if (next === "stacked" || next === "split") {- setDiffRenderMode(next);+ updateClientSettings({ diffLayout: next });}}}>diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxindex 3c5f6d7037a..7fc8153a24f 100644--- a/apps/web/src/components/settings/SettingsPanels.tsx+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -19,6 +19,7 @@ import {import {DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE,DEFAULT_UNIFIED_SETTINGS,+ type DiffLayout,type EnvironmentIdentificationMode,MAX_APPEARANCE_CONTRAST,MAX_CODE_FONT_SIZE,@@ -169,6 +170,11 @@ const TIMESTAMP_FORMAT_LABELS = {"24-hour": "24-hour",} as const;+const DIFF_LAYOUT_LABELS: Record<DiffLayout, string> = {+ stacked: "Stacked",+ split: "Split",+};+const QUIT_CONFIRMATION_MODE_LABELS: Record<QuitConfirmationMode, string> = {direct: "Direct",hold: "Hold",@@ -527,6 +533,7 @@ export function useSettingsRestore(onRestored?: () => void) {...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace? ["Diff whitespace changes"]: []),+ ...(settings.diffLayout !== DEFAULT_UNIFIED_SETTINGS.diffLayout ? ["Diff layout"] : []),...(settings.proactivePanelsEnabled !== DEFAULT_UNIFIED_SETTINGS.proactivePanelsEnabled? ["Proactive panels"]: []),@@ -593,6 +600,7 @@ export function useSettingsRestore(onRestored?: () => void) {settings.defaultThreadEnvMode,settings.newWorktreesStartFromOrigin,settings.diffIgnoreWhitespace,+ settings.diffLayout,settings.proactivePanelsEnabled,settings.environmentIdentificationMode,settings.contextWindowMeterEnabled,@@ -689,6 +697,7 @@ export function useSettingsRestore(onRestored?: () => void) {timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,+ diffLayout: DEFAULT_UNIFIED_SETTINGS.diffLayout,proactivePanelsEnabled: DEFAULT_UNIFIED_SETTINGS.proactivePanelsEnabled,showSkillsInSlashMenu: DEFAULT_UNIFIED_SETTINGS.showSkillsInSlashMenu,contextWindowMeterEnabled: DEFAULT_UNIFIED_SETTINGS.contextWindowMeterEnabled,@@ -2223,6 +2232,41 @@ export function GeneralSettingsPanel() {}/>+ <SettingsRow+ {...searchableSetting("diff-layout")}+ description="Show diffs stacked or side by side. The toggle in the diff toolbar changes this too."+ resetAction={+ settings.diffLayout !== DEFAULT_UNIFIED_SETTINGS.diffLayout ? (+ <SettingResetButton+ label="diff layout"+ onClick={() => updateSettings({ diffLayout: DEFAULT_UNIFIED_SETTINGS.diffLayout })}+ />+ ) : null+ }+ control={+ <Select+ value={settings.diffLayout}+ onValueChange={(value) => {+ if (value === "stacked" || value === "split") {+ updateSettings({ diffLayout: value });+ }+ }}+ >+ <SelectTrigger size="sm" className="w-full sm:w-40" aria-label="Diff layout">+ <SelectValue>{DIFF_LAYOUT_LABELS[settings.diffLayout]}</SelectValue>+ </SelectTrigger>+ <SelectPopup align="end" alignItemWithTrigger={false}>+ <SelectItem hideIndicator value="stacked">+ {DIFF_LAYOUT_LABELS.stacked}+ </SelectItem>+ <SelectItem hideIndicator value="split">+ {DIFF_LAYOUT_LABELS.split}+ </SelectItem>+ </SelectPopup>+ </Select>+ }+ />+<SettingsRow{...searchableSetting("proactive-panels")}description="Automatically open the linked pull request when it appears and the turn diff when agent work finishes."diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.tsindex d1bc52283ee..1bbd4ea9ed3 100644--- a/apps/web/src/components/settings/settingsSearch.ts+++ b/apps/web/src/components/settings/settingsSearch.ts@@ -184,6 +184,12 @@ export const SETTINGS_SEARCH_ITEMS = [to: "/settings/general",searchTerms: ["diff ignore spaces edits default"],},+ {+ id: "diff-layout",+ title: "Diff layout",+ to: "/settings/general",+ searchTerms: ["stacked split side by side unified inline view"],+ },{id: "proactive-panels",title: "Proactive panels",diff --git a/apps/web/src/diffPanelStore.test.ts b/apps/web/src/diffPanelStore.test.tsindex 7e7c95921f0..f1d774f9cbf 100644--- a/apps/web/src/diffPanelStore.test.ts+++ b/apps/web/src/diffPanelStore.test.ts@@ -11,30 +11,9 @@ describe("diffPanelStore", () => {useDiffPanelStore.setState({byThreadKey: {},branchBaseRefByThreadKey: {},- diffRenderMode: "stacked",}),);- it("keeps the selected render mode in panel and persisted state", async () => {- useDiffPanelStore.getState().setDiffRenderMode("split");-- expect(useDiffPanelStore.getState().diffRenderMode).toBe("split");- expect(- useDiffPanelStore.persist.getOptions().partialize?.(useDiffPanelStore.getState()),- ).toMatchObject({ diffRenderMode: "split" });-- const { name, storage } = useDiffPanelStore.persist.getOptions();- if (!name) throw new Error("Expected diff panel persistence to have a storage name");- const persisted = await storage?.getItem(name);- expect(persisted?.state).toMatchObject({ diffRenderMode: "split" });-- useDiffPanelStore.setState({ diffRenderMode: "stacked" });- if (persisted) await storage?.setItem(name, persisted);- await useDiffPanelStore.persist.rehydrate();-- expect(useDiffPanelStore.getState().diffRenderMode).toBe("split");- });-it("defaults each thread to branch changes when the working tree is clean", () => {expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, THREAD_REF),diff --git a/apps/web/src/diffPanelStore.ts b/apps/web/src/diffPanelStore.tsindex ebb560a2383..56b5ad23fec 100644--- a/apps/web/src/diffPanelStore.ts+++ b/apps/web/src/diffPanelStore.ts@@ -10,16 +10,12 @@ export type DiffPanelSelection =| { kind: "unstaged" }| { kind: "turn"; turnId: TurnId; filePath: string | null; revealRequestId: number };-export type DiffRenderMode = "stacked" | "split";-const DEFAULT_SELECTION: DiffPanelSelection = { kind: "branch", baseRef: null };const DEFAULT_WORKING_TREE_SELECTION: DiffPanelSelection = { kind: "unstaged" };interface DiffPanelStoreState {byThreadKey: Record<string, DiffPanelSelection>;branchBaseRefByThreadKey: Record<string, string | null>;- diffRenderMode: DiffRenderMode;- setDiffRenderMode: (mode: DiffRenderMode) => void;selectGitScope: (ref: ScopedThreadRef, scope: "branch" | "unstaged") => void;selectBranchBaseRef: (ref: ScopedThreadRef, baseRef: string | null) => void;selectTurn: (ref: ScopedThreadRef, turnId: TurnId, filePath?: string) => void;@@ -37,8 +33,6 @@ export const useDiffPanelStore = create<DiffPanelStoreState>()((set) => ({byThreadKey: {},branchBaseRefByThreadKey: {},- diffRenderMode: "stacked",- setDiffRenderMode: (diffRenderMode) => set({ diffRenderMode }),selectGitScope: (ref, scope) =>set((state) => {const threadKey = scopedThreadKey(ref);@@ -132,7 +126,6 @@ export const useDiffPanelStore = create<DiffPanelStoreState>()(partialize: (state) => ({byThreadKey: state.byThreadKey,branchBaseRefByThreadKey: state.branchBaseRefByThreadKey,- diffRenderMode: state.diffRenderMode,}),},),diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.tsindex 836c3c19d4c..fd3b3f35dd5 100644--- a/packages/contracts/src/settings.ts+++ b/packages/contracts/src/settings.ts@@ -31,6 +31,10 @@ export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"])export type TimestampFormat = typeof TimestampFormat.Type;export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";+export const DiffLayout = Schema.Literals(["stacked", "split"]);+export type DiffLayout = typeof DiffLayout.Type;+export const DEFAULT_DIFF_LAYOUT: DiffLayout = "stacked";+export const SidebarProjectSortOrder = Schema.Literals(["updated_at", "created_at", "manual"]);export type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;export const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = "updated_at";@@ -242,6 +246,7 @@ export const ClientSettingsSchema = Schema.Struct({Schema.withDecodingDefault(Effect.succeed([])),),diffIgnoreWhitespace: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),+ diffLayout: DiffLayout.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_DIFF_LAYOUT))),environmentIdentificationMode: EnvironmentIdentificationMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE)),),@@ -1007,6 +1012,7 @@ export const ClientSettingsPatch = Schema.Struct({confirmThreadUnpin: Schema.optionalKey(Schema.Boolean),continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),+ diffLayout: Schema.optionalKey(DiffLayout),environmentIdentificationMode: Schema.optionalKey(EnvironmentIdentificationMode),glassOpacity: Schema.optionalKey(GlassOpacity),fontSizeInterface: Schema.optionalKey(InterfaceFontSize),