Skip to content

Commit da8d585

Browse files
Make file previews editable with optimistic saves
- Switch full-file previews to an editable diff editor when safe - Track pending file writes per project so tabs show unsaved state - Upgrade @pierre/diffs and add revision-backed cache keys
1 parent 6047c95 commit da8d585

12 files changed

Lines changed: 430 additions & 50 deletions

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ const PreviewPanel = lazy(() =>
112112
);
113113
const DiffPanel = lazy(() => import("./DiffPanel"));
114114
const FilePreviewPanel = lazy(() => import("./files/FilePreviewPanel"));
115+
const EMPTY_PENDING_FILE_SURFACE_IDS: ReadonlySet<string> = new Set();
115116
import { BranchToolbar } from "./BranchToolbar";
116117
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
117118
import PlanSidebar from "./PlanSidebar";
@@ -1367,6 +1368,41 @@ function ChatViewContent(props: ChatViewProps) {
13671368
const activeProject = useStore(
13681369
useMemo(() => createProjectSelectorByRef(activeProjectRef), [activeProjectRef]),
13691370
);
1371+
const activeProjectKey = activeProject
1372+
? `${activeProject.environmentId}:${activeProject.cwd}`
1373+
: null;
1374+
const [pendingFileSurfaceIdsByProject, setPendingFileSurfaceIdsByProject] = useState<
1375+
ReadonlyMap<string, ReadonlySet<string>>
1376+
>(() => new Map());
1377+
const pendingFileSurfaceIds = activeProjectKey
1378+
? (pendingFileSurfaceIdsByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS)
1379+
: EMPTY_PENDING_FILE_SURFACE_IDS;
1380+
const handleFilePendingChange = useCallback(
1381+
(relativePath: string, pending: boolean) => {
1382+
if (!activeProjectKey) return;
1383+
setPendingFileSurfaceIdsByProject((currentByProject) => {
1384+
const current = currentByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS;
1385+
const surfaceId = `file:${relativePath}`;
1386+
if (current.has(surfaceId) === pending) return currentByProject;
1387+
1388+
const next = new Set(current);
1389+
if (pending) {
1390+
next.add(surfaceId);
1391+
} else {
1392+
next.delete(surfaceId);
1393+
}
1394+
1395+
const nextByProject = new Map(currentByProject);
1396+
if (next.size === 0) {
1397+
nextByProject.delete(activeProjectKey);
1398+
} else {
1399+
nextByProject.set(activeProjectKey, next);
1400+
}
1401+
return nextByProject;
1402+
});
1403+
},
1404+
[activeProjectKey],
1405+
);
13701406
const activeEnvironmentBootstrapComplete = useStore((state) =>
13711407
activeThread
13721408
? selectEnvironmentState(state, activeThread.environmentId).bootstrapComplete
@@ -4792,6 +4828,7 @@ function ChatViewContent(props: ChatViewProps) {
47924828
maximized={rightPanelMaximized}
47934829
surfaces={rightPanelState.surfaces}
47944830
activeSurfaceId={activeRightPanelSurface?.id ?? null}
4831+
pendingSurfaceIds={pendingFileSurfaceIds}
47954832
previewSessions={activePreviewState.sessions}
47964833
terminalLabelsById={activeTerminalLabelsById}
47974834
onActivate={activateRightPanelSurface}
@@ -4851,6 +4888,7 @@ function ChatViewContent(props: ChatViewProps) {
48514888
: null
48524889
}
48534890
onOpenFile={openFileSurface}
4891+
onPendingChange={handleFilePendingChange}
48544892
/>
48554893
</Suspense>
48564894
) : null}
@@ -4863,6 +4901,7 @@ function ChatViewContent(props: ChatViewProps) {
48634901
mode="sheet"
48644902
surfaces={rightPanelState.surfaces}
48654903
activeSurfaceId={activeRightPanelSurface?.id ?? null}
4904+
pendingSurfaceIds={pendingFileSurfaceIds}
48664905
previewSessions={activePreviewState.sessions}
48674906
terminalLabelsById={activeTerminalLabelsById}
48684907
onActivate={activateRightPanelSurface}
@@ -4935,6 +4974,7 @@ function ChatViewContent(props: ChatViewProps) {
49354974
: null
49364975
}
49374976
onOpenFile={openFileSurface}
4977+
onPendingChange={handleFilePendingChange}
49384978
/>
49394979
</Suspense>
49404980
) : null}

‎apps/web/src/components/DiffWorkerPoolProvider.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
4747
highlighterOptions={{
4848
theme: diffThemeName,
4949
tokenizeMaxLineLength: 1_000,
50+
useTokenTransformer: true,
5051
}}
5152
>
5253
<DiffWorkerThemeSync themeName={diffThemeName} />

