Skip to content

Commit ec86d9c

Browse files
fix(web): theme editor returns to its spot after the window shrinks and grows back
The theme editor panel clamped its stored position on every window resize, so shrinking the window and growing it back left the panel pinned to the edge it was pushed against. The panel now stores geometry as the user left it and fits it to the current viewport in render (new useViewportSize hook, a useSyncExternalStore over window resize), which removes the resize effect. Also in appearance settings: - ThemeColorPicker: the per-frame commit batcher lives in a small object owned by the popover and is flushed when the popover closes and when a drag ends, replacing the unmount-flush effect. - FontFamilyPicker: the already-granted local-fonts probe runs from the store's subscribe instead of a mount effect. - SettingsPanels: the legacy features fold opens for a search jump during render (previous-value state) instead of in an effect. Effects: ThemeEditorPanel 5 -> 4, ThemeColorPicker 1 -> 0, FontFamilyPicker 2 -> 1, SettingsPanels 1 -> 0. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent d5b921c commit ec86d9c

6 files changed

Lines changed: 200 additions & 97 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ let enumerationState: FontEnumerationState = supportsFontEnumeration()
3434
const enumerationListeners = new Set<() => void>();
3535

3636
function subscribeToEnumeration(listener: () => void): () => void {
37+
probeAlreadyGrantedPermission();
3738
enumerationListeners.add(listener);
3839
return () => enumerationListeners.delete(listener);
3940
}
@@ -74,7 +75,6 @@ function probeAlreadyGrantedPermission(): void {
7475
}
7576

