TypeScript
fix(web): theme editor returns to its spot after the window shrinks and grows back (#25076)
Julius Marminge4e43779f82d4
diff --git a/apps/web/src/components/settings/FontFamilyPicker.tsx b/apps/web/src/components/settings/FontFamilyPicker.tsxindex 9c6e5cad1b6..93edc8d327c 100644--- a/apps/web/src/components/settings/FontFamilyPicker.tsx+++ b/apps/web/src/components/settings/FontFamilyPicker.tsx@@ -34,6 +34,7 @@ let enumerationState: FontEnumerationState = supportsFontEnumeration()const enumerationListeners = new Set<() => void>();function subscribeToEnumeration(listener: () => void): () => void {+ probeAlreadyGrantedPermission();enumerationListeners.add(listener);return () => enumerationListeners.delete(listener);}@@ -74,7 +75,6 @@ function probeAlreadyGrantedPermission(): void {}export function useFontEnumeration(): FontEnumerationState {- useEffect(probeAlreadyGrantedPermission, []);return useSyncExternalStore(subscribeToEnumeration, readEnumerationState);}diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxindex eb9854714bc..739185b090a 100644--- a/apps/web/src/components/settings/SettingsPanels.tsx+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -3,7 +3,7 @@ import { NotificationSettings } from "./NotificationSettings";import { PRIVACY_POLICY_URL } from "../../legalLinks";import { CheckIcon, ChevronRightIcon } from "lucide-react";import { Link, useNavigate } from "@tanstack/react-router";-import { useEffect, useRef, useState } from "react";+import { useRef, useState } from "react";import {type DesktopUpdateChannel,IDLE_COMPACTION_MODES,@@ -716,17 +716,12 @@ function LegacyFeaturesSection() {const [open, setOpen] = useState(false);const searchTargetId = useSettingsSearchTargetId();const targetRef = useSettingsSearchTarget<HTMLElement>("legacy-features");- const lastExpandedTargetRef = useRef<string | null>(null);- useEffect(() => {- if (searchTargetId === null) {- lastExpandedTargetRef.current = null;- return;- }- if (!LEGACY_FEATURE_TARGET_IDS.has(searchTargetId)) return;- if (lastExpandedTargetRef.current === searchTargetId) return;- lastExpandedTargetRef.current = searchTargetId;- setOpen(true);- }, [searchTargetId]);+ // A search jump to a legacy setting opens the fold before its row mounts.+ const [seenSearchTargetId, setSeenSearchTargetId] = useState<string | null>(null);+ if (seenSearchTargetId !== searchTargetId) {+ setSeenSearchTargetId(searchTargetId);+ if (searchTargetId !== null && LEGACY_FEATURE_TARGET_IDS.has(searchTargetId)) setOpen(true);+ }return (<section id="legacy-features" ref={targetRef} tabIndex={-1} className="space-y-2.5">diff --git a/apps/web/src/components/settings/ThemeColorPicker.tsx b/apps/web/src/components/settings/ThemeColorPicker.tsxindex 7eb64cf9243..1bf7c23cf7e 100644--- a/apps/web/src/components/settings/ThemeColorPicker.tsx+++ b/apps/web/src/components/settings/ThemeColorPicker.tsx@@ -1,5 +1,4 @@-import { memo, useEffect, useEffectEvent, useRef, useState } from "react";-import { useStableCallback } from "../../hooks/useStableCallback";+import { memo, useEffect, useState } from "react";import { isThemeColor, themeColorToHex, type ThemeColorRole } from "../../themePalette";import { cn } from "../../lib/utils";import { hexToHsv, hsvToHex, type HsvColor } from "../../lib/color";@@ -67,13 +66,46 @@ function themeRgbValue(hex: string) {return themeHexToRgb(hex).join(", ");}+// Local state updates immediately for a smooth thumb; the parent commit+// (which can regenerate a whole guided palette) is batched to one call per+// animation frame. The popover flushes it on close, the drag surfaces on+// release, and the picker on unmount, so the final frame is never lost.+function createFrameCommitter() {+ let pending: { readonly color: string; readonly commit: (color: string) => void } | null = null;+ let frame: number | null = null;+ const flush = () => {+ if (frame !== null) {+ cancelAnimationFrame(frame);+ frame = null;+ }+ const next = pending;+ pending = null;+ next?.commit(next.color);+ };+ return {+ schedule(color: string, commit: (color: string) => void) {+ pending = { color, commit };+ if (frame !== null) return;+ frame = requestAnimationFrame(() => {+ frame = null;+ flush();+ });+ },+ flush,+ };+}++type FrameCommitter = ReturnType<typeof createFrameCommitter>;+function ThemeColorPickerPanel({label,value,+ committer,onChange,}: {label: string;value: string;+ committer: FrameCommitter;onChange: (value: string) => void;}) {const normalizedValue = normalizeThemePickerColor(value);@@ -98,40 +130,12 @@ function ThemeColorPickerPanel({if (currentColor !== normalizedValue) setHsv(hexToHsv(normalizedValue));}- // Update the thumb immediately; batch expensive parent palette regeneration to one commit per frame.- const commitColor = useStableCallback(onChange);- const pendingCommitRef = useRef<string | null>(null);- const commitFrameRef = useRef<number | null>(null);- // Flush the last drag frame if the popover closes or the pointer lifts before animation frame.- const flushPendingCommit = () => {- if (commitFrameRef.current !== null) {- cancelAnimationFrame(commitFrameRef.current);- commitFrameRef.current = null;- }- const pending = pendingCommitRef.current;- pendingCommitRef.current = null;- if (pending !== null) commitColor(pending);- };- // Flush only on unmount; rerunning this cleanup mid-drag would commit early.- const flushOnUnmount = useEffectEvent(() => flushPendingCommit());- useEffect(() => () => flushOnUnmount(), []);- const scheduleCommit = (color: string) => {- pendingCommitRef.current = color;- if (commitFrameRef.current !== null) return;- commitFrameRef.current = requestAnimationFrame(() => {- commitFrameRef.current = null;- const pending = pendingCommitRef.current;- pendingCommitRef.current = null;- if (pending !== null) commitColor(pending);- });- };-const commitHsv = (nextHsv: HsvColor) => {setHsv(nextHsv);const nextColor = hsvToHex(nextHsv.h, nextHsv.s, nextHsv.v);setHexDraft(nextColor);setRgbDraft(themeRgbValue(nextColor));- scheduleCommit(nextColor + alphaSuffix);+ committer.schedule(nextColor + alphaSuffix, onChange);};const handleHexChange = (nextValue: string) => {@@ -169,13 +173,13 @@ function ThemeColorPickerPanel({label={label}value={hsv}onChange={commitHsv}- onInteractionEnd={flushPendingCommit}+ onInteractionEnd={committer.flush}/><ColorHueSliderlabel={`${label} hue`}value={hsv.h}onChange={(h) => commitHsv({ ...hsv, h })}- onInteractionEnd={flushPendingCommit}+ onInteractionEnd={committer.flush}/><div className="grid grid-cols-[1fr_1.2fr] gap-2"><label className="grid min-w-0 gap-1">@@ -243,8 +247,15 @@ function ThemeColorPicker({onChange: (value: string) => void;onInteract?: () => void;}) {+ const [committer] = useState(createFrameCommitter);+ // Unmounting with the popover open (the editor closes mid-drag) never fires onOpenChange.+ useEffect(() => committer.flush, [committer]);return (- <Popover>+ <Popover+ onOpenChange={(open) => {+ if (!open) committer.flush();+ }}+ ><Tooltip><TooltipTriggerrender={@@ -275,7 +286,12 @@ function ThemeColorPicker({side="bottom"sideOffset={10}>- <ThemeColorPickerPanel label={label} onChange={onChange} value={value} />+ <ThemeColorPickerPanel+ committer={committer}+ label={label}+ onChange={onChange}+ value={value}+ /></PopoverPopup></Popover>);diff --git a/apps/web/src/components/settings/ThemeEditorPanel.browser.test.tsx b/apps/web/src/components/settings/ThemeEditorPanel.browser.test.tsxnew file mode 100644index 00000000000..a2802f544f2--- /dev/null+++ b/apps/web/src/components/settings/ThemeEditorPanel.browser.test.tsx@@ -0,0 +1,113 @@+import { describe, expect, it, vi } from "vite-plus/test";+import { page } from "vite-plus/test/browser";++import { render } from "../../../test/render";+import { ThemeEditorPanel } from "./ThemeEditorPanel";++function dragHeader(panel: HTMLElement, toX: number, toY: number) {+ const header = panel.querySelector<HTMLElement>("h2")!.closest<HTMLElement>(".cursor-grab")!;+ const rect = panel.getBoundingClientRect();+ const start = { clientX: rect.left + 40, clientY: rect.top + 10 };+ const init = { bubbles: true, button: 0, pointerId: 1 };+ header.dispatchEvent(new PointerEvent("pointerdown", { ...init, ...start }));+ header.dispatchEvent(+ new PointerEvent("pointermove", { ...init, clientX: toX + 40, clientY: toY + 10 }),+ );+ header.dispatchEvent(new PointerEvent("pointerup", init));+}++function dragResizeHandle(panel: HTMLElement, byX: number) {+ const handle = panel.querySelector<HTMLElement>(".cursor-se-resize")!;+ const rect = handle.getBoundingClientRect();+ const init = { bubbles: true, button: 0, pointerId: 2 };+ const start = { clientX: rect.left + 4, clientY: rect.top + 4 };+ handle.dispatchEvent(new PointerEvent("pointerdown", { ...init, ...start }));+ handle.dispatchEvent(+ new PointerEvent("pointermove", {+ ...init,+ clientX: start.clientX + byX,+ clientY: start.clientY,+ }),+ );+ handle.dispatchEvent(new PointerEvent("pointerup", init));+}++async function renderPanel() {+ await page.viewport(1280, 900);+ const stack = new AsyncDisposableStack();+ // Synthetic pointer ids are not active pointers, so the browser would reject capture.+ stack.use(vi.spyOn(HTMLElement.prototype, "setPointerCapture").mockImplementation(() => {}));+ // Tailwind is not loaded here; give the panel its fixed, card-sized box.+ const style = document.head.appendChild(document.createElement("style"));+ style.textContent = "[data-theme-editor-panel]{position:fixed;width:400px;height:300px}";+ stack.defer(() => style.remove());+ const screen = stack.use(+ await render(+ <ThemeEditorPanel+ open+ onOpenChange={() => {}}+ onSaved={() => true}+ editingTheme={null}+ initialAppearance="dark"+ restoreTheme={() => {}}+ />,+ ),+ );+ const panel = screen.getByRole("dialog", { name: "Create theme" });+ await expect.element(panel).toBeVisible();+ return {+ panel: panel.element() as HTMLElement,+ [Symbol.asyncDispose]: () => stack.disposeAsync(),+ };+}++describe("ThemeEditorPanel", () => {+ it("keeps its left edge when resized after the window shrank", async () => {+ await using view = await renderPanel();+ dragHeader(view.panel, 700, 40);+ await expect.poll(() => view.panel.style.left).toBe("700px");++ await page.viewport(600, 900);+ await expect.poll(() => Number.parseFloat(view.panel.style.left)).toBeLessThan(600);+ const clampedLeft = view.panel.style.left;++ dragResizeHandle(view.panel, -100);+ await expect.poll(() => view.panel.style.width).not.toBe("");+ expect(view.panel.style.left).toBe(clampedLeft);+ });++ it("returns to where the user left it when the window shrinks and grows back", async () => {+ await page.viewport(1280, 900);+ // Synthetic pointer ids are not active pointers, so the browser would reject capture.+ using _capture = vi+ .spyOn(HTMLElement.prototype, "setPointerCapture")+ .mockImplementation(() => {});+ // Tailwind is not loaded here; give the panel its fixed, card-sized box.+ const style = document.head.appendChild(document.createElement("style"));+ style.textContent = "[data-theme-editor-panel]{position:fixed;width:400px;height:300px}";+ using _style = { [Symbol.dispose]: () => style.remove() };+ await using screen = await render(+ <ThemeEditorPanel+ open+ onOpenChange={() => {}}+ onSaved={() => true}+ editingTheme={null}+ initialAppearance="dark"+ restoreTheme={() => {}}+ />,+ );+ const panel = screen.getByRole("dialog", { name: "Create theme" });+ await expect.element(panel).toBeVisible();++ dragHeader(panel.element() as HTMLElement, 700, 40);+ await expect.poll(() => (panel.element() as HTMLElement).style.left).toBe("700px");++ await page.viewport(600, 900);+ await expect+ .poll(() => Number.parseFloat((panel.element() as HTMLElement).style.left))+ .toBeLessThan(600);++ await page.viewport(1280, 900);+ await expect.poll(() => (panel.element() as HTMLElement).style.left).toBe("700px");+ });+});diff --git a/apps/web/src/components/settings/ThemeEditorPanel.tsx b/apps/web/src/components/settings/ThemeEditorPanel.tsxindex 329493fe3f9..9b71401c79b 100644--- a/apps/web/src/components/settings/ThemeEditorPanel.tsx+++ b/apps/web/src/components/settings/ThemeEditorPanel.tsx@@ -22,6 +22,7 @@ import {type ThemeColorRole,type ThemeDefinition,} from "../../themePalette";+import { useViewportSize } from "../../hooks/useViewportSize";import { cn } from "../../lib/utils";import { Button } from "../ui/button";import { MorphIcon } from "~/components/MorphIcon";@@ -271,21 +272,28 @@ function getManagedEditorColors();}+const PANEL_MARGIN = 8;+const PANEL_MIN_WIDTH = 280;+const PANEL_MIN_HEIGHT = 220;++/** Keeps the panel horizontally inside the viewport. Vertically only its header must stay+ * visible, so users can park the panel low to see the app behind it. */function clampPanelPosition(- panel: HTMLElement | null,+ viewport: { readonly width: number; readonly height: number },x: number,y: number,- widthOverride?: number,+ width: number,) {- const margin = 8;- // Use the caller's new width after shrink; DOM width stays stale until commit.- const width = widthOverride ?? panel?.offsetWidth ?? 0;+ const maxX = Math.max(PANEL_MARGIN, viewport.width - width - PANEL_MARGIN);+ const maxY = Math.max(PANEL_MARGIN, viewport.height - 48);return {- x: Math.min(Math.max(x, margin), Math.max(margin, window.innerWidth - width - margin)),- y: Math.min(Math.max(y, margin), Math.max(margin, window.innerHeight - 48)),+ x: Math.min(Math.max(x, PANEL_MARGIN), maxX),+ y: Math.min(Math.max(y, PANEL_MARGIN), maxY),};}+const readWindowViewport = () => ({ width: window.innerWidth, height: window.innerHeight });+// Kept out of the component: the compiler cannot lower a throw inside try/catch.function retireMergedTheme(retired: ThemeDefinition, mergeTarget: ThemeDefinition) {try {@@ -341,10 +349,12 @@ export function ThemeEditorPanel({const [isInspecting, setIsInspecting] = useState(false);const [selectedRole, setSelectedRole] = useState<ThemeColorRole | null>(null);const [usageCount, setUsageCount] = useState<number | null>(null);- const [position, setPosition] = useState<{ x: number; y: number } | null>(null);+ // The rendered width is CSS-sized unless the user resized the panel, so the position+ // remembers the width measured at the last drag or resize.+ const [position, setPosition] = useState<{ x: number; y: number; width: number } | null>(null);const [size, setSize] = useState<{ width: number; height: number } | null>(null);const panelRef = useRef<HTMLDivElement>(null);- const dragOffsetRef = useRef<{ dx: number; dy: number } | null>(null);+ const dragOffsetRef = useRef<{ dx: number; dy: number; width: number } | null>(null);const resizeStartRef = useRef<{pointerX: number;pointerY: number;@@ -353,32 +363,6 @@ export function ThemeEditorPanel({width: number;height: number;} | null>(null);- useEffect(() => {- if (!open) return;- const clamp = () => {- const margin = 8;- let clampedWidth: number | undefined;- let clampedHeight: number | undefined;- setSize((current) => {- if (!current) return current;- clampedWidth = Math.max(280, Math.min(current.width, window.innerWidth - margin * 2));- clampedHeight = Math.max(220, Math.min(current.height, window.innerHeight - margin * 2));- return { width: clampedWidth, height: clampedHeight };- });- setPosition((current) => {- if (!current) return current;- const clamped = clampPanelPosition(panelRef.current, current.x, current.y, clampedWidth);- const height = isMinimized- ? (panelRef.current?.offsetHeight ?? 0)- : (clampedHeight ?? panelRef.current?.offsetHeight ?? 0);- const maxY = Math.max(margin, window.innerHeight - height - margin);- return { x: clamped.x, y: Math.min(clamped.y, maxY) };- });- };- window.addEventListener("resize", clamp);- return () => window.removeEventListener("resize", clamp);- }, [isMinimized, open]);-// Seed during render so the first open frame cannot preview the previous session's colors.const [seededOpen, setSeededOpen] = useState(false);if (seededOpen !== open) {@@ -1010,20 +994,39 @@ export function ThemeEditorPanel({);};- const clampPosition = (x: number, y: number) => clampPanelPosition(panelRef.current, x, y);+ // Geometry is stored as the user left it and fitted to the current viewport here, so a+ // window that shrinks and grows back returns the panel to where it was.+ const viewport = useViewportSize();+ const shownSize = size && {+ width: Math.max(PANEL_MIN_WIDTH, Math.min(size.width, viewport.width - PANEL_MARGIN * 2)),+ height: Math.max(PANEL_MIN_HEIGHT, Math.min(size.height, viewport.height - PANEL_MARGIN * 2)),+ };+ const shownPosition =+ position &&+ clampPanelPosition(viewport, position.x, position.y, shownSize?.width ?? position.width);const handleDragPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {if ((event.target as HTMLElement).closest("button, input, a")) return;const rect = panelRef.current?.getBoundingClientRect();if (!rect) return;- dragOffsetRef.current = { dx: event.clientX - rect.x, dy: event.clientY - rect.y };+ dragOffsetRef.current = {+ dx: event.clientX - rect.x,+ dy: event.clientY - rect.y,+ width: rect.width,+ };event.currentTarget.setPointerCapture(event.pointerId);};const handleDragPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {const offset = dragOffsetRef.current;if (!offset) return;- setPosition(clampPosition(event.clientX - offset.dx, event.clientY - offset.dy));+ const next = clampPanelPosition(+ readWindowViewport(),+ event.clientX - offset.dx,+ event.clientY - offset.dy,+ offset.width,+ );+ setPosition({ ...next, width: offset.width });};const endDrag = () => {@@ -1034,8 +1037,10 @@ export function ThemeEditorPanel({const rect = panelRef.current?.getBoundingClientRect();if (!rect) return;event.preventDefault();- // Convert bottom-right parking to explicit position before resizing so the top-left corner stays fixed.- if (position === null) setPosition(clampPosition(rect.x, rect.y));+ // Resize from where the panel is drawn, so a position clamped after the window shrank, or bottom-right+ // parking, can't make the top-left corner slide.+ const next = clampPanelPosition(readWindowViewport(), rect.x, rect.y, rect.width);+ setPosition({ ...next, width: rect.width });resizeStartRef.current = {pointerX: event.clientX,pointerY: event.clientY,@@ -1050,15 +1055,15 @@ export function ThemeEditorPanel({const handleResizePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {const start = resizeStartRef.current;if (!start) return;- const margin = 8;- const MIN_WIDTH = 280;- const MIN_HEIGHT = 220;- const maxWidth = Math.max(MIN_WIDTH, window.innerWidth - margin - start.left);- const maxHeight = Math.max(MIN_HEIGHT, window.innerHeight - margin - start.top);+ const maxWidth = Math.max(PANEL_MIN_WIDTH, window.innerWidth - PANEL_MARGIN - start.left);+ const maxHeight = Math.max(PANEL_MIN_HEIGHT, window.innerHeight - PANEL_MARGIN - start.top);setSize({- width: Math.min(Math.max(start.width + event.clientX - start.pointerX, MIN_WIDTH), maxWidth),+ width: Math.min(+ Math.max(start.width + event.clientX - start.pointerX, PANEL_MIN_WIDTH),+ maxWidth,+ ),height: Math.min(- Math.max(start.height + event.clientY - start.pointerY, MIN_HEIGHT),+ Math.max(start.height + event.clientY - start.pointerY, PANEL_MIN_HEIGHT),maxHeight,),});@@ -1080,9 +1085,11 @@ export function ThemeEditorPanel({ref={panelRef}role="dialog"style={{- ...(position ? { left: position.x, top: position.y } : {}),- ...(size ? { width: size.width } : {}),- ...(size && !isMinimized ? { height: size.height, maxHeight: "calc(100dvh - 1rem)" } : {}),+ ...(shownPosition ? { left: shownPosition.x, top: shownPosition.y } : {}),+ ...(shownSize ? { width: shownSize.width } : {}),+ ...(shownSize && !isMinimized+ ? { height: shownSize.height, maxHeight: "calc(100dvh - 1rem)" }+ : {}),}}><divdiff --git a/apps/web/src/hooks/useViewportSize.ts b/apps/web/src/hooks/useViewportSize.tsnew file mode 100644index 00000000000..0f8015fc9f0--- /dev/null+++ b/apps/web/src/hooks/useViewportSize.ts@@ -0,0 +1,15 @@+import { useSyncExternalStore } from "react";++const subscribeToViewport = (onChange: () => void) => {+ window.addEventListener("resize", onChange);+ return () => window.removeEventListener("resize", onChange);+};+const readViewportWidth = () => window.innerWidth;+const readViewportHeight = () => window.innerHeight;++/** The window's CSS viewport, re-read on every resize. */+export function useViewportSize() {+ const width = useSyncExternalStore(subscribeToViewport, readViewportWidth);+ const height = useSyncExternalStore(subscribeToViewport, readViewportHeight);+ return { width, height };+}