diff --git a/apps/web/src/components/ChatMarkdown.browser.tsx b/apps/web/src/components/ChatMarkdown.browser.tsx index 23b84665c1..570c6dd498 100644 --- a/apps/web/src/components/ChatMarkdown.browser.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.tsx @@ -303,6 +303,13 @@ describe("ChatMarkdown", () => { ).toMatchObject({ isOpen: true, activeSurfaceId: "file:apps/web/src/components/ChatMarkdown.tsx", + surfaces: [ + expect.objectContaining({ + relativePath: "apps/web/src/components/ChatMarkdown.tsx", + revealLine: 978, + revealRequestId: 1, + }), + ], }); expect(openInPreferredEditorMock).not.toHaveBeenCalled(); expect(openFileInPreviewMock).not.toHaveBeenCalled(); diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 225e8e1dfc..1d18a96f6e 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -678,6 +678,7 @@ interface MarkdownFileLinkProps { iconPath: string; displayPath: string; workspaceRelativePath: string | null; + line?: number | undefined; label: string; copyMarkdown: string; theme: "light" | "dark"; @@ -956,6 +957,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({ iconPath, displayPath, workspaceRelativePath, + line, label, copyMarkdown, theme, @@ -981,8 +983,8 @@ const MarkdownFileLink = memo(function MarkdownFileLink({ handleOpenInEditor(); return; } - useRightPanelStore.getState().openFile(threadRef, workspaceRelativePath); - }, [handleOpenInEditor, threadRef, workspaceRelativePath]); + useRightPanelStore.getState().openFile(threadRef, workspaceRelativePath, line); + }, [handleOpenInEditor, line, threadRef, workspaceRelativePath]); const handleOpenInBrowser = useCallback(() => { void onOpenInBrowser?.().catch((error) => { @@ -1112,6 +1114,7 @@ function areMarkdownFileLinkPropsEqual( previous.iconPath === next.iconPath && previous.displayPath === next.displayPath && previous.workspaceRelativePath === next.workspaceRelativePath && + previous.line === next.line && previous.label === next.label && previous.copyMarkdown === next.copyMarkdown && previous.theme === next.theme && @@ -1330,6 +1333,7 @@ function ChatMarkdown({ iconPath={fileLinkMeta.filePath} displayPath={fileLinkMeta.displayPath} workspaceRelativePath={fileLinkMeta.workspaceRelativePath} + line={fileLinkMeta.line} label={labelParts.join(" ยท ")} copyMarkdown={`[${fileLinkMeta.basename}](${normalizedHref})`} theme={resolvedTheme} diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 1dca769788..c7a513df0f 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -2373,16 +2373,19 @@ describe("ChatView timeline estimator parity (full app)", () => { try { await waitForElement( - () => document.querySelector('button[aria-label="Close plan sidebar"]'), + () => + Array.from(document.querySelectorAll("button")).find( + (element) => element.textContent?.trim() === "Ship plan mode follow-up", + ) ?? null, "Unable to find persisted plan surface content.", ); for (const viewport of [WIDE_FOOTER_VIEWPORT, COMPACT_FOOTER_VIEWPORT]) { await mounted.setViewport(viewport); await vi.waitFor(() => { - expect( - document.querySelectorAll('button[aria-label="Close plan sidebar"]'), - ).toHaveLength(1); expect(document.body.textContent).toContain("Ship plan mode follow-up"); + expect( + document.querySelector("[data-right-panel-tabbar]")?.textContent, + ).toContain("Plan"); }); expect( selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF), diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index b416b8f3ec..a1caff4ca4 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -184,7 +184,7 @@ import { ExpandedImageDialog } from "./chat/ExpandedImageDialog"; import { PullRequestThreadDialog } from "./PullRequestThreadDialog"; import { MessagesTimeline } from "./chat/MessagesTimeline"; import { ChatHeader } from "./chat/ChatHeader"; -import { PanelLayoutControls } from "./chat/PanelLayoutControls"; +import { PanelLayoutControls, RightPanelMaximizeControl } from "./chat/PanelLayoutControls"; import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview"; import { NoActiveThreadState } from "./NoActiveThreadState"; import { resolveEffectiveEnvMode } from "./BranchToolbar.logic"; @@ -1126,7 +1126,6 @@ function ChatViewContent(props: ChatViewProps) { >({}); const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] = useState>({}); - const [planSidebarOpen, setPlanSidebarOpen] = useState(false); const shouldUsePlanSidebarSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY); // Tracks whether the user explicitly dismissed the sidebar for the active turn. const planSidebarDismissedForTurnRef = useRef(null); @@ -1278,6 +1277,8 @@ function ChatViewContent(props: ChatViewProps) { const activeRightPanelSurface = useRightPanelStore((state) => selectActiveRightPanelSurface(state.byThreadKey, activeThreadRef), ); + const activeFileSurface = + activeRightPanelSurface?.kind === "file" ? activeRightPanelSurface : null; const activePreviewState = usePreviewStateStore((state) => selectThreadPreviewState(state.byThreadKey, activeThreadRef), ); @@ -1296,7 +1297,6 @@ function ChatViewContent(props: ChatViewProps) { ); const previewPanelOpen = activeRightPanelKind === "preview" && isPreviewSupportedInRuntime(); const rightPanelOpen = rightPanelState.isOpen; - const rightPanelPlanOpen = rightPanelOpen && activeRightPanelSurface?.kind === "plan"; const canMaximizeRightPanel = rightPanelOpen && !shouldUsePlanSidebarSheet; const rightPanelMaximized = canMaximizeRightPanel && maximizedRightPanelThreadKey === routeThreadKey; @@ -1331,6 +1331,7 @@ function ChatViewContent(props: ChatViewProps) { reconcileTerminalIds, terminalUiState.terminalIds, ]); + const planSidebarOpen = activeRightPanelKind === "plan"; useEffect(() => { if (!activeThreadRef || !diffOpen) return; @@ -2708,23 +2709,25 @@ function ChatViewContent(props: ChatViewProps) { const toggleInteractionMode = useCallback(() => { handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan"); }, [handleInteractionModeChange, interactionMode]); - const togglePlanSidebar = useCallback(() => { - setPlanSidebarOpen((open) => { - if (open) { - planSidebarDismissedForTurnRef.current = - activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__"; - } else { - planSidebarDismissedForTurnRef.current = null; - } - return !open; - }); - }, [activePlan?.turnId, sidebarProposedPlan?.turnId]); - const closePlanSidebar = useCallback(() => { - setMaximizedRightPanelThreadKey(null); - setPlanSidebarOpen(false); + const dismissPlanSidebarForCurrentTurn = useCallback(() => { planSidebarDismissedForTurnRef.current = activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__"; }, [activePlan?.turnId, sidebarProposedPlan?.turnId]); + const togglePlanSidebar = useCallback(() => { + if (!activeThreadRef) return; + if (planSidebarOpen) { + dismissPlanSidebarForCurrentTurn(); + } else { + planSidebarDismissedForTurnRef.current = null; + } + useRightPanelStore.getState().toggle(activeThreadRef, "plan"); + }, [activeThreadRef, dismissPlanSidebarForCurrentTurn, planSidebarOpen]); + const closePlanSidebar = useCallback(() => { + if (!activeThreadRef) return; + setMaximizedRightPanelThreadKey(null); + useRightPanelStore.getState().close(activeThreadRef); + dismissPlanSidebarForCurrentTurn(); + }, [activeThreadRef, dismissPlanSidebarForCurrentTurn]); const createBrowserSurface = useCallback(() => { if (!activeThreadRef) return; const activeTabId = activePreviewState.activeTabId; @@ -2904,6 +2907,11 @@ function ChatViewContent(props: ChatViewProps) { const activateRightPanelSurface = useCallback( (surface: RightPanelSurface) => { if (!activeThreadRef) return; + if (surface.kind === "plan") { + planSidebarDismissedForTurnRef.current = null; + } else if (planSidebarOpen) { + dismissPlanSidebarForCurrentTurn(); + } useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id); if (surface.kind === "preview" && surface.resourceId) { usePreviewStateStore.getState().setActiveTab(activeThreadRef, surface.resourceId); @@ -2928,13 +2936,29 @@ function ChatViewContent(props: ChatViewProps) { }); } }, - [activeThreadRef, diffOpen, environmentId, navigate, onDiffPanelOpen, threadId], + [ + activeThreadRef, + diffOpen, + dismissPlanSidebarForCurrentTurn, + environmentId, + navigate, + onDiffPanelOpen, + planSidebarOpen, + threadId, + ], ); const toggleRightPanel = useCallback(() => { if (!activeThreadRef) return; - if (rightPanelOpen) setMaximizedRightPanelThreadKey(null); + if (rightPanelOpen) { + if (planSidebarOpen) { + closePlanSidebar(); + } else { + closePreviewPanel(); + } + return; + } useRightPanelStore.getState().toggleVisibility(activeThreadRef); - }, [activeThreadRef, rightPanelOpen]); + }, [activeThreadRef, closePlanSidebar, closePreviewPanel, planSidebarOpen, rightPanelOpen]); const toggleRightPanelMaximized = useCallback(() => { if (!canMaximizeRightPanel) return; setMaximizedRightPanelThreadKey((threadKey) => @@ -2944,6 +2968,9 @@ function ChatViewContent(props: ChatViewProps) { const cleanupRightPanelSurfaces = useCallback( (surfaces: readonly RightPanelSurface[]) => { if (!activeThreadRef) return; + if (surfaces.some((surface) => surface.kind === "plan")) { + dismissPlanSidebarForCurrentTurn(); + } for (const surface of surfaces) { if (surface.kind === "preview" && surface.resourceId) { @@ -2962,10 +2989,6 @@ function ChatViewContent(props: ChatViewProps) { } } } - if (surfaces.some((surface) => surface.kind === "plan")) { - closePlanSidebar(); - } - if (diffOpen && surfaces.some((surface) => surface.kind === "diff")) { void navigate({ to: "/$environmentId/$threadId", @@ -2978,9 +3001,9 @@ function ChatViewContent(props: ChatViewProps) { [ activeThreadRef, closePreview, - closePlanSidebar, closeTerminalMutation, diffOpen, + dismissPlanSidebarForCurrentTurn, environmentId, navigate, threadId, @@ -3168,12 +3191,13 @@ function ChatViewContent(props: ChatViewProps) { setShowScrollToBottom(false); if (planSidebarOpenOnNextThreadRef.current) { planSidebarOpenOnNextThreadRef.current = false; - setPlanSidebarOpen(true); - } else { - planSidebarOpenOnNextThreadRef.current = false; - setPlanSidebarOpen(false); + if (activeThreadRef) { + useRightPanelStore.getState().open(activeThreadRef, "plan"); + } } planSidebarDismissedForTurnRef.current = null; + // activeThreadRef resets transitively with the active thread. + // eslint-disable-next-line react-hooks/exhaustive-deps }, [activeThread?.id]); // Auto-open the plan sidebar when plan/todo steps arrive for the current turn. @@ -3186,10 +3210,13 @@ function ChatViewContent(props: ChatViewProps) { if (latestTurnId && activePlan.turnId !== latestTurnId) return; const turnKey = activePlan.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__"; if (planSidebarDismissedForTurnRef.current === turnKey) return; - setPlanSidebarOpen(true); + if (activeThreadRef) { + useRightPanelStore.getState().open(activeThreadRef, "plan"); + } }, [ activePlan, activeLatestTurn?.turnId, + activeThreadRef, autoOpenPlanSidebar, planSidebarOpen, sidebarProposedPlan?.turnId, @@ -4170,7 +4197,9 @@ function ChatViewContent(props: ChatViewProps) { // step-tracking activities that the sidebar will display. if (nextInteractionMode === "default" && autoOpenPlanSidebar) { planSidebarDismissedForTurnRef.current = null; - setPlanSidebarOpen(true); + if (activeThreadRef) { + useRightPanelStore.getState().open(activeThreadRef, "plan"); + } } sendInFlightRef.current = false; } catch (err) { @@ -4505,24 +4534,105 @@ function ChatViewContent(props: ChatViewProps) { return ; } + const panelToggleControls = ( + + ); + const panelLayoutControls = ( +
+ {rightPanelOpen && !shouldUsePlanSidebarSheet ? ( + + ) : null} + {panelToggleControls} +
+ ); + const rightPanelContent = activeThreadRef ? ( + activeRightPanelSurface?.kind === "preview" ? ( + + + + ) : activeRightPanelSurface?.kind === "terminal" ? ( + + ) : activeRightPanelSurface?.kind === "diff" ? ( + + + + ) : activeRightPanelSurface?.kind === "plan" ? ( + + ) : (activeRightPanelSurface?.kind === "files" || activeRightPanelSurface?.kind === "file") && + activeProject && + activeWorkspaceRoot ? ( + + + + ) : null + ) : null; + return (
{isElectron && activeThreadRef ? ( ) : null} - + {rightPanelOpen && !shouldUsePlanSidebarSheet ? panelLayoutControls : null}
{/* Top bar */}
+ {!rightPanelOpen ? panelLayoutControls : null}
@@ -4752,21 +4859,6 @@ function ChatViewContent(props: ChatViewProps) { ) : null}
{/* end chat column */} - - {/* Plan sidebar */} - {planSidebarOpen && !rightPanelPlanOpen && !shouldUsePlanSidebarSheet ? ( - - ) : null}
{/* end horizontal flex container */} @@ -4788,21 +4880,6 @@ function ChatViewContent(props: ChatViewProps) { onAddTerminalContext={addTerminalContextToDraft} /> ))} - {shouldUsePlanSidebarSheet && !rightPanelPlanOpen ? ( - - - - ) : null} {!shouldUsePlanSidebarSheet && rightPanelOpen && activeThreadRef ? ( @@ -4828,81 +4905,14 @@ function ChatViewContent(props: ChatViewProps) { diffAvailable={isServerThread && isGitRepo} filesAvailable={activeProject !== null} > - {activeRightPanelSurface?.kind === "preview" ? ( - - - - ) : activeRightPanelSurface?.kind === "terminal" ? ( - - ) : activeRightPanelSurface?.kind === "diff" ? ( - - - - - - ) : activeRightPanelSurface?.kind === "plan" ? ( - closeRightPanelSurface(activeRightPanelSurface)} - /> - ) : (activeRightPanelSurface?.kind === "files" || - activeRightPanelSurface?.kind === "file") && - activeProject ? ( - - - - ) : null} + {rightPanelContent} ) : null} {shouldUsePlanSidebarSheet && rightPanelOpen && activeThreadRef ? ( - + - {activeRightPanelSurface?.kind === "preview" ? ( - - - - ) : activeRightPanelSurface?.kind === "terminal" ? ( - - ) : activeRightPanelSurface?.kind === "diff" ? ( - - - - - - ) : activeRightPanelSurface?.kind === "plan" ? ( - closeRightPanelSurface(activeRightPanelSurface)} - /> - ) : (activeRightPanelSurface?.kind === "files" || - activeRightPanelSurface?.kind === "file") && - activeProject ? ( - - - - ) : null} + {rightPanelContent} ) : null} diff --git a/apps/web/src/components/PlanSidebar.tsx b/apps/web/src/components/PlanSidebar.tsx index eb9a60055f..a029479842 100644 --- a/apps/web/src/components/PlanSidebar.tsx +++ b/apps/web/src/components/PlanSidebar.tsx @@ -1,6 +1,6 @@ import { memo, useState, useCallback } from "react"; import { useAtomSet } from "@effect/atom-react"; -import type { EnvironmentId } from "@t3tools/contracts"; +import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; import { type TimestampFormat } from "@t3tools/contracts/settings"; import { Badge } from "./ui/badge"; import { Button } from "./ui/button"; @@ -12,7 +12,6 @@ import { ChevronRightIcon, EllipsisIcon, LoaderIcon, - PanelRightCloseIcon, } from "lucide-react"; import { cn } from "~/lib/utils"; import type { ActivePlanState } from "../session-logic"; @@ -57,11 +56,11 @@ interface PlanSidebarProps { activeProposedPlan: LatestProposedPlanState | null; label?: string; environmentId: EnvironmentId; + threadRef?: ScopedThreadRef | undefined; markdownCwd: string | undefined; workspaceRoot: string | undefined; timestampFormat: TimestampFormat; - mode?: "sheet" | "sidebar"; - onClose: () => void; + mode?: "sheet" | "sidebar" | "embedded"; } const PlanSidebar = memo(function PlanSidebar({ @@ -69,11 +68,11 @@ const PlanSidebar = memo(function PlanSidebar({ activeProposedPlan, label = "Plan", environmentId, + threadRef, markdownCwd, workspaceRoot, timestampFormat, mode = "sidebar", - onClose, }: PlanSidebarProps) { const [proposedPlanExpanded, setProposedPlanExpanded] = useState(false); const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false); @@ -183,15 +182,6 @@ const PlanSidebar = memo(function PlanSidebar({ ) : null} - @@ -260,6 +250,7 @@ const PlanSidebar = memo(function PlanSidebar({ diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index b5c419a088..ead306f7c9 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -27,6 +27,7 @@ import { PierreEntryIcon } from "./chat/PierreEntryIcon"; interface RightPanelTabsProps { mode: PreviewPanelMode; maximized?: boolean; + layoutControls?: ReactNode; surfaces: readonly RightPanelSurface[]; activeSurfaceId: string | null; pendingSurfaceIds: ReadonlySet; @@ -342,8 +343,8 @@ export function RightPanelTabs(props: RightPanelTabsProps) { >
+ {props.layoutControls}
{props.activeSurfaceId === null ? ( diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index ffb87a27c6..eb3d417d7c 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -88,15 +88,15 @@ export const ChatHeader = memo(function ChatHeader({ const rightPanelShortcutLabel = shortcutLabelForCommand(keybindings, "rightPanel.toggle"); return ( -
-
+
+
{activeThreadTitle} @@ -108,7 +108,7 @@ export const ChatHeader = memo(function ChatHeader({
diff --git a/apps/web/src/components/chat/PanelLayoutControls.tsx b/apps/web/src/components/chat/PanelLayoutControls.tsx index 3b7fbf4ad9..deb7b3ee9a 100644 --- a/apps/web/src/components/chat/PanelLayoutControls.tsx +++ b/apps/web/src/components/chat/PanelLayoutControls.tsx @@ -1,8 +1,6 @@ import { Maximize2Icon, Minimize2Icon, PanelBottomIcon, PanelRightIcon } from "lucide-react"; import { memo } from "react"; -import { cn } from "~/lib/utils"; - import { Toggle } from "../ui/toggle"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -13,11 +11,8 @@ interface PanelLayoutControlsProps { rightPanelAvailable: boolean; rightPanelOpen: boolean; rightPanelShortcutLabel: string | null; - rightPanelMaximized: boolean; - canMaximizeRightPanel: boolean; onToggleTerminal: () => void; onToggleRightPanel: () => void; - onToggleRightPanelMaximized: () => void; } export const PanelLayoutControls = memo(function PanelLayoutControls({ @@ -27,47 +22,14 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({ rightPanelAvailable, rightPanelOpen, rightPanelShortcutLabel, - rightPanelMaximized, - canMaximizeRightPanel, onToggleTerminal, onToggleRightPanel, - onToggleRightPanelMaximized, }: PanelLayoutControlsProps) { return (
- {rightPanelOpen ? ( - - - {rightPanelMaximized ? ( - - ) : ( - - )} - - } - /> - - {canMaximizeRightPanel - ? rightPanelMaximized - ? "Restore panel size" - : "Maximize panel" - : "Panel maximization is unavailable at this width"} - - - ) : null} ); }); + +export const RightPanelMaximizeControl = memo(function RightPanelMaximizeControl({ + maximized, + onToggle, +}: { + maximized: boolean; + onToggle: () => void; +}) { + const label = maximized ? "Restore panel size" : "Maximize panel"; + return ( + + + {maximized ? ( + + ) : ( + + )} + + } + /> + {label} + + ); +}); diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index aa84b7402d..4125be17a2 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -4,10 +4,10 @@ import type { ResolvedKeybindingsConfig, ScopedThreadRef, } from "@t3tools/contracts"; -import type { SelectedLineRange } from "@pierre/diffs"; +import { VirtualizedFile, type SelectedLineRange } from "@pierre/diffs"; import { Editor } from "@pierre/diffs/editor"; -import { EditorProvider, File, Virtualizer } from "@pierre/diffs/react"; import { useAtomSet } from "@effect/atom-react"; +import { EditorProvider, File, type FileOptions, Virtualizer } from "@pierre/diffs/react"; import { ChevronRight, Code2, Eye, FolderTree, Globe2, LoaderCircle } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -62,12 +62,176 @@ interface FilePreviewPanelProps { composerDraftTarget: ScopedThreadRef | DraftId; keybindings: ResolvedKeybindingsConfig; availableEditors: ReadonlyArray; + revealLine: number | null; + revealRequestId: number; onOpenFile: (relativePath: string) => void; onPendingChange: (relativePath: string, pending: boolean) => void; } const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen"; const FILE_SAVE_DEBOUNCE_MS = 500; +const FILE_LINK_REVEAL_ATTRIBUTE = "data-file-link-reveal"; +const FILE_LINK_REVEAL_UNSAFE_CSS = ` + [${FILE_LINK_REVEAL_ATTRIBUTE}][data-line] { + background-color: light-dark( + color-mix( + in lab, + var(--diffs-computed-diff-line-bg) 82%, + var(--diffs-bg-selection-override, var(--diffs-selection-base)) + ), + color-mix( + in lab, + var(--diffs-computed-diff-line-bg) 75%, + var(--diffs-bg-selection-override, var(--diffs-selection-base)) + ) + ) !important; + } + + [${FILE_LINK_REVEAL_ATTRIBUTE}][data-column-number] { + background-color: light-dark( + color-mix( + in lab, + var(--diffs-computed-diff-line-bg) 75%, + var(--diffs-bg-selection-number-override, var(--diffs-selection-base)) + ), + color-mix( + in lab, + var(--diffs-computed-diff-line-bg) 60%, + var(--diffs-bg-selection-number-override, var(--diffs-selection-base)) + ) + ) !important; + color: var(--diffs-selection-number-fg) !important; + } +`; +type FilePostRender = NonNullable["onPostRender"]>; + +function clampFileLine(contents: string, requestedLine: number): number { + let lineCount = 1; + for (let index = 0; index < contents.length; index += 1) { + const character = contents.charCodeAt(index); + if (character === 10) { + lineCount += 1; + } else if (character === 13) { + lineCount += 1; + if (contents.charCodeAt(index + 1) === 10) index += 1; + } + } + return Math.min(Math.max(1, requestedLine), lineCount); +} + +function updateFileLinkReveal(fileContainer: HTMLElement, line: number | null): void { + const root = fileContainer.shadowRoot ?? fileContainer; + for (const element of root.querySelectorAll(`[${FILE_LINK_REVEAL_ATTRIBUTE}]`)) { + element.removeAttribute(FILE_LINK_REVEAL_ATTRIBUTE); + } + if (line === null) return; + + root + .querySelector(`[data-line="${line}"]`) + ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, ""); + root + .querySelector(`[data-column-number="${line}"]`) + ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, ""); +} + +function useFileLineReveal( + relativePath: string | null, + revealLine: number | null, + revealRequestId: number, +): FilePostRender { + const [handledRequestIdsByPath] = useState(() => new Map()); + const [latestRequestIdsByPath] = useState(() => new Map()); + const [pendingFramesByPath] = useState(() => new Map()); + + return useCallback( + (fileContainer, instance, phase) => { + if (relativePath === null) return; + + const cancelPendingReveal = () => { + const frameId = pendingFramesByPath.get(relativePath); + if (frameId !== undefined) { + cancelAnimationFrame(frameId); + pendingFramesByPath.delete(relativePath); + } + }; + + if (phase === "unmount") { + cancelPendingReveal(); + return; + } + + const targetLine = + revealLine === null ? null : clampFileLine(instance.file?.contents ?? "", revealLine); + updateFileLinkReveal(fileContainer, targetLine); + + if (!(instance instanceof VirtualizedFile)) return; + + if (latestRequestIdsByPath.get(relativePath) !== revealRequestId) { + cancelPendingReveal(); + latestRequestIdsByPath.set(relativePath, revealRequestId); + } + + if (targetLine === null) { + fileContainer.style.minHeight = ""; + return; + } + + const scrollContainer = fileContainer.closest(".file-preview-virtualizer"); + if (!scrollContainer) return; + fileContainer.style.minHeight = `${Math.ceil( + Math.max(instance.height, scrollContainer.clientHeight), + )}px`; + + if ( + handledRequestIdsByPath.get(relativePath) === revealRequestId || + pendingFramesByPath.has(relativePath) + ) { + return; + } + + const reveal = () => { + pendingFramesByPath.delete(relativePath); + if ( + latestRequestIdsByPath.get(relativePath) !== revealRequestId || + !fileContainer.isConnected + ) { + return; + } + + const linePosition = instance.getLinePosition(targetLine); + if (!linePosition) return; + + const fileTop = + scrollContainer.scrollTop + + fileContainer.getBoundingClientRect().top - + scrollContainer.getBoundingClientRect().top; + const centeredTop = Math.max( + 0, + fileTop + + linePosition.top - + Math.max(0, (scrollContainer.clientHeight - linePosition.height) / 2), + ); + const maxScrollTop = Math.max( + 0, + scrollContainer.scrollHeight - scrollContainer.clientHeight, + ); + + scrollContainer.scrollTop = Math.min(centeredTop, maxScrollTop); + handledRequestIdsByPath.set(relativePath, revealRequestId); + }; + + pendingFramesByPath.set(relativePath, requestAnimationFrame(reveal)); + }, + [ + handledRequestIdsByPath, + latestRequestIdsByPath, + pendingFramesByPath, + relativePath, + revealLine, + revealRequestId, + ], + ); +} interface EditableFileSurfaceProps { environmentId: EnvironmentId; @@ -76,9 +240,16 @@ interface EditableFileSurfaceProps { composerDraftTarget: ScopedThreadRef | DraftId; contents: string; resolvedTheme: "light" | "dark"; + revealRequestId: number; + onPostRender: FilePostRender; onPendingChange: (relativePath: string, pending: boolean) => void; } +interface FileSelectionOverride { + revealRequestId: number; + range: SelectedLineRange | null; +} + function useFileSaveCoordinator({ environmentId, cwd, @@ -118,13 +289,24 @@ function EditableFileSurface({ composerDraftTarget, contents, resolvedTheme, + revealRequestId, + onPostRender, onPendingChange, }: EditableFileSurfaceProps) { const addReviewComment = useComposerDraftStore((store) => store.addReviewComment); const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment); const [lineAnnotations, setLineAnnotations] = useState([]); - const [selectedRange, setSelectedRange] = useState(null); + const [selectionOverride, setSelectionOverride] = useState(null); + const selectedRange = + selectionOverride?.revealRequestId === revealRequestId ? selectionOverride.range : null; + const setSelectedRange = useCallback( + (range: SelectedLineRange | null) => { + setSelectionOverride({ revealRequestId, range }); + }, + [revealRequestId], + ); const surfaceRef = useRef(null); + const selectionFrameRef = useRef(null); const saveCoordinator = useFileSaveCoordinator({ environmentId, cwd, @@ -182,7 +364,7 @@ function EditableFileSurface({ }); }); }, - [composerDraftTarget, removeReviewComment], + [composerDraftTarget, removeReviewComment, setSelectedRange], ); const submitAnnotationEntry = useCallback( @@ -217,7 +399,14 @@ function EditableFileSurface({ })), ); }, - [addReviewComment, composerDraftTarget, contents, lineAnnotations, relativePath], + [ + addReviewComment, + composerDraftTarget, + contents, + lineAnnotations, + relativePath, + setSelectedRange, + ], ); const beginComment = useCallback((range: SelectedLineRange) => { @@ -268,7 +457,7 @@ function EditableFileSurface({ isBlocked: () => hasOpenCommentForm, onDismiss: () => setSelectedRange(null), }); - }, [editor, hasOpenCommentForm]); + }, [editor, hasOpenCommentForm, setSelectedRange]); const handleLineSelectionEnd = useCallback( (range: SelectedLineRange | null) => { setSelectedRange(range); @@ -276,7 +465,26 @@ function EditableFileSurface({ beginComment(range); } }, - [beginComment], + [beginComment, setSelectedRange], + ); + + const handlePostRender = useCallback( + (fileContainer, instance, phase) => { + onPostRender(fileContainer, instance, phase); + + if (selectionFrameRef.current !== null) { + cancelAnimationFrame(selectionFrameRef.current); + selectionFrameRef.current = null; + } + if (phase === "unmount") return; + + selectionFrameRef.current = requestAnimationFrame(() => { + selectionFrameRef.current = null; + if (!fileContainer.isConnected) return; + instance.setSelectedLines(selectedRange, { notify: false }); + }); + }, + [onPostRender, selectedRange], ); return ( @@ -305,6 +513,8 @@ function EditableFileSurface({ overflow: "scroll", theme: resolveDiffThemeName(resolvedTheme), themeType: resolvedTheme, + unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS, + onPostRender: handlePostRender, }} selectedLines={selectedRange} lineAnnotations={lineAnnotations} @@ -339,7 +549,10 @@ function RenderedMarkdownSurface({ contents, threadRef, onPendingChange, -}: Omit & { +}: Omit< + EditableFileSurfaceProps, + "resolvedTheme" | "composerDraftTarget" | "revealLine" | "revealRequestId" | "onPostRender" +> & { threadRef: ScopedThreadRef; }) { const saveCoordinator = useFileSaveCoordinator({ @@ -387,6 +600,8 @@ export default function FilePreviewPanel({ composerDraftTarget, keybindings, availableEditors, + revealLine, + revealRequestId, onOpenFile, onPendingChange, }: FilePreviewPanelProps) { @@ -397,10 +612,16 @@ export default function FilePreviewPanel({ const { open: openPreview } = usePreviewActions(); const file = useProjectFileQuery(environmentId, cwd, relativePath); const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen); - const [renderedMarkdownPath, setRenderedMarkdownPath] = useState(null); + const [markdownView, setMarkdownView] = useState<{ + path: string | null; + revealRequestId: number | null; + }>({ path: null, revealRequestId: null }); const breadcrumbRef = useRef(null); const isMarkdown = relativePath ? isMarkdownPreviewFile(relativePath) : false; - const renderMarkdown = isMarkdown && renderedMarkdownPath === relativePath; + const renderMarkdown = + isMarkdown && + markdownView.path === relativePath && + (revealLine === null || markdownView.revealRequestId === revealRequestId); const canOpenInBrowser = relativePath !== null && isPreviewSupportedInRuntime() && isBrowserPreviewFile(relativePath); const absolutePath = relativePath ? resolvePathLinkTarget(relativePath, cwd) : null; @@ -408,6 +629,7 @@ export default function FilePreviewPanel({ () => (relativePath ? fileBreadcrumbs(projectName, relativePath) : []), [projectName, relativePath], ); + const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId); useEffect(() => { const currentCrumb = breadcrumbRef.current?.querySelector( @@ -498,9 +720,12 @@ export default function FilePreviewPanel({ - setRenderedMarkdownPath(pressed ? relativePath : null) - } + onPressedChange={(pressed) => { + setMarkdownView({ + path: pressed ? relativePath : null, + revealRequestId: pressed ? revealRequestId : null, + }); + }} aria-label={renderMarkdown ? "Show markdown source" : "Show rendered markdown"} variant="ghost" size="sm" @@ -604,6 +829,8 @@ export default function FilePreviewPanel({ overflow: "scroll", theme: resolveDiffThemeName(resolvedTheme), themeType: resolvedTheme, + unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS, + onPostRender: onFilePostRender, }} className="min-h-full" /> @@ -617,6 +844,8 @@ export default function FilePreviewPanel({ composerDraftTarget={composerDraftTarget} contents={file.data.contents} resolvedTheme={resolvedTheme} + revealRequestId={revealRequestId} + onPostRender={onFilePostRender} onPendingChange={onPendingChange} /> ) diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.ts index 1c51c8e89e..3b6dcc347e 100644 --- a/apps/web/src/rightPanelStore.test.ts +++ b/apps/web/src/rightPanelStore.test.ts @@ -73,6 +73,36 @@ describe("rightPanelStore", () => { }); }); + it("upgrades saved file surfaces with neutral reveal state", () => { + expect( + migratePersistedRightPanelState({ + byThreadKey: { + "env-1:thread-A": { + isOpen: true, + activeSurfaceId: "file:src/index.ts", + surfaces: [{ id: "file:src/index.ts", kind: "file", relativePath: "src/index.ts" }], + }, + }, + }), + ).toEqual({ + byThreadKey: { + "env-1:thread-A": { + isOpen: true, + activeSurfaceId: "file:src/index.ts", + surfaces: [ + { + id: "file:src/index.ts", + kind: "file", + relativePath: "src/index.ts", + revealLine: null, + revealRequestId: 0, + }, + ], + }, + }, + }); + }); + it("open sets the active panel for a thread", () => { useRightPanelStore.getState().open(refA, "preview"); expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("preview"); @@ -108,8 +138,55 @@ describe("rightPanelStore", () => { isOpen: true, activeSurfaceId: "file:README.md", surfaces: [ - { id: "file:src/index.ts", kind: "file", relativePath: "src/index.ts" }, - { id: "file:README.md", kind: "file", relativePath: "README.md" }, + { + id: "file:src/index.ts", + kind: "file", + relativePath: "src/index.ts", + revealLine: null, + revealRequestId: 2, + }, + { + id: "file:README.md", + kind: "file", + relativePath: "README.md", + revealLine: null, + revealRequestId: 1, + }, + ], + }); + }); + + it("updates line reveal requests when reopening a file surface", () => { + useRightPanelStore.getState().openFile(refA, "src/index.ts", 42); + useRightPanelStore.getState().openFile(refA, "src/index.ts", 87); + + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: true, + activeSurfaceId: "file:src/index.ts", + surfaces: [ + { + id: "file:src/index.ts", + kind: "file", + relativePath: "src/index.ts", + revealLine: 87, + revealRequestId: 2, + }, + ], + }); + + useRightPanelStore.getState().openFile(refA, "src/index.ts"); + + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: true, + activeSurfaceId: "file:src/index.ts", + surfaces: [ + { + id: "file:src/index.ts", + kind: "file", + relativePath: "src/index.ts", + revealLine: null, + revealRequestId: 3, + }, ], }); }); @@ -314,7 +391,15 @@ describe("rightPanelStore", () => { expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ isOpen: true, activeSurfaceId: "file:src/index.ts", - surfaces: [{ id: "file:src/index.ts", kind: "file", relativePath: "src/index.ts" }], + surfaces: [ + { + id: "file:src/index.ts", + kind: "file", + relativePath: "src/index.ts", + revealLine: null, + revealRequestId: 1, + }, + ], }); }); diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts index bb7f1210e0..36fa82f9ff 100644 --- a/apps/web/src/rightPanelStore.ts +++ b/apps/web/src/rightPanelStore.ts @@ -30,11 +30,17 @@ export type RightPanelSurface = } | { id: "diff"; kind: "diff" } | { id: "files"; kind: "files" } - | { id: `file:${string}`; kind: "file"; relativePath: string } + | { + id: `file:${string}`; + kind: "file"; + relativePath: string; + revealLine: number | null; + revealRequestId: number; + } | { id: "plan"; kind: "plan" }; const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2"; -const RIGHT_PANEL_STORAGE_VERSION = 6; +const RIGHT_PANEL_STORAGE_VERSION = 7; export interface ThreadRightPanelState { isOpen: boolean; @@ -46,7 +52,7 @@ interface RightPanelStoreState { byThreadKey: Record; open: (ref: ScopedThreadRef, kind: Exclude) => void; openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void; - openFile: (ref: ScopedThreadRef, relativePath: string) => void; + openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void; openTerminal: (ref: ScopedThreadRef, terminalId: string) => void; splitTerminal: ( ref: ScopedThreadRef, @@ -94,10 +100,16 @@ const browserSurface = (tabId: string | null): RightPanelSurface => ? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId } : { id: "browser:new", kind: "preview", resourceId: null }; -const fileSurface = (relativePath: string): RightPanelSurface => ({ +const fileSurface = ( + relativePath: string, + revealLine: number | null, + revealRequestId: number, +): RightPanelSurface => ({ id: `file:${relativePath}`, kind: "file", relativePath, + revealLine, + revealRequestId, }); const terminalSurface = (terminalId: string): RightPanelSurface => ({ @@ -136,6 +148,11 @@ const updateThread = ( return { ...byThreadKey, [threadKey]: next }; }; +function normalizeRevealLine(line: number | undefined): number | null { + if (line === undefined || !Number.isFinite(line)) return null; + return Math.max(1, Math.trunc(line)); +} + export function migratePersistedRightPanelState(persistedState: unknown): { byThreadKey: Record; } { @@ -153,6 +170,20 @@ export function migratePersistedRightPanelState(persistedState: unknown): { threadState && typeof threadState === "object" ? threadState : null; const surfaces = Array.isArray(validThreadState?.surfaces) ? validThreadState.surfaces.flatMap((surface) => { + if (surface.kind === "file") { + const revealLine = + typeof surface.revealLine === "number" && + Number.isFinite(surface.revealLine) + ? Math.max(1, Math.trunc(surface.revealLine)) + : null; + const revealRequestId = + typeof surface.revealRequestId === "number" && + Number.isSafeInteger(surface.revealRequestId) && + surface.revealRequestId >= 0 + ? surface.revealRequestId + : 0; + return [{ ...surface, revealLine, revealRequestId }]; + } if (surface.kind !== "terminal") return [surface]; if ( !("resourceId" in surface) || @@ -228,16 +259,31 @@ export const useRightPanelStore = create()( return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface); }), })), - openFile: (ref, relativePath) => + openFile: (ref, relativePath, line) => set((state) => ({ byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => { const withoutStandaloneExplorer = current.surfaces.filter( (surface) => surface.kind !== "files", ); - return upsertSurface( - { ...current, surfaces: withoutStandaloneExplorer }, - fileSurface(relativePath), + const surfaceId = `file:${relativePath}` as const; + const existing = withoutStandaloneExplorer.find( + (surface): surface is Extract => + surface.id === surfaceId && surface.kind === "file", ); + const surface = fileSurface( + relativePath, + normalizeRevealLine(line), + (existing?.revealRequestId ?? 0) + 1, + ); + return { + isOpen: true, + activeSurfaceId: surface.id, + surfaces: existing + ? withoutStandaloneExplorer.map((entry) => + entry.id === surface.id ? surface : entry, + ) + : [...withoutStandaloneExplorer, surface], + }; }), })), openTerminal: (ref, terminalId) =>