‎apps/web/src/components/RightPanelTabs.tsx‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ interface RightPanelTabsProps {
2020
maximized?: boolean;
2121
surfaces: readonly RightPanelSurface[];
2222
activeSurfaceId: string | null;
23+
pendingSurfaceIds: ReadonlySet<string>;
2324
previewSessions: Readonly<Record<string, PreviewSessionSnapshot>>;
2425
terminalLabelsById: ReadonlyMap<string, string>;
2526
onActivate: (surface: RightPanelSurface) => void;
@@ -225,6 +226,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
225226
<div className="flex h-full w-max min-w-full items-center gap-1">
226227
{props.surfaces.map((surface) => {
227228
const active = surface.id === props.activeSurfaceId;
229+
const pending = props.pendingSurfaceIds.has(surface.id);
228230
const title = surfaceTitle(surface, props.previewSessions, props.terminalLabelsById);
229231
return (
230232
<div
@@ -258,11 +260,24 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
258260
</Tooltip>
259261
<button
260262
type="button"
261-
className="rounded p-0.5 opacity-0 hover:bg-muted group-hover:opacity-100 focus:opacity-100"
263+
className={cn(
264+
"relative flex size-4 shrink-0 items-center justify-center rounded hover:bg-muted focus:opacity-100",
265+
pending ? "opacity-100" : "opacity-0 group-hover:opacity-100",
266+
)}
262267
aria-label={`Close ${title}`}
263268
onClick={() => props.onCloseSurface(surface)}
264269
>
265-
<X className="size-3" />
270+
{pending ? (
271+
<>
272+
<span
273+
className="size-2 rounded-full bg-current group-hover:hidden"
274+
aria-hidden
275+
/>
276+
<X className="hidden size-3 group-hover:block" />
277+
</>
278+
) : (
279+
<X className="size-3" />
280+
)}
266281
</button>
267282
</div>
268283
);

‎apps/web/src/components/files/FilePreviewPanel.tsx‎

Lines changed: 146 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import type { EnvironmentId } from "@t3tools/contracts";
2-
import { File, Virtualizer } from "@pierre/diffs/react";
2+
import { Editor } from "@pierre/diffs/editor";
3+
import { EditorProvider, File, Virtualizer } from "@pierre/diffs/react";
34
import { ChevronRight, FolderTree, LoaderCircle } from "lucide-react";
45
import { useEffect, useMemo, useRef, useState } from "react";
56

7+
import { ensureEnvironmentApi } from "~/environmentApi";
68
import { useTheme } from "~/hooks/useTheme";
79
import { resolveDiffThemeName } from "~/lib/diffRendering";
810
import { cn } from "~/lib/utils";
@@ -11,19 +13,127 @@ import { Toggle } from "~/components/ui/toggle";
1113
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
1214

1315
import FileBrowserPanel from "./FileBrowserPanel";
16+
import { projectFileCacheKey } from "./fileContentRevision";
1417
import { fileBreadcrumbs } from "./filePath";
15-
import { useProjectFileQuery } from "./projectFilesQueryState";
18+
import {
19+
confirmProjectFileQueryData,
20+
setProjectFileQueryData,
21+
useProjectFileQuery,
22+
} from "./projectFilesQueryState";
1623

1724
interface FilePreviewPanelProps {
1825
environmentId: EnvironmentId;
1926
cwd: string;
2027
projectName: string;
2128
relativePath: string | null;
2229
onOpenFile: (relativePath: string) => void;
30+
onPendingChange: (relativePath: string, pending: boolean) => void;
2331
}
2432

2533
const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen";
2634

35+
class PendingFileWrites {
36+
private pending = 0;
37+
private failed = false;
38+
39+
constructor(
40+
private readonly relativePath: string,
41+
private readonly onPendingChange: (relativePath: string, pending: boolean) => void,
42+
) {}
43+
44+
begin(): void {
45+
if (this.pending === 0) this.failed = false;
46+
this.pending += 1;
47+
this.onPendingChange(this.relativePath, true);
48+
}
49+
50+
finish(success: boolean): void {
51+
if (!success) this.failed = true;
52+
this.pending -= 1;
53+
if (this.pending === 0 && !this.failed) {
54+
this.onPendingChange(this.relativePath, false);
55+
}
56+
}
57+
}
58+
59+
interface EditableFileSurfaceProps {
60+
environmentId: EnvironmentId;
61+
cwd: string;
62+
relativePath: string;
63+
contents: string;
64+
resolvedTheme: "light" | "dark";
65+
onPendingChange: (relativePath: string, pending: boolean) => void;
66+
}
67+
68+
function EditableFileSurface({
69+
environmentId,
70+
cwd,
71+
relativePath,
72+
contents,
73+
resolvedTheme,
74+
onPendingChange,
75+
}: EditableFileSurfaceProps) {
76+
const pendingWrites = useMemo(
77+
() => new PendingFileWrites(relativePath, onPendingChange),
78+
[onPendingChange, relativePath],
79+
);
80+
const editor = useMemo(
81+
() =>
82+
new Editor({
83+
onChange: (file) => {
84+
pendingWrites.begin();
85+
setProjectFileQueryData(environmentId, cwd, relativePath, file.contents);
86+
void ensureEnvironmentApi(environmentId)
87+
.projects.writeFile({
88+
cwd,
89+
relativePath,
90+
contents: file.contents,
91+
})
92+
.then(
93+
() => {
94+
confirmProjectFileQueryData(environmentId, cwd, relativePath, file.contents);
95+
pendingWrites.finish(true);
96+
},
97+
() => {
98+
pendingWrites.finish(false);
99+
},
100+
);
101+
},
102+
}),
103+
[cwd, environmentId, pendingWrites, relativePath],
104+
);
105+
106+
useEffect(() => () => editor.cleanUp(), [editor]);
107+
108+
return (
109+
<EditorProvider editor={editor}>
110+
<Virtualizer
111+
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
112+
config={{
113+
overscrollSize: 600,
114+
intersectionObserverMargin: 1200,
115+
}}
116+
>
117+
<File
118+
file={{
119+
name: relativePath,
120+
contents,
121+
cacheKey: projectFileCacheKey(cwd, relativePath, contents),
122+
}}
123+
options={{
124+
disableFileHeader: true,
125+
overflow: "scroll",
126+
theme: resolveDiffThemeName(resolvedTheme),
127+
themeType: resolvedTheme,
128+
}}
129+
className="min-h-full"
130+
contentEditable
131+
/>
132+
</Virtualizer>
133+
</EditorProvider>
134+
);
135+
}
136+
27137
function initialExplorerOpen(): boolean {
28138
try {
29139
return window.localStorage.getItem(FILE_EXPLORER_STORAGE_KEY) !== "false";
@@ -38,6 +148,7 @@ export default function FilePreviewPanel({
38148
projectName,
39149
relativePath,
40150
onOpenFile,
151+
onPendingChange,
41152
}: FilePreviewPanelProps) {
42153
const { resolvedTheme } = useTheme();
43154
const file = useProjectFileQuery(environmentId, cwd, relativePath);
@@ -143,29 +254,41 @@ export default function FilePreviewPanel({
143254
<LoaderCircle className="size-5 animate-spin" />
144255
</div>
145256
) : relativePath && file.data ? (
146-
<Virtualizer
147-
key={`${relativePath}:${resolvedTheme}:${file.data.byteLength}`}
148-
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
149-
config={{
150-
overscrollSize: 600,
151-
intersectionObserverMargin: 1200,
152-
}}
153-
>
154-
<File
155-
file={{
156-
name: relativePath,
157-
contents: file.data.contents,
158-
cacheKey: `${cwd}:${relativePath}:${file.data.byteLength}`,
159-
}}
160-
options={{
161-
disableFileHeader: true,
162-
overflow: "scroll",
163-
theme: resolveDiffThemeName(resolvedTheme),
164-
themeType: resolvedTheme,
257+
file.data.truncated ? (
258+
<Virtualizer
259+
key={`${relativePath}:${resolvedTheme}:${file.data.byteLength}`}
260+
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
261+
config={{
262+
overscrollSize: 600,
263+
intersectionObserverMargin: 1200,
165264
}}
166-
className="min-h-full"
265+
>
266+
<File
267+
file={{
268+
name: relativePath,
269+
contents: file.data.contents,
270+
cacheKey: projectFileCacheKey(cwd, relativePath, file.data.contents),
271+
}}
272+
options={{
273+
disableFileHeader: true,
274+
overflow: "scroll",
275+
theme: resolveDiffThemeName(resolvedTheme),
276+
themeType: resolvedTheme,
277+
}}
278+
className="min-h-full"
279+
/>
280+
</Virtualizer>
281+
) : (
282+
<EditableFileSurface
283+
key={`${relativePath}:${resolvedTheme}`}
284+
environmentId={environmentId}
285+
cwd={cwd}
286+
relativePath={relativePath}
287+
contents={file.data.contents}
288+
resolvedTheme={resolvedTheme}
289+
onPendingChange={onPendingChange}
167290
/>
168-
</Virtualizer>
291+
)
169292
) : null}
170293
</div>
171294
{explorerOpen || relativePath === null ? (
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { fileContentRevision, projectFileCacheKey } from "./fileContentRevision";
4+
5+
describe("fileContentRevision", () => {
6+
it("changes for same-length edits", () => {
7+
expect(fileContentRevision("nodeVersion")).not.toBe(fileContentRevision("nodeVeasdrs"));
8+
});
9+
10+
it("keeps identical contents stable", () => {
11+
expect(projectFileCacheKey("/repo", "file.json", "contents")).toBe(
12+
projectFileCacheKey("/repo", "file.json", "contents"),
13+
);
14+
});
15+
});
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
export function fileContentRevision(contents: string): string {
2+
let hash = 2_166_136_261;
3+
for (let index = 0; index < contents.length; index += 1) {
4+
hash ^= contents.charCodeAt(index);
5+
hash = Math.imul(hash, 16_777_619);
6+
}
7+
return `${contents.length}:${(hash >>> 0).toString(36)}`;
8+
}
9+
10+
export function projectFileCacheKey(cwd: string, relativePath: string, contents: string): string {
11+
return `${cwd}:${relativePath}:${fileContentRevision(contents)}`;
12+
}

0 commit comments

Comments
 (0)