Skip to content

Commit 0951828

Browse files
committed
fix(web): turning a retention rule on no longer saves 8 days first
Enabling a retention switch published 8 days immediately, so cleanup could run before the user chose an age. The switch now opens a local draft and saves only when that age is committed. Leaving or cancelling the draft keeps the rule off. Turning an enabled rule off still saves immediately.
1 parent d18352e commit 0951828

2 files changed

Lines changed: 230 additions & 14 deletions

File tree

‎apps/web/src/components/settings/StorageSettings.browser.test.tsx‎

Lines changed: 134 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { page } from "vite-plus/test/browser";
1313
const state = vi.hoisted(() => ({
1414
settings: {} as typeof DEFAULT_SERVER_SETTINGS,
1515
run: vi.fn(),
16+
update: vi.fn(),
1617
report: null as StorageCleanupReport | null,
1718
}));
1819

@@ -67,7 +68,7 @@ vi.mock(import("./useScopedSettings"), async (original) => ({
6768
...(await original()),
6869
useScopedSettings: (() => state.settings) as never,
6970
useScopedSettingsMixed: () => false,
70-
useUpdateScopedSettings: () => vi.fn(),
71+
useUpdateScopedSettings: () => state.update,
7172
useClearScopedSettings: () => vi.fn(),
7273
}));
7374
// The real page container needs a router and the real row reads write permission and
@@ -95,7 +96,14 @@ import { StorageSettingsPanel } from "./StorageSettings";
9596
let root: Root;
9697
let container: HTMLDivElement;
9798

