diff --git a/packages/app/e2e/browser/chat-outline.spec.ts b/packages/app/e2e/browser/chat-outline.spec.ts index 640b141f53..26fc917dc2 100644 --- a/packages/app/e2e/browser/chat-outline.spec.ts +++ b/packages/app/e2e/browser/chat-outline.spec.ts @@ -2,7 +2,7 @@ import { expect, test } from "../support/fixtures"; import { trackPromptJumpRequests } from "../support/helpers/agent-timeline-gate"; import { clickChatOutlineRowEdge, - disableChatOutlineFromAppearance, + disableChatOutline, expectActiveChatOutlinePrompt, expectActiveChatOutlinePromptMovedFrom, expectChatOutlinePreview, @@ -314,13 +314,13 @@ test.describe("desktop chat outline", () => { } }); - test("can be disabled from Appearance settings", async ({ page }) => { + test("can be disabled from Chat settings", async ({ page }) => { const agent = await seedLongMockAgentTimeline({ turns: 2 }); try { await page.setViewportSize(WIDE_VIEWPORT); await openAgentTimeline(page, agent); - await disableChatOutlineFromAppearance(page); + await disableChatOutline(page); await expectNoChatOutline(page); } finally { diff --git a/packages/app/e2e/browser/content-width.spec.ts b/packages/app/e2e/browser/content-width.spec.ts index bd3cc4394f..bed1b1849a 100644 --- a/packages/app/e2e/browser/content-width.spec.ts +++ b/packages/app/e2e/browser/content-width.spec.ts @@ -1,20 +1,27 @@ -import { test } from "../support/fixtures"; +import { expect, test } from "../support/fixtures"; import { + chatOutlineRail, + disableChatOutline, + expectChatOutlinePrompts, + expectNoChatOutline, +} from "../support/helpers/chat-outline"; +import { + chooseContentWidth, + expectColumnAtLeftGutter, + expectColumnClearOfOutline, expectContentColumnWidth, - expectCustomContentWidthSetting, - expectDefaultContentWidthSetting, - openAppearanceSettings, - resetContentWidth, - setContentWidth, } from "../support/helpers/content-width"; import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; const ULTRAWIDE_VIEWPORT = { width: 2560, height: 1080 }; +const DEFAULT_COLUMN = { min: 800, max: 820 }; +const WIDE_COLUMN = { min: 1180, max: 1200 }; +const FULL_COLUMN = { min: 2000, max: ULTRAWIDE_VIEWPORT.width }; -test("widens chat and Markdown files to the chosen content width and resets to the default", async ({ +test("resizes mounted chat content and leaves room for the outline at full width", async ({ page, -}, testInfo) => { +}) => { test.setTimeout(120_000); const agent = await seedMockAgentWorkspace({ repoPrefix: "content-width-", @@ -23,47 +30,58 @@ test("widens chat and Markdown files to the chosen content width and resets to t }); try { + await agent.client.waitForFinish(agent.agentId, 30_000); + await agent.client.sendAgentMessage(agent.agentId, "Write another paragraph."); await agent.client.waitForFinish(agent.agentId, 30_000); await page.setViewportSize(ULTRAWIDE_VIEWPORT); - const assistantMessage = page.getByTestId("assistant-message").first(); - const markdownPreview = page.getByTestId("markdown-preview-frame").first(); + await openAgentRoute(page, agent); + await expectChatOutlinePrompts(page, 2); + const reply = page.getByTestId("assistant-message").first(); + const composer = page.getByTestId("message-input-root"); + await expectContentColumnWidth(reply, DEFAULT_COLUMN); + const originalReply = await reply.elementHandle(); - await test.step("chat starts at the default width", async () => { - await openAgentRoute(page, agent); - await expectContentColumnWidth(assistantMessage, { max: 820 }); - }); + await chooseContentWidth(page, "Wide"); + await expectContentColumnWidth(reply, WIDE_COLUMN); + await expectContentColumnWidth(composer, WIDE_COLUMN); - await test.step("settings show the default without a reset", async () => { - await openAppearanceSettings(page); - await expectDefaultContentWidthSetting(page, 820); - }); + await chooseContentWidth(page, "Full"); + await expectContentColumnWidth(reply, FULL_COLUMN); + await expectContentColumnWidth(composer, FULL_COLUMN); + await expectColumnClearOfOutline(reply, chatOutlineRail(page)); - await test.step("a custom width is saved and offers a reset", async () => { - await setContentWidth(page, 1600); - await expectCustomContentWidthSetting(page, 1600); - await page.screenshot({ path: testInfo.outputPath("settings-custom-width.png") }); - }); + await disableChatOutline(page); + await expectNoChatOutline(page); + await expectColumnAtLeftGutter(page, reply); - await test.step("chat and Markdown files use the custom width", async () => { - await openAgentRoute(page, agent); - await expectContentColumnWidth(assistantMessage, { min: 1200, max: 1600 }); - await page.screenshot({ path: testInfo.outputPath("chat-custom-width.png") }); + await chooseContentWidth(page, "Default"); + await expectContentColumnWidth(reply, DEFAULT_COLUMN); + await expectContentColumnWidth(composer, DEFAULT_COLUMN); + expect(await originalReply?.evaluate((node) => node.isConnected)).toBe(true); + } finally { + await agent.cleanup(); + } +}); - await openFileExplorer(page); - await openFileFromExplorer(page, "README.md"); - await expectContentColumnWidth(markdownPreview, { min: 1200, max: 1600 }); - await page.screenshot({ path: testInfo.outputPath("markdown-custom-width.png") }); - }); +test("updates an open Markdown preview when the content width changes", async ({ page }) => { + const agent = await seedMockAgentWorkspace({ + repoPrefix: "markdown-content-width-", + title: "Markdown content width", + }); - await test.step("reset returns to the default without storing it", async () => { - await openAppearanceSettings(page); - await resetContentWidth(page); - await expectDefaultContentWidthSetting(page, 820); + try { + await page.setViewportSize(ULTRAWIDE_VIEWPORT); + await openAgentRoute(page, agent); + await openFileExplorer(page); + await openFileFromExplorer(page, "README.md"); + const preview = page.getByTestId("markdown-preview-frame").first(); + await expectContentColumnWidth(preview, DEFAULT_COLUMN); - await openAgentRoute(page, agent); - await expectContentColumnWidth(assistantMessage, { max: 820 }); - await page.screenshot({ path: testInfo.outputPath("chat-default-width.png") }); - }); + await chooseContentWidth(page, "Wide"); + await expectContentColumnWidth(preview, WIDE_COLUMN); + + await chooseContentWidth(page, "Full"); + await expectContentColumnWidth(preview, { min: 1500, max: ULTRAWIDE_VIEWPORT.width }); } finally { await agent.cleanup(); } diff --git a/packages/app/e2e/support/helpers/chat-outline.ts b/packages/app/e2e/support/helpers/chat-outline.ts index d219979fcf..e741125464 100644 --- a/packages/app/e2e/support/helpers/chat-outline.ts +++ b/packages/app/e2e/support/helpers/chat-outline.ts @@ -1,6 +1,6 @@ import { expect, type Locator, type Page } from "@playwright/test"; import { openSettings } from "./app"; -import { openSettingsSection } from "./settings"; +import { clickSettingsBackToWorkspace, openSettingsSection } from "./settings"; import { runWorkspaceActionFromCommandCenter } from "./command-center-workspace-actions"; import { seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent"; import { loadSessionMessageReaders } from "./new-workspace"; @@ -81,12 +81,13 @@ export async function splitCurrentPanelRight(page: Page): Promise { await runWorkspaceActionFromCommandCenter(page, "Split pane right"); } -export async function disableChatOutlineFromAppearance(page: Page): Promise { - const timelineUrl = page.url(); +export async function disableChatOutline(page: Page): Promise { await openSettings(page); await openSettingsSection(page, "chat"); - await page.getByRole("switch", { name: "Chat outline" }).click(); - await page.goto(timelineUrl); + const outlineSwitch = page.getByRole("switch", { name: "Chat outline" }); + await outlineSwitch.click(); + await expect(outlineSwitch).not.toBeChecked(); + await clickSettingsBackToWorkspace(page); } /** Parks the pointer in the middle of the transcript, clear of the rail. */ diff --git a/packages/app/e2e/support/helpers/content-width.ts b/packages/app/e2e/support/helpers/content-width.ts index a99ee6a956..501a4f65cf 100644 --- a/packages/app/e2e/support/helpers/content-width.ts +++ b/packages/app/e2e/support/helpers/content-width.ts @@ -1,63 +1,53 @@ import { expect, type Locator, type Page } from "@playwright/test"; import { openSettings } from "./app"; -import { openSettingsSection } from "./settings"; +import { clickSettingsBackToWorkspace, openSettingsSection } from "./settings"; -const APP_SETTINGS_KEY = "@paseo:app-settings"; +type ContentWidthOption = "Default" | "Wide" | "Full"; -function contentWidthInput(page: Page): Locator { - return page.getByLabel("Content width in pixels", { exact: true }); +function contentWidthOption(page: Page, option: ContentWidthOption): Locator { + return page + .getByTestId("content-width-options") + .getByRole("button", { name: option, exact: true }); } -function resetContentWidthButton(page: Page): Locator { - return page.getByRole("button", { name: "Reset content width to default", exact: true }); -} - -export async function openAppearanceSettings(page: Page): Promise { +export async function chooseContentWidth(page: Page, option: ContentWidthOption): Promise { await openSettings(page); await openSettingsSection(page, "appearance"); + const button = contentWidthOption(page, option); + await button.click(); + await expect(button).toHaveAttribute("aria-selected", "true"); + await clickSettingsBackToWorkspace(page); } -export async function setContentWidth(page: Page, width: number): Promise { - const input = contentWidthInput(page); - await input.fill(String(width)); - await input.press("Tab"); -} - -export async function resetContentWidth(page: Page): Promise { - await resetContentWidthButton(page).click(); -} - -export async function expectDefaultContentWidthSetting(page: Page, width: number): Promise { - await expect(contentWidthInput(page)).toHaveValue(String(width)); - await expect(resetContentWidthButton(page)).toHaveCount(0); - await expect.poll(() => readStoredContentWidth(page)).toBeNull(); -} - -export async function expectCustomContentWidthSetting(page: Page, width: number): Promise { - await expect(contentWidthInput(page)).toHaveValue(String(width)); - await expect(resetContentWidthButton(page)).toBeVisible(); - await expect.poll(() => readStoredContentWidth(page)).toBe(width); -} - -/** Asserts the rendered width of a content-column element stays within `max` and above `min`. */ +/** Checks the rendered content width, allowing for padding inside the column. */ export async function expectContentColumnWidth( element: Locator, - bounds: { min?: number; max: number }, + bounds: { min: number; max: number }, ): Promise { await expect(element).toBeVisible({ timeout: 30_000 }); await expect .poll(async () => (await element.boundingBox())?.width ?? 0) - .toBeLessThanOrEqual(bounds.max); + .toBeGreaterThanOrEqual(bounds.min); await expect - .poll(async () => (await element.boundingBox())?.width ?? 0) - .toBeGreaterThan(bounds.min ?? 0); + .poll(async () => (await element.boundingBox())?.width ?? Infinity) + .toBeLessThanOrEqual(bounds.max); } -async function readStoredContentWidth(page: Page): Promise { - return page.evaluate((key) => { - const raw = localStorage.getItem(key); - return raw === null - ? undefined - : (JSON.parse(raw) as { contentMaxWidth?: unknown }).contentMaxWidth; - }, APP_SETTINGS_KEY); +export async function expectColumnClearOfOutline(column: Locator, outline: Locator): Promise { + await expect + .poll(async () => { + const [content, rail] = await Promise.all([column.boundingBox(), outline.boundingBox()]); + return content && rail ? content.x - (rail.x + rail.width) : -1; + }) + .toBeGreaterThanOrEqual(8); +} + +export async function expectColumnAtLeftGutter(page: Page, column: Locator): Promise { + const viewport = page.getByTestId("agent-chat-scroll"); + await expect + .poll(async () => { + const [content, scroll] = await Promise.all([column.boundingBox(), viewport.boundingBox()]); + return content && scroll ? content.x - scroll.x : Infinity; + }) + .toBeLessThanOrEqual(24); } diff --git a/packages/app/src/agent-stream/chat-outline/rail.tsx b/packages/app/src/agent-stream/chat-outline/rail.tsx index 0736ee21a2..d6db6c1251 100644 --- a/packages/app/src/agent-stream/chat-outline/rail.tsx +++ b/packages/app/src/agent-stream/chat-outline/rail.tsx @@ -11,3 +11,7 @@ export interface ChatOutlineRailProps { export function ChatOutlineRail(_props: ChatOutlineRailProps): null { return null; } + +export function useChatOutlineRailLayout(_enabled: boolean) { + return { onLayout: undefined, inset: 0 }; +} diff --git a/packages/app/src/agent-stream/chat-outline/rail.web.tsx b/packages/app/src/agent-stream/chat-outline/rail.web.tsx index 3cb79f108b..875d8699cd 100644 --- a/packages/app/src/agent-stream/chat-outline/rail.web.tsx +++ b/packages/app/src/agent-stream/chat-outline/rail.web.tsx @@ -3,6 +3,7 @@ import { Pressable, Text, View, type PointerEvent as RNPointerEvent } from "reac import { StyleSheet } from "react-native-unistyles"; import { useReducedMotion } from "react-native-reanimated"; import { useContainerWidthBelow } from "@/hooks/use-container-width"; +import { SPACING } from "@/styles/theme"; import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style"; import { createChatOutlineHoverIntent } from "./hover-intent"; import { promptTickMagnification } from "./model"; @@ -11,6 +12,7 @@ import type { ChatOutlineRailProps } from "./rail"; // Hover tracking lives on the rail and the slots, never on the Pressable inside them: // magnifying a slot must not move the box the pointer is resting on. See docs/hover.md. const RAIL_WIDTH = 36; +const RAIL_LEFT = SPACING[2]; const SLOT_HEIGHT = 8; const MIN_PANEL_WIDTH = 918; const RESTING_PILL_HEIGHT = 2; @@ -22,6 +24,11 @@ const PREVIEW_WIDTH = 260; const PREVIEW_HEIGHT = 48; const PREVIEW_GAP = 4; +export function useChatOutlineRailLayout(enabled: boolean) { + const { onLayout, isBelow } = useContainerWidthBelow(MIN_PANEL_WIDTH); + return { onLayout, inset: enabled && !isBelow ? RAIL_LEFT + RAIL_WIDTH : 0 }; +} + export const ChatOutlineRail = memo(function ChatOutlineRail({ prompts, activePrompt, @@ -31,7 +38,6 @@ export const ChatOutlineRail = memo(function ChatOutlineRail({ const [focusedIndex, setFocusedIndex] = useState(null); const activeSeq = useSyncExternalStore(activePrompt.subscribe, activePrompt.getActiveSeq); const prefersReducedMotion = useReducedMotion(); - const { onLayout, isBelow: isPanelNarrow } = useContainerWidthBelow(MIN_PANEL_WIDTH); const hoverIntent = useMemo( () => @@ -60,9 +66,6 @@ export const ChatOutlineRail = memo(function ChatOutlineRail({ ); const handlePointerLeaveRail = useCallback(() => hoverIntent.leave(), [hoverIntent]); useEffect(() => () => hoverIntent.dispose(), [hoverIntent]); - useEffect(() => { - if (isPanelNarrow) hoverIntent.leave(); - }, [hoverIntent, isPanelNarrow]); const handleFocusChange = useCallback((index: number, focused: boolean) => { setFocusedIndex((current) => { if (focused) return index; @@ -74,40 +77,34 @@ export const ChatOutlineRail = memo(function ChatOutlineRail({ // same band and the same preview once the pointer leaves. const attentionIndex = hoveredIndex ?? focusedIndex; - if (prompts.length < 2) return null; - return ( - - {isPanelNarrow ? null : ( - - {prompts.map((prompt, index) => ( - - ))} - - )} + + {prompts.map((prompt, index) => ( + + ))} ); }); @@ -185,13 +182,9 @@ const ChatOutlineTick = memo(function ChatOutlineTick({ }); const styles = StyleSheet.create((theme) => ({ - panelMeasure: { - position: "absolute", - inset: 0, - }, rail: { position: "absolute", - left: theme.spacing[2], + left: RAIL_LEFT, top: "10%", bottom: "10%", width: RAIL_WIDTH, diff --git a/packages/app/src/agent-stream/strategy-web.tsx b/packages/app/src/agent-stream/strategy-web.tsx index 465d98e8d8..ccc789f6b5 100644 --- a/packages/app/src/agent-stream/strategy-web.tsx +++ b/packages/app/src/agent-stream/strategy-web.tsx @@ -314,6 +314,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool olderHistoryProgressKey, scrollEnabled, contentMaxWidth, + outlineInset = 0, isMobileBreakpoint, } = props; const historyVirtualized = useRevisedHistoryRows( @@ -453,7 +454,13 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool unsubscribe?.(); }; }, []); - const contentWidth = contentRef.current?.getBoundingClientRect().width; + // The scroll viewport keeps its width when the reading column changes. + // Track the effective column width for cached measurements and estimates. + const readContentWidth = () => { + const available = rowsHostRef.current?.getBoundingClientRect().width; + return available ? Math.min(available, contentMaxWidth ?? available) : contentMaxWidth; + }; + const contentWidth = readContentWidth(); const rowVirtualizer = useVirtualizer({ count: segments.historyVirtualized.length, enabled: shouldUseVirtualizer, @@ -469,7 +476,9 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool const row = segments.historyVirtualized[index]; const measured = row && measuredRowHeights.current.get(row.id); if (measured && measured.width === contentWidth) return measured.height; - return row ? estimateStreamItemHeight({ item: row, contentMaxWidth }) : 120; + return row + ? estimateStreamItemHeight({ item: row, contentMaxWidth: contentWidth ?? 0 }) + : 120; }, observeElementOffset: observeVirtualOffset, rangeExtractor, @@ -477,6 +486,10 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool overscan: 8, }); rowVirtualizerRef.current = rowVirtualizer; + useLayoutEffect(() => { + // Discard offscreen sizes measured with the previous text wrapping. + rowVirtualizer.measure(); + }, [contentMaxWidth, outlineInset, rowVirtualizer]); // Scroll correction belongs to the viewport's committed layout. The virtualizer // otherwise writes scrollTop before React applies its new row positions. rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = () => false; @@ -722,7 +735,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool if (!container || !content) return null; const viewportTop = container.getBoundingClientRect().top; const scrollTop = container.scrollTop; - const width = content.getBoundingClientRect().width; + const width = readContentWidth() ?? 0; return Array.from(content.querySelectorAll("[data-history-row-id]"), (element) => { const bounds = element.getBoundingClientRect(); const id = element.dataset.historyRowId!; @@ -1215,17 +1228,24 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool ]); const contentContainerStyle = useMemo((): CSSProperties => { + const gutter = isMobileBreakpoint ? 8 : 16; + const leftGutter = gutter + outlineInset; + // Balance the outline gutter using only the space the capped column has left over. + const rightGutter = + outlineInset > 0 && contentMaxWidth !== undefined + ? `clamp(${gutter}px, calc(100% - ${leftGutter + contentMaxWidth}px), ${leftGutter}px)` + : gutter; return { display: "flex", flexDirection: "column", minHeight: "100%", paddingTop: CONTENT_PADDING_TOP_PX, paddingBottom: 16, - paddingLeft: isMobileBreakpoint ? 8 : 16, - paddingRight: isMobileBreakpoint ? 8 : 16, + paddingLeft: leftGutter, + paddingRight: rightGutter, boxSizing: "border-box", }; - }, [isMobileBreakpoint]); + }, [contentMaxWidth, isMobileBreakpoint, outlineInset]); const scrollContainerStyle = useMemo((): CSSProperties => { const overlayScrollbarEnabled = scrollEnabled && !isMobileBreakpoint; return { diff --git a/packages/app/src/agent-stream/strategy.ts b/packages/app/src/agent-stream/strategy.ts index aab5b0413e..7507f3442b 100644 --- a/packages/app/src/agent-stream/strategy.ts +++ b/packages/app/src/agent-stream/strategy.ts @@ -107,7 +107,8 @@ export interface StreamRenderInput { baseListContentContainerStyle: StyleProp; forwardListContentContainerStyle: StyleProp; // The chat column's max width. The web viewport estimates unmeasured row heights with it. - contentMaxWidth: number; + contentMaxWidth: number | undefined; + outlineInset?: number; } export interface ResolveStreamRenderStrategyInput { diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index 9f71998a41..149e863400 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -80,7 +80,7 @@ import { resolveStreamRenderStrategy } from "./strategy-resolver"; import { type StreamSegmentRenderers, type StreamViewportHandle } from "./strategy"; import { renderStreamRow, type RenderStreamItem } from "./stream-row"; import { type NearBottom, useIsNearBottom, useNearBottom } from "./near-bottom"; -import { ChatOutlineRail } from "@/agent-stream/chat-outline/rail"; +import { ChatOutlineRail, useChatOutlineRailLayout } from "@/agent-stream/chat-outline/rail"; import { useChatOutline } from "@/agent-stream/chat-outline/use-chat-outline"; import { getHostRuntimeStore } from "@/runtime/host-runtime"; import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan"; @@ -617,19 +617,22 @@ const AgentStreamViewComponent = forwardRef ({ @@ -1173,7 +1176,10 @@ const AgentStreamViewComponent = forwardRef - + @@ -1202,15 +1208,18 @@ const AgentStreamViewComponent = forwardRef - + {outlineLayout.inset > 0 && chatOutline.prompts.length >= 2 ? ( + + ) : null} }; } @@ -105,10 +105,13 @@ describe("applyAppearance", () => { ]); }); - it("patches the content max width into the theme", () => { - applyAppearance(makeInput({ contentMaxWidth: 1600 })); + it.each([ + [1600, "1600px"], + [undefined, "100%"], + ])("uses a CSS variable-compatible width on web for %s", (contentMaxWidth, cssWidth) => { + applyAppearance(makeInput({ contentMaxWidth })); - expect(runCapturedUpdater().contentMaxWidth).toBe(1600); + expect(runCapturedUpdater().contentMaxWidth).toBe(cssWidth); }); it("resolves an empty UI font family to the default stack", () => { diff --git a/packages/app/src/appearance/apply.ts b/packages/app/src/appearance/apply.ts index 04032a00b0..ea4486fe63 100644 --- a/packages/app/src/appearance/apply.ts +++ b/packages/app/src/appearance/apply.ts @@ -5,6 +5,7 @@ import { DEFAULT_MONO_FONT_STACK, FONT_SIZE, REGISTERED_THEMES, + themeContentMaxWidth, type Theme, } from "@/styles/theme"; import { applyRootUiFont } from "./apply-root-font"; @@ -17,7 +18,7 @@ export interface AppearanceInput { uiBaseFontSize: number; // already clamped contentFontSize: number; // already clamped codeFontSize: number; // already clamped - contentMaxWidth: number; // already clamped, default resolved + contentMaxWidth: number | undefined; // undefined fills the available width syntaxTheme: SyntaxThemeId; } @@ -64,6 +65,7 @@ export function applyAppearance(input: AppearanceInput): void { const ui = input.uiFontFamily.trim() || DEFAULT_UI_FONT_STACK; const mono = input.monoFontFamily.trim() || DEFAULT_MONO_FONT_STACK; const diffLineHeight = Math.round(input.codeFontSize * 1.5); // couple to code size + const contentMaxWidth = themeContentMaxWidth(input.contentMaxWidth); const activeTheme = UnistylesRuntime.themeName; // Unistyles web emits after each registry patch. Updating the mounted theme // first ensures subscribers receive its new numeric tokens in this render; @@ -87,7 +89,7 @@ export function applyAppearance(input: AppearanceInput): void { fontFamily, fontSize, lineHeight, - contentMaxWidth: input.contentMaxWidth, + contentMaxWidth, colors: { ...t.colors, syntax: resolveSyntaxColors(input.syntaxTheme, t.colorScheme) }, }; } @@ -96,7 +98,7 @@ export function applyAppearance(input: AppearanceInput): void { fontFamily, fontSize, lineHeight, - contentMaxWidth: input.contentMaxWidth, + contentMaxWidth, colors: { ...t.colors, syntax: resolveSyntaxColors(input.syntaxTheme, t.colorScheme) }, }; }); diff --git a/packages/app/src/appearance/provider.tsx b/packages/app/src/appearance/provider.tsx index 77addad9a3..6466221197 100644 --- a/packages/app/src/appearance/provider.tsx +++ b/packages/app/src/appearance/provider.tsx @@ -65,6 +65,7 @@ export function AppearanceProvider({ children }: { children: ReactNode }) { return options.find((option) => option.id === settings.pluginThemeId) ?? null; }, [options, settings.pluginThemeId, settings.theme]); + const contentMaxWidth = resolveContentMaxWidth(settings); useEffect(() => { if (isLoading) return; applyTheme({ preference: settings.theme, contributedTheme: selected }); @@ -74,7 +75,7 @@ export function AppearanceProvider({ children }: { children: ReactNode }) { uiBaseFontSize: settings.uiBaseFontSize, contentFontSize: settings.contentFontSize, codeFontSize: settings.codeFontSize, - contentMaxWidth: resolveContentMaxWidth({ contentMaxWidth: settings.contentMaxWidth }), + contentMaxWidth, syntaxTheme: settings.syntaxTheme, }); setHasAppliedAppearance(true); @@ -87,7 +88,7 @@ export function AppearanceProvider({ children }: { children: ReactNode }) { settings.uiBaseFontSize, settings.contentFontSize, settings.codeFontSize, - settings.contentMaxWidth, + contentMaxWidth, settings.syntaxTheme, ]); diff --git a/packages/app/src/assistant-selection-copy/surface.tsx b/packages/app/src/assistant-selection-copy/surface.tsx index 4f6464c190..691f7e3d6e 100644 --- a/packages/app/src/assistant-selection-copy/surface.tsx +++ b/packages/app/src/assistant-selection-copy/surface.tsx @@ -1,14 +1,20 @@ import type { ReactNode } from "react"; -import { View, type StyleProp, type ViewStyle } from "react-native"; +import { View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from "react-native"; interface AssistantSelectionCopySurfaceProps { children: ReactNode; style?: StyleProp; + onLayout?: (event: LayoutChangeEvent) => void; } export function AssistantSelectionCopySurface({ children, style, + onLayout, }: AssistantSelectionCopySurfaceProps) { - return {children}; + return ( + + {children} + + ); } diff --git a/packages/app/src/assistant-selection-copy/surface.web.tsx b/packages/app/src/assistant-selection-copy/surface.web.tsx index 280688b61e..57ddd94e61 100644 --- a/packages/app/src/assistant-selection-copy/surface.web.tsx +++ b/packages/app/src/assistant-selection-copy/surface.web.tsx @@ -1,10 +1,11 @@ import { useCallback, type ClipboardEvent, type CSSProperties, type ReactNode } from "react"; -import { View, type StyleProp, type ViewStyle } from "react-native"; +import { View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from "react-native"; import { createAssistantSelectionClipboardContent } from "./content.web"; interface AssistantSelectionCopySurfaceProps { children: ReactNode; style?: StyleProp; + onLayout?: (event: LayoutChangeEvent) => void; } const DISPLAY_CONTENTS: CSSProperties = { display: "contents" }; @@ -12,6 +13,7 @@ const DISPLAY_CONTENTS: CSSProperties = { display: "contents" }; export function AssistantSelectionCopySurface({ children, style, + onLayout, }: AssistantSelectionCopySurfaceProps) { const handleCopy = useCallback((event: ClipboardEvent) => { const content = createAssistantSelectionClipboardContent(window.getSelection()); @@ -26,7 +28,9 @@ export function AssistantSelectionCopySurface({ return (
- {children} + + {children} +
); } diff --git a/packages/app/src/components/ui/segmented-control.tsx b/packages/app/src/components/ui/segmented-control.tsx index 5b18b7499d..e0221d56d1 100644 --- a/packages/app/src/components/ui/segmented-control.tsx +++ b/packages/app/src/components/ui/segmented-control.tsx @@ -25,7 +25,7 @@ export interface SegmentedControlOption { interface SegmentedControlProps { options: SegmentedControlOption[]; - value: T; + value: T | null; onValueChange: (value: T) => void; size?: ControlSize; hideLabels?: boolean; @@ -112,7 +112,7 @@ function SegmentItem({ hideLabels: boolean; segmentSizeStyle: StyleProp; labelSizeStyle: StyleProp; - currentValue: T; + currentValue: T | null; onValueChange: (value: T) => void; }) { const labelStyle = useMemo( diff --git a/packages/app/src/hooks/use-settings/index.ts b/packages/app/src/hooks/use-settings/index.ts index 382ab350fc..9113b2e6e4 100644 --- a/packages/app/src/hooks/use-settings/index.ts +++ b/packages/app/src/hooks/use-settings/index.ts @@ -23,19 +23,16 @@ import { DEFAULT_UI_BASE_FONT_SIZE, MAX_CODE_FONT_SIZE, MAX_CONTENT_FONT_SIZE, - MAX_CONTENT_MAX_WIDTH, MAX_TERMINAL_SCROLLBACK_LINES, MAX_UI_BASE_FONT_SIZE, MIN_CODE_FONT_SIZE, MIN_CONTENT_FONT_SIZE, - MIN_CONTENT_MAX_WIDTH, MIN_TERMINAL_SCROLLBACK_LINES, MIN_UI_BASE_FONT_SIZE, loadAppSettingsFromStorage as loadAppSettingsFromStoragePure, loadSettingsFromStorage as loadSettingsFromStoragePure, normalizeAppSettings, parseClampedFontSize, - parseContentMaxWidth, parseTerminalScrollbackLines, resolveContentMaxWidth, sanitizeFontFamily, @@ -43,6 +40,7 @@ import { type AppSettings, type AppSettingsUpdate, type ChatDisplay, + type ContentWidthPreset, type OpenInSidePanePreferences, type PullRequestOpenLocation, type DesktopSettingsBridge, @@ -69,16 +67,13 @@ export { DEFAULT_UI_BASE_FONT_SIZE, MAX_CODE_FONT_SIZE, MAX_CONTENT_FONT_SIZE, - MAX_CONTENT_MAX_WIDTH, MAX_TERMINAL_SCROLLBACK_LINES, MAX_UI_BASE_FONT_SIZE, MIN_CODE_FONT_SIZE, MIN_CONTENT_FONT_SIZE, - MIN_CONTENT_MAX_WIDTH, MIN_TERMINAL_SCROLLBACK_LINES, MIN_UI_BASE_FONT_SIZE, parseClampedFontSize, - parseContentMaxWidth, parseTerminalScrollbackLines, resolveContentMaxWidth, sanitizeFontFamily, @@ -87,6 +82,7 @@ export type { AppSettings, AppSettingsUpdate, ChatDisplay, + ContentWidthPreset, AppLanguage, OpenInSidePanePreferences, PullRequestOpenLocation, diff --git a/packages/app/src/hooks/use-settings/storage.test.ts b/packages/app/src/hooks/use-settings/storage.test.ts index 8f426f9f2b..55e2d2085b 100644 --- a/packages/app/src/hooks/use-settings/storage.test.ts +++ b/packages/app/src/hooks/use-settings/storage.test.ts @@ -1121,49 +1121,64 @@ describe("parseClampedFontSize", () => { }); }); -describe("content max width", () => { - it("follows the current default until the user picks a width", async () => { +describe("content width", () => { + it("uses the default width when no preference is saved", async () => { const deps = makeDeps(); const queryClient = new QueryClient(); await saveAppSettings({ queryClient, updates: { codeFontSize: 14 }, deps }); - const stored = JSON.parse(deps.storage.entries.get(APP_SETTINGS_KEY) ?? "null"); - expect(stored.contentMaxWidth).toBeNull(); - expect(resolveContentMaxWidth(await loadAppSettingsFromStorage(deps))).toBe( - DEFAULT_CONTENT_MAX_WIDTH, - ); + const settings = await loadAppSettingsFromStorage(deps); + expect(settings.contentWidth).toBe("default"); + expect(resolveContentMaxWidth(settings)).toBe(DEFAULT_CONTENT_MAX_WIDTH); }); - it("keeps a picked width and returns to the default when reset", async () => { + it.each([ + ["wide", 1200], + ["full", undefined], + ["default", DEFAULT_CONTENT_MAX_WIDTH], + ] as const)("persists the %s preset and resolves its width", async (contentWidth, expected) => { const deps = makeDeps(); const queryClient = new QueryClient(); + await saveAppSettings({ queryClient, updates: { contentWidth }, deps }); - await saveAppSettings({ queryClient, updates: { contentMaxWidth: 1600 }, deps }); - expect(resolveContentMaxWidth(await loadAppSettingsFromStorage(deps))).toBe(1600); - - await saveAppSettings({ queryClient, updates: { contentMaxWidth: null }, deps }); - expect(JSON.parse(deps.storage.entries.get(APP_SETTINGS_KEY) ?? "null").contentMaxWidth).toBe( - null, - ); - expect(resolveContentMaxWidth(await loadAppSettingsFromStorage(deps))).toBe( - DEFAULT_CONTENT_MAX_WIDTH, - ); + const settings = await loadAppSettingsFromStorage(deps); + expect(settings.contentWidth).toBe(contentWidth); + expect(resolveContentMaxWidth(settings)).toBe(expected); }); - it("clamps stored widths and drops malformed ones to the default", async () => { - const load = (contentMaxWidth: unknown) => - loadAppSettingsFromStorage( - makeDeps({ - storage: createInMemoryKeyValueStorage({ - [APP_SETTINGS_KEY]: JSON.stringify({ contentMaxWidth }), - }), - }), - ); + it("preserves a legacy custom width until a preset is picked", async () => { + const deps = makeDeps({ + storage: createInMemoryKeyValueStorage({ + [APP_SETTINGS_KEY]: JSON.stringify({ contentMaxWidth: 1600 }), + }), + }); + const queryClient = new QueryClient(); + const settings = await loadAppSettingsFromStorage(deps); + expect(settings.contentWidth).toBe(1600); + expect(resolveContentMaxWidth(settings)).toBe(1600); - expect((await load(100_000)).contentMaxWidth).toBe(4000); - expect((await load(10)).contentMaxWidth).toBe(600); - expect((await load("wide")).contentMaxWidth).toBeNull(); + await saveAppSettings({ queryClient, updates: { codeFontSize: 14 }, deps }); + expect((await loadAppSettingsFromStorage(deps)).contentWidth).toBe(1600); + + await saveAppSettings({ queryClient, updates: { contentWidth: "default" }, deps }); + expect((await loadAppSettingsFromStorage(deps)).contentWidth).toBe("default"); + }); + + it.each([ + [100_000, 4000], + [10, 600], + [null, "default"], + ["wide", "default"], + ])("normalizes legacy width %s on load", async (contentMaxWidth, expected) => { + const settings = await loadAppSettingsFromStorage( + makeDeps({ + storage: createInMemoryKeyValueStorage({ + [APP_SETTINGS_KEY]: JSON.stringify({ contentMaxWidth }), + }), + }), + ); + expect(settings.contentWidth).toBe(expected); }); }); diff --git a/packages/app/src/hooks/use-settings/storage.ts b/packages/app/src/hooks/use-settings/storage.ts index f04b7b6d94..11ba437dd4 100644 --- a/packages/app/src/hooks/use-settings/storage.ts +++ b/packages/app/src/hooks/use-settings/storage.ts @@ -73,8 +73,11 @@ export const MIN_CODE_FONT_SIZE = 9; export const MAX_CODE_FONT_SIZE = 22; // line-height 1.5×22=33 stays safe export const MAX_FONT_FAMILY_LENGTH = 200; export { DEFAULT_CONTENT_MAX_WIDTH }; -export const MIN_CONTENT_MAX_WIDTH = 600; -export const MAX_CONTENT_MAX_WIDTH = 4000; +const WIDE_CONTENT_MAX_WIDTH = 1200; +const legacyContentMaxWidthSchema = clampedNumber(600, 4000); +const contentWidthPresetSchema = z.enum(["default", "wide", "full"]); +export type ContentWidthPreset = z.infer; +type ContentWidth = ContentWidthPreset | number; export interface AppSettings { theme: ThemePreference; @@ -89,8 +92,8 @@ export interface AppSettings { uiBaseFontSize: number; // clamped px, platform default 14 or 15 contentFontSize: number; // clamped px, platform default 15 or 16 codeFontSize: number; // clamped px, default 12 - /** Max width of chat and markdown content in px; null follows the current default. */ - contentMaxWidth: number | null; + /** Numbers preserve widths saved before presets were introduced. */ + contentWidth: ContentWidth; syntaxTheme: SyntaxThemeId; // default "one" workspaceTitleSource: WorkspaceTitleSource; sidebarWorkspaceTrailing: SidebarWorkspaceTrailing; @@ -152,7 +155,7 @@ export const DEFAULT_CLIENT_SETTINGS: AppSettings = { uiBaseFontSize: DEFAULT_UI_BASE_FONT_SIZE, contentFontSize: DEFAULT_CONTENT_FONT_SIZE, codeFontSize: DEFAULT_CODE_FONT_SIZE, - contentMaxWidth: null, + contentWidth: "default", syntaxTheme: "one", workspaceTitleSource: "title", sidebarWorkspaceTrailing: "timestamp", @@ -244,10 +247,12 @@ const StoredAppSettingsSchema = z codeFontSize: clampedNumber(MIN_CODE_FONT_SIZE, MAX_CODE_FONT_SIZE).catch( DEFAULT_CODE_FONT_SIZE, ), - contentMaxWidth: z - .null() - .or(clampedNumber(MIN_CONTENT_MAX_WIDTH, MAX_CONTENT_MAX_WIDTH)) - .catch(null), + contentWidth: contentWidthPresetSchema + .or(legacyContentMaxWidthSchema) + .optional() + .catch(undefined), + // COMPAT(contentMaxWidth): preserve the previous numeric preference. + contentMaxWidth: legacyContentMaxWidthSchema.nullish().catch(undefined), syntaxTheme: z.string().refine(isSyntaxThemeId).catch("one"), workspaceTitleSource: z.enum(["title", "branch"]).catch("title"), sidebarWorkspaceTrailing: z.enum(["diff", "timestamp", "none"]).catch("timestamp"), @@ -303,9 +308,10 @@ const StoredAppSettingsSchema = z manageBuiltInDaemon: z.boolean().optional().catch(undefined), releaseChannel: z.enum(["stable", "beta"]).optional().catch(undefined), }) - .transform((stored) => { + .transform(({ contentMaxWidth, ...stored }) => { const { legacyPullRequestsInSidePane, ...openInSidePane } = stored.openInSidePane; const needsWrite = + contentMaxWidth !== undefined || (stored.uiBaseFontSize === undefined && stored.uiFontSize !== undefined) || stored.contentFontSize === undefined; const uiBaseFontSize = @@ -324,6 +330,7 @@ const StoredAppSettingsSchema = z const chatDisplay = stored.chatDisplay ?? (groupsToolCalls ? "collapseToolCalls" : "full"); return { ...stored, + contentWidth: stored.contentWidth ?? contentMaxWidth ?? "default", openInSidePane, pullRequestOpenLocation: stored.pullRequestOpenLocation ?? (legacyPullRequestsInSidePane ? "side" : "explorer"), @@ -497,12 +504,19 @@ export function parseTerminalScrollbackLines(value: unknown): number | null { ); } -export function parseContentMaxWidth(value: unknown): number | null { - return parseClampedFontSize(value, { min: MIN_CONTENT_MAX_WIDTH, max: MAX_CONTENT_MAX_WIDTH }); -} - -export function resolveContentMaxWidth(settings: Pick): number { - return settings.contentMaxWidth ?? DEFAULT_CONTENT_MAX_WIDTH; +export function resolveContentMaxWidth({ + contentWidth, +}: Pick): number | undefined { + switch (contentWidth) { + case "default": + return DEFAULT_CONTENT_MAX_WIDTH; + case "wide": + return WIDE_CONTENT_MAX_WIDTH; + case "full": + return undefined; + default: + return contentWidth; + } } export function parseClampedFontSize( diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 8050a802ed..a2a16fc3e4 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2711,10 +2711,11 @@ export const ar: TranslationResources = { layout: { title: "التخطيط", contentWidth: "عرض المحتوى", - contentWidthHint: "أقصى عرض للمحادثة وملفات Markdown على الشاشات العريضة", - contentWidthAccessibility: "عرض المحتوى بالبكسل", - reset: "إعادة تعيين", - resetAccessibility: "إعادة عرض المحتوى إلى الافتراضي", + contentWidthHint: "عرض المحادثة ومحرر الرسائل ومعاينات Markdown", + contentWidthDefault: "افتراضي", + contentWidthWide: "عريض", + contentWidthFull: "كامل", + contentWidthCustom: "عرض مخصص · {{width}} بكسل", }, syntax: { title: "بناء الجملة", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 5f916373d4..540e984796 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2806,10 +2806,11 @@ export const en = { layout: { title: "Layout", contentWidth: "Content width", - contentWidthHint: "Max width of chat and Markdown files on wide screens", - contentWidthAccessibility: "Content width in pixels", - reset: "Reset", - resetAccessibility: "Reset content width to default", + contentWidthHint: "Width of chat, composer, and Markdown previews", + contentWidthDefault: "Default", + contentWidthWide: "Wide", + contentWidthFull: "Full", + contentWidthCustom: "Custom width · {{width}} px", }, syntax: { title: "Syntax", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 23fea2743a..cbd4b7ffd0 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2734,10 +2734,11 @@ export const es: TranslationResources = { layout: { title: "Diseño", contentWidth: "Ancho del contenido", - contentWidthHint: "Ancho máximo del chat y de los archivos Markdown en pantallas anchas", - contentWidthAccessibility: "Ancho del contenido en píxeles", - reset: "Restablecer", - resetAccessibility: "Restablecer el ancho del contenido", + contentWidthHint: "Ancho del chat, el campo de mensaje y las vistas previas de Markdown", + contentWidthDefault: "Predeterminado", + contentWidthWide: "Ancho", + contentWidthFull: "Completo", + contentWidthCustom: "Ancho personalizado · {{width}} px", }, syntax: { title: "Sintaxis", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 2d451eed88..d02d9688f5 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2735,11 +2735,11 @@ export const fr: TranslationResources = { layout: { title: "Mise en page", contentWidth: "Largeur du contenu", - contentWidthHint: - "Largeur maximale de la discussion et des fichiers Markdown sur les grands écrans", - contentWidthAccessibility: "Largeur du contenu en pixels", - reset: "Réinitialiser", - resetAccessibility: "Réinitialiser la largeur du contenu", + contentWidthHint: "Largeur du chat, de la zone de saisie et des aperçus Markdown", + contentWidthDefault: "Par défaut", + contentWidthWide: "Large", + contentWidthFull: "Pleine largeur", + contentWidthCustom: "Largeur personnalisée · {{width}} px", }, syntax: { title: "Syntaxe", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 2ba764a894..79630973c4 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2700,10 +2700,11 @@ export const ja: TranslationResources = { layout: { title: "レイアウト", contentWidth: "コンテンツ幅", - contentWidthHint: "ワイド画面でのチャットと Markdown ファイルの最大幅", - contentWidthAccessibility: "コンテンツ幅 (ピクセル)", - reset: "リセット", - resetAccessibility: "コンテンツ幅をデフォルトに戻す", + contentWidthHint: "チャット、入力欄、Markdown プレビューの幅", + contentWidthDefault: "標準", + contentWidthWide: "ワイド", + contentWidthFull: "全幅", + contentWidthCustom: "カスタム幅 · {{width}} px", }, syntax: { title: "構文ハイライト", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index e4988e9a19..eaa4569986 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2690,10 +2690,11 @@ export const ko: TranslationResources = { layout: { title: "레이아웃", contentWidth: "콘텐츠 너비", - contentWidthHint: "와이드 화면에서 채팅과 Markdown 파일의 최대 너비", - contentWidthAccessibility: "콘텐츠 너비(픽셀)", - reset: "재설정", - resetAccessibility: "콘텐츠 너비를 기본값으로 재설정", + contentWidthHint: "채팅, 메시지 입력란, Markdown 미리보기의 너비", + contentWidthDefault: "기본", + contentWidthWide: "넓게", + contentWidthFull: "전체", + contentWidthCustom: "사용자 지정 너비 · {{width}} px", }, syntax: { title: "구문", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index d92dffa1b6..7f3ac5e251 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2714,10 +2714,11 @@ export const ptBR: TranslationResources = { layout: { title: "Layout", contentWidth: "Largura do conteúdo", - contentWidthHint: "Largura máxima do chat e dos arquivos Markdown em telas largas", - contentWidthAccessibility: "Largura do conteúdo em pixels", - reset: "Redefinir", - resetAccessibility: "Redefinir a largura do conteúdo", + contentWidthHint: "Largura do chat, do campo de mensagem e das prévias de Markdown", + contentWidthDefault: "Padrão", + contentWidthWide: "Largo", + contentWidthFull: "Total", + contentWidthCustom: "Largura personalizada · {{width}} px", }, syntax: { title: "Sintaxe", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index cda5ba0121..a200079654 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2722,10 +2722,11 @@ export const ru: TranslationResources = { layout: { title: "Макет", contentWidth: "Ширина содержимого", - contentWidthHint: "Максимальная ширина чата и файлов Markdown на широких экранах", - contentWidthAccessibility: "Ширина содержимого в пикселях", - reset: "Сбросить", - resetAccessibility: "Сбросить ширину содержимого", + contentWidthHint: "Ширина чата, поля ввода и предпросмотра Markdown", + contentWidthDefault: "По умолчанию", + contentWidthWide: "Широкий", + contentWidthFull: "На всю ширину", + contentWidthCustom: "Своя ширина · {{width}} пкс", }, syntax: { title: "Синтаксис", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index e8e59a127e..fc253b1b67 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -2646,10 +2646,11 @@ export const zhCN: TranslationResources = { layout: { title: "布局", contentWidth: "内容宽度", - contentWidthHint: "宽屏上聊天和 Markdown 文件的最大宽度", - contentWidthAccessibility: "内容宽度(像素)", - reset: "重置", - resetAccessibility: "将内容宽度重置为默认值", + contentWidthHint: "聊天、消息输入框和 Markdown 预览的宽度", + contentWidthDefault: "默认", + contentWidthWide: "宽版", + contentWidthFull: "全宽", + contentWidthCustom: "自定义宽度 · {{width}} px", }, syntax: { title: "语法", diff --git a/packages/app/src/screens/settings/appearance/appearance-section.tsx b/packages/app/src/screens/settings/appearance/appearance-section.tsx index 9ff6adccad..3600d97b6d 100644 --- a/packages/app/src/screens/settings/appearance/appearance-section.tsx +++ b/packages/app/src/screens/settings/appearance/appearance-section.tsx @@ -13,7 +13,7 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/component import { DropdownTrigger } from "@/components/ui/dropdown-trigger"; import { SettingsSection } from "@/components/settings/headings/settings-section"; import { ThemePicker } from "@/appearance/theme-picker"; -import { Button } from "@/components/ui/button"; +import { SegmentedControl } from "@/components/ui/segmented-control"; import { EditingTextInput, type EditingTextInputHandle } from "@/components/ui/text-input"; import { MAX_CODE_FONT_SIZE, @@ -23,11 +23,10 @@ import { MIN_CONTENT_FONT_SIZE, MIN_UI_BASE_FONT_SIZE, parseClampedFontSize, - parseContentMaxWidth, - resolveContentMaxWidth, sanitizeFontFamily, useAppSettings, type AppSettings, + type ContentWidthPreset, } from "@/hooks/use-settings"; import { DEFAULT_MONO_FONT_STACK, DEFAULT_UI_FONT_STACK } from "@/styles/theme"; import { isNative } from "@/constants/platform"; @@ -172,68 +171,35 @@ function FontSizeRow({ } // --------------------------------------------------------------------------- -// Content width: numeric field (commit on blur/submit) + reset to the default -// --------------------------------------------------------------------------- - -interface ContentWidthRowProps { - value: AppSettings["contentMaxWidth"]; - onChange: (value: AppSettings["contentMaxWidth"]) => void; -} - -function ContentWidthRow({ value, onChange }: ContentWidthRowProps) { +function ContentWidthRow({ + value, + onChange, +}: { + value: AppSettings["contentWidth"]; + onChange: (value: ContentWidthPreset) => void; +}) { const { t } = useTranslation(); - const width = resolveContentMaxWidth({ contentMaxWidth: value }); - // The field is uncontrolled, so a saved or reset width is written into it directly. - const input = useRef(null); - - useEffect(() => { - input.current?.replaceText(String(width)); - }, [width]); - - const commit = useCallback(() => { - const next = parseContentMaxWidth(input.current?.getText()) ?? width; - input.current?.replaceText(String(next)); - // Typing the width already in effect keeps following the default. - if (next !== width) { - onChange(next); - } - }, [onChange, width]); - - const reset = useCallback(() => { - onChange(null); - }, [onChange]); return ( - - + + {t("settings.appearance.layout.contentWidth")} - {t("settings.appearance.layout.contentWidthHint")} + {typeof value === "number" + ? t("settings.appearance.layout.contentWidthCustom", { width: value }) + : t("settings.appearance.layout.contentWidthHint")} - - {value === null ? null : ( - - )} - - px - + + testID="content-width-options" + value={typeof value === "number" ? null : value} + onValueChange={onChange} + options={[ + { value: "default", label: t("settings.appearance.layout.contentWidthDefault") }, + { value: "wide", label: t("settings.appearance.layout.contentWidthWide") }, + { value: "full", label: t("settings.appearance.layout.contentWidthFull") }, + ]} + /> ); } @@ -333,9 +299,9 @@ export function AppearanceSection() { setCodeSizeDraft(String(settings.codeFontSize)); }, [settings.codeFontSize]); - const handleContentMaxWidthChange = useCallback( - (contentMaxWidth: AppSettings["contentMaxWidth"]) => { - void updateSettings({ contentMaxWidth }); + const handleContentWidthChange = useCallback( + (contentWidth: ContentWidthPreset) => { + void updateSettings({ contentWidth }); }, [updateSettings], ); @@ -504,10 +470,7 @@ export function AppearanceSection() { - + @@ -571,18 +534,10 @@ const styles = StyleSheet.create((theme) => ({ fontSize: theme.fontSize.base, textAlign: "right", }, - widthInput: { - width: 80, - minHeight: 36, - paddingVertical: theme.spacing[2], - paddingHorizontal: theme.spacing[3], - borderRadius: theme.borderRadius.md, - borderWidth: theme.borderWidth[1], - borderColor: theme.colors.border, - backgroundColor: theme.colors.surface2, - color: theme.colors.foreground, - fontSize: theme.fontSize.base, - textAlign: "right", + contentWidthRow: { + alignItems: "flex-start", + gap: theme.spacing[2], + padding: theme.spacing[4], }, unit: { color: theme.colors.foregroundMuted, diff --git a/packages/app/src/styles/theme.ts b/packages/app/src/styles/theme.ts index f90594fa55..a1bff0292b 100644 --- a/packages/app/src/styles/theme.ts +++ b/packages/app/src/styles/theme.ts @@ -1,4 +1,5 @@ -import { Platform } from "react-native"; +import { Platform, type ViewStyle } from "react-native"; +import { isWeb } from "@/constants/platform"; import { darkHighlightColors, lightHighlightColors } from "@getpaseo/highlight"; import { deriveSurfaceStates } from "./derive-colors"; @@ -641,6 +642,17 @@ export const DEFAULT_MONO_FONT_STACK: string = Platform.select({ // Chat and markdown content column; the appearance updater patches the user's width in. export const DEFAULT_CONTENT_MAX_WIDTH = 820; +// On web Unistyles puts string tokens in CSS variables, so mounted content +// receives width changes without regenerating its classes. The px string is +// emitted as CSS by Unistyles. Native always receives a number or percentage. +export function themeContentMaxWidth( + width: number | undefined, +): NonNullable { + return isWeb && width !== undefined + ? (`${width}px` as NonNullable) + : (width ?? "100%"); +} + // `fontSize`, `fontFamily`, `lineHeight`, and `contentMaxWidth` are deliberately widened to plain // `number`/`string` (not narrowed by `as const`) so the appearance updater can patch // them at runtime via `UnistylesRuntime.updateTheme`. The remaining tokens keep their @@ -650,7 +662,7 @@ interface CommonTheme { fontSize: Record; fontFamily: { ui: string; mono: string }; lineHeight: Record; - contentMaxWidth: number; + contentMaxWidth: ReturnType; iconSize: typeof ICON_SIZE; fontWeight: typeof FONT_WEIGHT; borderRadius: typeof BORDER_RADIUS; @@ -663,7 +675,7 @@ const commonTheme: CommonTheme = { fontSize: FONT_SIZE, fontFamily: { ui: DEFAULT_UI_FONT_STACK, mono: DEFAULT_MONO_FONT_STACK }, lineHeight: LINE_HEIGHT, - contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH, + contentMaxWidth: themeContentMaxWidth(DEFAULT_CONTENT_MAX_WIDTH), iconSize: ICON_SIZE, fontWeight: FONT_WEIGHT, borderRadius: BORDER_RADIUS,