Skip to content

Commit 4e43779

Browse files
fix(web): theme editor returns to its spot after the window shrinks and grows back (#25076)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 3a1b3a7 commit 4e43779

6 files changed

Lines changed: 244 additions & 98 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: 51 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, useEffect, 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, the drag surfaces on
72+
// release, and the picker on unmount, 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,15 @@ function ThemeColorPicker({
243247
onChange: (value: string) => void;
244248
onInteract?: () => void;
245249
}) {
250+
const [committer] = useState(createFrameCommitter);
251+
// Unmounting with the popover open (the editor closes mid-drag) never fires onOpenChange.
252+
useEffect(() => committer.flush, [committer]);
246253
return (
247-
<Popover>
254+
<Popover
255+
onOpenChange={(open) => {
256+
if (!open) committer.flush();
257+
}}
258+
>
248259
<Tooltip>
249260
<TooltipTrigger
250261
render={
@@ -275,7 +286,12 @@ function ThemeColorPicker({
275286
side="bottom"
276287
sideOffset={10}
277288
>
278-
<ThemeColorPickerPanel label={label} onChange={onChange} value={value} />
289+
<ThemeColorPickerPanel
290+
committer={committer}
291+
label={label}
292+
onChange={onChange}
293+
value={value}
294+
/>
279295
</PopoverPopup>
280296
</Popover>
281297
);
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
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+
function dragResizeHandle(panel: HTMLElement, byX: number) {
20+
const handle = panel.querySelector<HTMLElement>(".cursor-se-resize")!;
21+
const rect = handle.getBoundingClientRect();
22+
const init = { bubbles: true, button: 0, pointerId: 2 };
23+
const start = { clientX: rect.left + 4, clientY: rect.top + 4 };
24+
handle.dispatchEvent(new PointerEvent("pointerdown", { ...init, ...start }));
25+
handle.dispatchEvent(
26+
new PointerEvent("pointermove", {
27+
...init,
28+
clientX: start.clientX + byX,
29+
clientY: start.clientY,
30+
}),
31+
);
32+
handle.dispatchEvent(new PointerEvent("pointerup", init));
33+
}
34+
35+
async function renderPanel() {
36+
await page.viewport(1280, 900);
37+
const stack = new AsyncDisposableStack();
38+
// Synthetic pointer ids are not active pointers, so the browser would reject capture.
39+
stack.use(vi.spyOn(HTMLElement.prototype, "setPointerCapture").mockImplementation(() => {}));
40+
// Tailwind is not loaded here; give the panel its fixed, card-sized box.
41+
const style = document.head.appendChild(document.createElement("style"));
42+
style.textContent = "[data-theme-editor-panel]{position:fixed;width:400px;height:300px}";
43+
stack.defer(() => style.remove());
44+
const screen = stack.use(
45+
await render(
46+
<ThemeEditorPanel
47+
open
48+
onOpenChange={() => {}}
49+
onSaved={() => true}
50+
editingTheme={null}
51+
initialAppearance="dark"
52+
restoreTheme={() => {}}
53+
/>,
54+
),
55+
);
56+
const panel = screen.getByRole("dialog", { name: "Create theme" });
57+
await expect.element(panel).toBeVisible();
58+
return {
59+
panel: panel.element() as HTMLElement,
60+
[Symbol.asyncDispose]: () => stack.disposeAsync(),
61+
};
62+
}
63+
64+
describe("ThemeEditorPanel", () => {
65+
it("keeps its left edge when resized after the window shrank", async () => {
66+
await using view = await renderPanel();
67+
dragHeader(view.panel, 700, 40);
68+
await expect.poll(() => view.panel.style.left).toBe("700px");
69+
70+
await page.viewport(600, 900);
71+
await expect.poll(() => Number.parseFloat(view.panel.style.left)).toBeLessThan(600);
72+
const clampedLeft = view.panel.style.left;
73+
74+
dragResizeHandle(view.panel, -100);
75+
await expect.poll(() => view.panel.style.width).not.toBe("");
76+
expect(view.panel.style.left).toBe(clampedLeft);
77+
});
78+
79+
it("returns to where the user left it when the window shrinks and grows back", async () => {
80+
await page.viewport(1280, 900);
81+
// Synthetic pointer ids are not active pointers, so the browser would reject capture.
82+
using _capture = vi
83+
.spyOn(HTMLElement.prototype, "setPointerCapture")
84+
.mockImplementation(() => {});
85+
// Tailwind is not loaded here; give the panel its fixed, card-sized box.
86+
const style = document.head.appendChild(document.createElement("style"));
87+
style.textContent = "[data-theme-editor-panel]{position:fixed;width:400px;height:300px}";
88+
using _style = { [Symbol.dispose]: () => style.remove() };
89+
await using screen = await render(
90+
<ThemeEditorPanel
91+
open
92+
onOpenChange={() => {}}
93+
onSaved={() => true}
94+
editingTheme={null}
95+
initialAppearance="dark"
96+
restoreTheme={() => {}}
97+
/>,
98+
);
99+
const panel = screen.getByRole("dialog", { name: "Create theme" });
100+
await expect.element(panel).toBeVisible();
101+
102+
dragHeader(panel.element() as HTMLElement, 700, 40);
103+
await expect.poll(() => (panel.element() as HTMLElement).style.left).toBe("700px");
104+
105+
await page.viewport(600, 900);
106+
await expect
107+
.poll(() => Number.parseFloat((panel.element() as HTMLElement).style.left))
108+
.toBeLessThan(600);
109+
110+
await page.viewport(1280, 900);
111+
await expect.poll(() => (panel.element() as HTMLElement).style.left).toBe("700px");
112+
});
113+
});

0 commit comments

Comments
 (0)