7677
export function useFontEnumeration(): FontEnumerationState {
77-
useEffect(probeAlreadyGrantedPermission, []);
7878
return useSyncExternalStore(subscribeToEnumeration, readEnumerationState);
7979
}
8080

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

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { NotificationSettings } from "./NotificationSettings";
33
import { PRIVACY_POLICY_URL } from "../../legalLinks";
44
import { CheckIcon, ChevronRightIcon } from "lucide-react";
55
import { Link, useNavigate } from "@tanstack/react-router";
6-
import { useEffect, useRef, useState } from "react";
6+
import { useRef, useState } from "react";
77
import {
88
type DesktopUpdateChannel,
99
IDLE_COMPACTION_MODES,
@@ -716,17 +716,12 @@ function LegacyFeaturesSection() {
716716
const [open, setOpen] = useState(false);
717717
const searchTargetId = useSettingsSearchTargetId();
718718
const targetRef = useSettingsSearchTarget<HTMLElement>("legacy-features");
719-
const lastExpandedTargetRef = useRef<string | null>(null);
720-
useEffect(() => {
721-
if (searchTargetId === null) {
722-
lastExpandedTargetRef.current = null;
723-
return;
724-
}
725-
if (!LEGACY_FEATURE_TARGET_IDS.has(searchTargetId)) return;
726-
if (lastExpandedTargetRef.current === searchTargetId) return;
727-
lastExpandedTargetRef.current = searchTargetId;
728-
setOpen(true);
729-
}, [searchTargetId]);
719+
// A search jump to a legacy setting opens the fold before its row mounts.
720+
const [seenSearchTargetId, setSeenSearchTargetId] = useState<string | null>(null);
721+
if (seenSearchTargetId !== searchTargetId) {
722+
setSeenSearchTargetId(searchTargetId);
723+
if (searchTargetId !== null && LEGACY_FEATURE_TARGET_IDS.has(searchTargetId)) setOpen(true);
724+
}
730725

731726
return (
732727
<section id="legacy-features" ref={targetRef} tabIndex={-1} className="space-y-2.5">

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

Lines changed: 49 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import { memo, useEffect, useEffectEvent, useRef, useState } from "react";
2-
import { useStableCallback } from "../../hooks/useStableCallback";
1+
import { memo, useState } from "react";
32
import { isThemeColor, themeColorToHex, type ThemeColorRole } from "../../themePalette";
43
import { cn } from "../../lib/utils";
54
import { hexToHsv, hsvToHex, type HsvColor } from "../../lib/color";
@@ -67,13 +66,46 @@ function themeRgbValue(hex: string) {
6766
return themeHexToRgb(hex).join(", ");
6867
}
6968

69+
// Local state updates immediately for a smooth thumb; the parent commit
70+
// (which can regenerate a whole guided palette) is batched to one call per
71+
// animation frame. The popover flushes it on close and the drag surfaces on
72+
// release, so the final frame is never lost.
73+
function createFrameCommitter() {
74+
let pending: { readonly color: string; readonly commit: (color: string) => void } | null = null;
75+
let frame: number | null = null;
76+
const flush = () => {
77+
if (frame !== null) {
78+
cancelAnimationFrame(frame);
79+
frame = null;
80+
}
81+
const next = pending;
82+
pending = null;
83+
next?.commit(next.color);
84+
};
85+
return {
86+
schedule(color: string, commit: (color: string) => void) {
87+
pending = { color, commit };
88+
if (frame !== null) return;
89+
frame = requestAnimationFrame(() => {
90+
frame = null;
91+
flush();
92+
});
93+
},
94+
flush,
95+
};
96+
}
97+
98+
type FrameCommitter = ReturnType<typeof createFrameCommitter>;
99+
70100
function ThemeColorPickerPanel({
71101
label,
72102
value,
103+
committer,
73104
onChange,
74105
}: {
75106
label: string;
76107
value: string;
108+
committer: FrameCommitter;
77109
onChange: (value: string) => void;
78110
}) {
79111
const normalizedValue = normalizeThemePickerColor(value);
@@ -98,40 +130,12 @@ function ThemeColorPickerPanel({
98130
if (currentColor !== normalizedValue) setHsv(hexToHsv(normalizedValue));
99131
}
100132

101-
// Update the thumb immediately; batch expensive parent palette regeneration to one commit per frame.
102-
const commitColor = useStableCallback(onChange);
103-
const pendingCommitRef = useRef<string | null>(null);
104-
const commitFrameRef = useRef<number | null>(null);
105-
// Flush the last drag frame if the popover closes or the pointer lifts before animation frame.
106-
const flushPendingCommit = () => {
107-
if (commitFrameRef.current !== null) {
108-
cancelAnimationFrame(commitFrameRef.current);
109-
commitFrameRef.current = null;
110-
}
111-
const pending = pendingCommitRef.current;
112-
pendingCommitRef.current = null;
113-
if (pending !== null) commitColor(pending);
114-
};
115-
// Flush only on unmount; rerunning this cleanup mid-drag would commit early.
116-
const flushOnUnmount = useEffectEvent(() => flushPendingCommit());
117-
useEffect(() => () => flushOnUnmount(), []);
118-
const scheduleCommit = (color: string) => {
119-
pendingCommitRef.current = color;
120-
if (commitFrameRef.current !== null) return;
121-
commitFrameRef.current = requestAnimationFrame(() => {
122-
commitFrameRef.current = null;
123-
const pending = pendingCommitRef.current;
124-
pendingCommitRef.current = null;
125-
if (pending !== null) commitColor(pending);
126-
});
127-
};
128-
129133
const commitHsv = (nextHsv: HsvColor) => {
130134
setHsv(nextHsv);
131135
const nextColor = hsvToHex(nextHsv.h, nextHsv.s, nextHsv.v);
132136
setHexDraft(nextColor);
133137
setRgbDraft(themeRgbValue(nextColor));
134-
scheduleCommit(nextColor + alphaSuffix);
138+
committer.schedule(nextColor + alphaSuffix, onChange);
135139
};
136140

137141
const handleHexChange = (nextValue: string) => {
@@ -169,13 +173,13 @@ function ThemeColorPickerPanel({
169173
label={label}
170174
value={hsv}
171175
onChange={commitHsv}
172-
onInteractionEnd={flushPendingCommit}
176+
onInteractionEnd={committer.flush}
173177
/>
174178
<ColorHueSlider
175179
label={`${label} hue`}
176180
value={hsv.h}
177181
onChange={(h) => commitHsv({ ...hsv, h })}
178-
onInteractionEnd={flushPendingCommit}
182+
onInteractionEnd={committer.flush}
179183
/>
180184
<div className="grid grid-cols-[1fr_1.2fr] gap-2">
181185
<label className="grid min-w-0 gap-1">
@@ -243,8 +247,13 @@ function ThemeColorPicker({
243247
onChange: (value: string) => void;
244248
onInteract?: () => void;
245249
}) {
250+
const [committer] = useState(createFrameCommitter);
246251
return (
247-
<Popover>
252+
<Popover
253+
onOpenChange={(open) => {
254+
if (!open) committer.flush();
255+
}}
256+
>
248257
<Tooltip>
249258
<TooltipTrigger
250259
render={
@@ -275,7 +284,12 @@ function ThemeColorPicker({
275284
side="bottom"
276285
sideOffset={10}
277286
>
278-
<ThemeColorPickerPanel label={label} onChange={onChange} value={value} />
287+
<ThemeColorPickerPanel
288+
committer={committer}
289+
label={label}
290+
onChange={onChange}
291+
value={value}
292+
/>
279293
</PopoverPopup>
280294
</Popover>
281295
);
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { describe, expect, it, vi } from "vite-plus/test";
2+
import { page } from "vite-plus/test/browser";
3+
4+
import { render } from "../../../test/render";
5+
import { ThemeEditorPanel } from "./ThemeEditorPanel";
6+
7+
function dragHeader(panel: HTMLElement, toX: number, toY: number) {
8+
const header = panel.querySelector<HTMLElement>("h2")!.closest<HTMLElement>(".cursor-grab")!;
9+
const rect = panel.getBoundingClientRect();
10+
const start = { clientX: rect.left + 40, clientY: rect.top + 10 };
11+
const init = { bubbles: true, button: 0, pointerId: 1 };
12+
header.dispatchEvent(new PointerEvent("pointerdown", { ...init, ...start }));
13+
header.dispatchEvent(
14+
new PointerEvent("pointermove", { ...init, clientX: toX + 40, clientY: toY + 10 }),
15+
);
16+
header.dispatchEvent(new PointerEvent("pointerup", init));
17+
}
18+
19+
describe("ThemeEditorPanel", () => {
20+
it("returns to where the user left it when the window shrinks and grows back", async () => {
21+
await page.viewport(1280, 900);
22+
// Synthetic pointer ids are not active pointers, so the browser would reject capture.
23+
using _capture = vi
24+
.spyOn(HTMLElement.prototype, "setPointerCapture")
25+
.mockImplementation(() => {});
26+
// Tailwind is not loaded here; give the panel its fixed, card-sized box.
27+
const style = document.head.appendChild(document.createElement("style"));
28+
style.textContent = "[data-theme-editor-panel]{position:fixed;width:400px;height:300px}";
29+
using _style = { [Symbol.dispose]: () => style.remove() };
30+
await using screen = await render(
31+
<ThemeEditorPanel
32+
open
33+
onOpenChange={() => {}}
34+
onSaved={() => true}
35+
editingTheme={null}
36+
initialAppearance="dark"
37+
restoreTheme={() => {}}
38+
/>,
39+
);
40+
const panel = screen.getByRole("dialog", { name: "Create theme" });
41+
await expect.element(panel).toBeVisible();
42+
43+
dragHeader(panel.element() as HTMLElement, 700, 40);
44+
await expect.poll(() => (panel.element() as HTMLElement).style.left).toBe("700px");
45+
46+
await page.viewport(600, 900);
47+
await expect
48+
.poll(() => Number.parseFloat((panel.element() as HTMLElement).style.left))
49+
.toBeLessThan(600);
50+
51+
await page.viewport(1280, 900);
52+
await expect.poll(() => (panel.element() as HTMLElement).style.left).toBe("700px");
53+
});
54+
});

0 commit comments

Comments
 (0)