Skip to content

Commit a3da7fe

Browse files
Debounce editable file preview saves
- Extract file save coordination into a reusable helper - Keep pending state accurate across overlapping writes - Add tests for debounce, retries, and failures
1 parent da8d585 commit a3da7fe

3 files changed

Lines changed: 190 additions & 45 deletions

File tree

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

Lines changed: 28 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
1515
import FileBrowserPanel from "./FileBrowserPanel";
1616
import { projectFileCacheKey } from "./fileContentRevision";
1717
import { fileBreadcrumbs } from "./filePath";
18+
import { FileSaveCoordinator } from "./fileSaveCoordinator";
1819
import {
1920
confirmProjectFileQueryData,
2021
setProjectFileQueryData,
@@ -31,30 +32,7 @@ interface FilePreviewPanelProps {
3132
}
3233

3334
const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen";
34-
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-
}
35+
const FILE_SAVE_DEBOUNCE_MS = 500;
5836

5937
interface EditableFileSurfaceProps {
6038
environmentId: EnvironmentId;
@@ -73,37 +51,42 @@ function EditableFileSurface({
7351
resolvedTheme,
7452
onPendingChange,
7553
}: EditableFileSurfaceProps) {
76-
const pendingWrites = useMemo(
77-
() => new PendingFileWrites(relativePath, onPendingChange),
78-
[onPendingChange, relativePath],
54+
const saveCoordinator = useMemo(
55+
() =>
56+
new FileSaveCoordinator({
57+
debounceMs: FILE_SAVE_DEBOUNCE_MS,
58+
onPendingChange: (pending) => onPendingChange(relativePath, pending),
59+
persist: async (nextContents) => {
60+
await ensureEnvironmentApi(environmentId).projects.writeFile({
61+
cwd,
62+
relativePath,
63+
contents: nextContents,
64+
});
65+
},
66+
onConfirmed: (confirmedContents) => {
67+
confirmProjectFileQueryData(environmentId, cwd, relativePath, confirmedContents);
68+
},
69+
}),
70+
[cwd, environmentId, onPendingChange, relativePath],
7971
);
8072
const editor = useMemo(
8173
() =>
8274
new Editor({
8375
onChange: (file) => {
84-
pendingWrites.begin();
8576
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-
);
77+
saveCoordinator.change(file.contents);
10178
},
10279
}),
103-
[cwd, environmentId, pendingWrites, relativePath],
80+
[cwd, environmentId, relativePath, saveCoordinator],
10481
);
10582

106-
useEffect(() => () => editor.cleanUp(), [editor]);
83+
useEffect(
84+
() => () => {
85+
editor.cleanUp();
86+
saveCoordinator.dispose();
87+
},
88+
[editor, saveCoordinator],
89+
);
10790

10891
return (
10992
<EditorProvider editor={editor}>
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2+
3+
import { FileSaveCoordinator } from "./fileSaveCoordinator";
4+
5+
function deferred() {
6+
let resolve!: () => void;
7+
const promise = new Promise<void>((resolvePromise) => {
8+
resolve = resolvePromise;
9+
});
10+
return { promise, resolve };
11+
}
12+
13+
describe("FileSaveCoordinator", () => {
14+
afterEach(() => {
15+
vi.useRealTimers();
16+
});
17+
18+
it("debounces edits and persists only the latest contents", async () => {
19+
vi.useFakeTimers();
20+
const persist = vi.fn<(contents: string) => Promise<void>>().mockResolvedValue(undefined);
21+
const onPendingChange = vi.fn();
22+
const onConfirmed = vi.fn();
23+
const coordinator = new FileSaveCoordinator({
24+
debounceMs: 500,
25+
persist,
26+
onPendingChange,
27+
onConfirmed,
28+
});
29+
30+
coordinator.change("first");
31+
await vi.advanceTimersByTimeAsync(300);
32+
coordinator.change("latest");
33+
await vi.advanceTimersByTimeAsync(499);
34+
expect(persist).not.toHaveBeenCalled();
35+
36+
await vi.advanceTimersByTimeAsync(1);
37+
expect(persist).toHaveBeenCalledOnce();
38+
expect(persist).toHaveBeenCalledWith("latest");
39+
expect(onConfirmed).toHaveBeenCalledWith("latest");
40+
expect(onPendingChange.mock.calls).toEqual([[true], [true], [false]]);
41+
});
42+
43+
it("keeps pending state until an edit made during a write is also saved", async () => {
44+
vi.useFakeTimers();
45+
const firstWrite = deferred();
46+
const persist = vi
47+
.fn<(contents: string) => Promise<void>>()
48+
.mockReturnValueOnce(firstWrite.promise)
49+
.mockResolvedValueOnce(undefined);
50+
const onPendingChange = vi.fn();
51+
const coordinator = new FileSaveCoordinator({
52+
debounceMs: 500,
53+
persist,
54+
onPendingChange,
55+
onConfirmed: vi.fn(),
56+
});
57+
58+
coordinator.change("first");
59+
await vi.advanceTimersByTimeAsync(500);
60+
coordinator.change("latest");
61+
await vi.advanceTimersByTimeAsync(500);
62+
expect(persist).toHaveBeenCalledTimes(1);
63+
64+
firstWrite.resolve();
65+
await vi.runAllTimersAsync();
66+
expect(persist).toHaveBeenCalledTimes(2);
67+
expect(persist).toHaveBeenLastCalledWith("latest");
68+
expect(onPendingChange.mock.calls.at(-1)).toEqual([false]);
69+
});
70+
71+
it("leaves the file pending when the latest write fails", async () => {
72+
vi.useFakeTimers();
73+
const onPendingChange = vi.fn();
74+
const coordinator = new FileSaveCoordinator({
75+
debounceMs: 500,
76+
persist: vi.fn().mockRejectedValue(new Error("write failed")),
77+
onPendingChange,
78+
onConfirmed: vi.fn(),
79+
});
80+
81+
coordinator.change("latest");
82+
await vi.advanceTimersByTimeAsync(500);
83+
await Promise.resolve();
84+
expect(onPendingChange).toHaveBeenCalledWith(true);
85+
expect(onPendingChange).not.toHaveBeenCalledWith(false);
86+
});
87+
});
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
export interface FileSaveCoordinatorOptions {
2+
readonly debounceMs: number;
3+
readonly persist: (contents: string) => Promise<void>;
4+
readonly onPendingChange: (pending: boolean) => void;
5+
readonly onConfirmed: (contents: string) => void;
6+
}
7+
8+
export class FileSaveCoordinator {
9+
private timer: ReturnType<typeof setTimeout> | null = null;
10+
private latestContents = "";
11+
private latestRevision = 0;
12+
private lastChangeAt = 0;
13+
private saving = false;
14+
private disposed = false;
15+
16+
constructor(private readonly options: FileSaveCoordinatorOptions) {}
17+
18+
change(contents: string): void {
19+
this.latestContents = contents;
20+
this.latestRevision += 1;
21+
this.lastChangeAt = Date.now();
22+
this.options.onPendingChange(true);
23+
this.schedule(this.options.debounceMs);
24+
}
25+
26+
dispose(): void {
27+
this.disposed = true;
28+
this.clearTimer();
29+
if (this.latestRevision > 0) void this.persistLatest();
30+
}
31+
32+
private schedule(delay: number): void {
33+
this.clearTimer();
34+
this.timer = setTimeout(() => {
35+
this.timer = null;
36+
void this.persistLatest();
37+
}, delay);
38+
}
39+
40+
private clearTimer(): void {
41+
if (this.timer === null) return;
42+
clearTimeout(this.timer);
43+
this.timer = null;
44+
}
45+
46+
private async persistLatest(): Promise<void> {
47+
if (this.saving || this.latestRevision === 0) return;
48+
49+
this.saving = true;
50+
const contents = this.latestContents;
51+
const revision = this.latestRevision;
52+
let succeeded = false;
53+
try {
54+
await this.options.persist(contents);
55+
succeeded = true;
56+
this.options.onConfirmed(contents);
57+
} catch {}
58+
59+
this.saving = false;
60+
if (revision === this.latestRevision) {
61+
if (succeeded) this.options.onPendingChange(false);
62+
return;
63+
}
64+
65+
const remainingDebounce = Math.max(
66+
0,
67+
this.options.debounceMs - (Date.now() - this.lastChangeAt),
68+
);
69+
if (this.disposed) {
70+
void this.persistLatest();
71+
} else {
72+
this.schedule(remainingDebounce);
73+
}
74+
}
75+
}

0 commit comments

Comments
 (0)