99+
function setInputValue(input: HTMLInputElement, value: string) {
100+
const prototype = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");
101+
prototype?.set?.call(input, value);
102+
input.dispatchEvent(new Event("input", { bubbles: true }));
103+
}
104+
98105
beforeEach(() => {
106+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
99107
state.settings = {
100108
...DEFAULT_SERVER_SETTINGS,
101109
storageCleanup: {
@@ -112,6 +120,7 @@ beforeEach(() => {
112120
};
113121
state.report = null;
114122
state.run.mockReset();
123+
state.update.mockReset();
115124
container = document.createElement("div");
116125
document.body.append(container);
117126
root = createRoot(container);
@@ -120,6 +129,7 @@ beforeEach(() => {
120129
afterEach(async () => {
121130
await act(async () => root.unmount());
122131
container.remove();
132+
vi.unstubAllGlobals();
123133
});
124134

125135
async function render() {
@@ -181,6 +191,129 @@ it.each(["machine-wide immediate", "project custom"])(
181191
},
182192
);
183193

194+
const RETENTION_RULES = [
195+
["Delete inactive worktrees", "worktreeAfterDays"],
196+
["Delete settled worktrees", "worktreeSettledAfterDays"],
197+
["Delete old browser artifacts", "browserArtifactsAfterDays"],
198+
["Delete old rotated logs", "logsAfterDays"],
199+
] as const;
200+
201+
function retentionSwitch(label: string) {
202+
const element = container.querySelector<HTMLElement>(`[role="switch"][aria-label="${label}"]`);
203+
if (!element) throw new Error(`Missing switch ${label}`);
204+
return element;
205+
}
206+
207+
function daysInput(label: string) {
208+
return container.querySelector<HTMLInputElement>(`input[aria-label="${label} in days"]`);
209+
}
210+
211+
it.each(RETENTION_RULES)("turning %s on does not save 8 days", async (label) => {
212+
await render();
213+
214+
await act(async () => retentionSwitch(label).click());
215+
216+
expect(state.update).not.toHaveBeenCalled();
217+
expect(retentionSwitch(label).getAttribute("aria-checked")).toBe("true");
218+
expect(daysInput(label)?.value).toBe("8");
219+
});
220+
221+
it("saves a drafted retention age only when that age is committed", async () => {
222+
const label = "Delete inactive worktrees";
223+
await render();
224+
await act(async () => retentionSwitch(label).click());
225+
const input = daysInput(label)!;
226+
227+
await act(async () => {
228+
setInputValue(input, "30");
229+
input.blur();
230+
});
231+
232+
expect(state.update).toHaveBeenCalledExactlyOnceWith({
233+
storageCleanup: { worktreeAfterDays: 30 },
234+
});
235+
expect(daysInput(label)?.value).toBe("30");
236+
});
237+
238+
it("saves the visible default when Enter commits an untouched retention draft", async () => {
239+
const label = "Delete inactive worktrees";
240+
await render();
241+
await act(async () => retentionSwitch(label).click());
242+
243+
await act(async () => {
244+
daysInput(label)?.dispatchEvent(
245+
new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }),
246+
);
247+
});
248+
249+
expect(state.update).toHaveBeenCalledExactlyOnceWith({
250+
storageCleanup: { worktreeAfterDays: 8 },
251+
});
252+
});
253+
254+
it("keeps a retention rule off when its draft is left or cancelled", async () => {
255+
const label = "Delete inactive worktrees";
256+
await render();
257+
await act(async () => retentionSwitch(label).click());
258+
const outside = document.createElement("button");
259+
document.body.append(outside);
260+
261+
await act(async () => outside.focus());
262+
263+
expect(state.update).not.toHaveBeenCalled();
264+
expect(daysInput(label)).toBeNull();
265+
outside.remove();
266+
267+
await act(async () => retentionSwitch(label).click());
268+
await act(async () => {
269+
daysInput(label)?.dispatchEvent(
270+
new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }),
271+
);
272+
});
273+
274+
expect(state.update).not.toHaveBeenCalled();
275+
expect(daysInput(label)).toBeNull();
276+
});
277+
278+
it("saves a retention step from the drafted age", async () => {
279+
const label = "Delete old rotated logs";
280+
await render();
281+
await act(async () => retentionSwitch(label).click());
282+
283+
await act(async () => {
284+
container.querySelector<HTMLElement>(`[aria-label="Increase ${label}"]`)?.click();
285+
});
286+
287+
expect(state.update).toHaveBeenCalledExactlyOnceWith({
288+
storageCleanup: { logsAfterDays: 9 },
289+
});
290+
});
291+
292+
it("turns an enabled retention rule off immediately and edits it without saving 8", async () => {
293+
const label = "Delete old browser artifacts";
294+
state.settings = {
295+
...state.settings,
296+
storageCleanup: { ...state.settings.storageCleanup, browserArtifactsAfterDays: 30 },
297+
};
298+
await render();
299+
const input = daysInput(label)!;
300+
301+
await act(async () => {
302+
input.focus();
303+
setInputValue(input, "14");
304+
input.blur();
305+
});
306+
expect(state.update).toHaveBeenCalledExactlyOnceWith({
307+
storageCleanup: { browserArtifactsAfterDays: 14 },
308+
});
309+
310+
state.update.mockClear();
311+
await act(async () => retentionSwitch(label).click());
312+
expect(state.update).toHaveBeenCalledExactlyOnceWith({
313+
storageCleanup: { browserArtifactsAfterDays: null },
314+
});
315+
});
316+
184317
it("keeps cleanup disabled when settled retention and all other rules are off", async () => {
185318
const button = await render();
186319

‎apps/web/src/components/settings/StorageSettings.tsx‎

Lines changed: 96 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import type {
44
WorktreeCleanupRules,
55
} from "@t3tools/contracts";
66
import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
7-
import { useRef, useState } from "react";
7+
import { useEffect, useRef, useState } from "react";
88
import { useAtomValue } from "@effect/atom-react";
99
import {
1010
isAtomCommandInterrupted,
@@ -115,16 +115,74 @@ function RetentionControl({
115115
onChange: (value: number | null) => void;
116116
minimum?: number;
117117
}) {
118-
const [draft, setDraft] = useState(value);
118+
const initialDays = Math.max(minimum, 8);
119+
const [draft, setDraft] = useState<number | null>(value);
119120
const [savedValue, setSavedValue] = useState(value);
121+
// `draft` is an age the user can see and has not saved. `holding` is that age after
122+
// commit, kept on screen until the saved value arrives so the row does not flash Off.
123+
const [mode, setMode] = useState<"synced" | "draft" | "holding">("synced");
124+
const modeRef = useRef(mode);
125+
const rootRef = useRef<HTMLDivElement>(null);
126+
const pointerInsideRef = useRef(false);
127+
const publishedRef = useRef<number | null>(null);
120128
if (savedValue !== value) {
121129
setSavedValue(value);
122130
setDraft(value);
131+
setMode("synced");
132+
}
133+
134+
useEffect(() => {
135+
modeRef.current = mode;
136+
if (mode === "synced") publishedRef.current = null;
137+
if (mode !== "draft") return;
138+
const input = rootRef.current?.querySelector("input");
139+
input?.focus();
140+
input?.select();
141+
}, [mode]);
142+
143+
const enabled = value !== null || mode !== "synced";
144+
145+
function discardDraft() {
146+
modeRef.current = "synced";
147+
publishedRef.current = null;
148+
setMode("synced");
149+
setDraft(value);
150+
}
151+
152+
function commitDays(next: number) {
153+
const days = Math.min(3650, Math.max(minimum, Math.round(next)));
154+
if (value === null && modeRef.current === "holding" && publishedRef.current === days) return;
155+
setDraft(days);
156+
if (value === null) {
157+
modeRef.current = "holding";
158+
setMode("holding");
159+
publishedRef.current = days;
160+
}
161+
onChange(days);
123162
}
124163

125164
return (
126-
<div className="flex items-center gap-3">
127-
{value !== null ? (
165+
<div
166+
ref={rootRef}
167+
className="flex items-center gap-3"
168+
onPointerDown={() => {
169+
pointerInsideRef.current = true;
170+
}}
171+
onPointerUp={() => {
172+
pointerInsideRef.current = false;
173+
}}
174+
onPointerCancel={() => {
175+
pointerInsideRef.current = false;
176+
}}
177+
onBlur={(event) => {
178+
if (modeRef.current !== "draft") return;
179+
const next = event.relatedTarget;
180+
if (next instanceof Node && event.currentTarget.contains(next)) return;
181+
if (pointerInsideRef.current) return;
182+
discardDraft();
183+
}}
184+
>
185+
{enabled ? (
128186
<NumberField
129187
value={draft}
130188
min={minimum}
@@ -134,20 +192,32 @@ function RetentionControl({
134192
className="w-auto"
135193
onValueChange={setDraft}
136194
onValueCommitted={(next) => {
137-
if (next === null) setDraft(value);
138-
else {
139-
const days = Math.min(3650, Math.max(minimum, Math.round(next)));
140-
setDraft(days);
141-
onChange(days);
142-
}
195+
if (next === null) setDraft(value ?? initialDays);
196+
else commitDays(next);
143197
}}
144198
>
145199
<NumberFieldGroup>
146200
<NumberFieldDecrement aria-label={`Decrease ${label}`} />
147201
<NumberFieldInput
148202
aria-label={`${label} in days`}
149-
size={new Intl.NumberFormat().format(draft ?? value).length}
203+
size={new Intl.NumberFormat().format(draft ?? value ?? initialDays).length}
150204
className="field-sizing-content w-auto min-w-[1ch] grow-0 text-right"
205+
onKeyDown={(event) => {
206+
if (event.nativeEvent.isComposing) return;
207+
if (modeRef.current !== "draft") return;
208+
if (event.key === "Escape") {
209+
event.preventDefault();
210+
event.stopPropagation();
211+
discardDraft();
212+
return;
213+
}
214+
if (event.key !== "Enter") return;
215+
event.preventDefault();
216+
const raw = event.currentTarget.value.trim();
217+
if (raw === "") return;
218+
const parsed = Number(raw);
219+
if (Number.isFinite(parsed)) commitDays(parsed);
220+
}}
151221
/>
152222
<span aria-hidden="true" className="self-center pr-2 text-xs">
153223
days
@@ -160,8 +230,21 @@ function RetentionControl({
160230
)}
161231
<Switch
162232
aria-label={label}
163-
checked={value !== null}
164-
onCheckedChange={(enabled) => onChange(enabled ? 8 : null)}
233+
checked={enabled}
234+
onCheckedChange={(nextEnabled) => {
235+
// Opening the switch only shows the default age. Nothing is saved until that
236+
// age is committed, so cleanup cannot run at 8 days the user has not chosen.
237+
if (nextEnabled) {
238+
publishedRef.current = null;
239+
setDraft(initialDays);
240+
modeRef.current = "draft";
241+
setMode("draft");
242+
return;
243+
}
244+
const publishOff = value !== null || modeRef.current === "holding";
245+
discardDraft();
246+
if (publishOff) onChange(null);
247+
}}
165248
/>
166249
</div>
167250
);

0 commit comments

Comments
 (0)