@devries-cameron20 / t3code Mirror · read-only / commits / 9d7997afc5
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 15:45 UTC

refactor(web): resize drags, panel shells and the browser host own their listeners (#25464)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 26, 2026 at 05:31 UTC 9d7997afc5db09462e140de19f799c709655094c
12 files changed +435 -314
apps/web/src/appInit.tsx
+2
@@ -4,6 +4,7 @@ import { createBrowserHistory, createHashHistory } from "@tanstack/react-router"
4
5 import { applyAppearanceContrast } from "./appearanceContrast";
6 import { applyAppearanceFontVariables } from "./appearanceFonts";
7 +import { startElectronBrowserHost } from "./browser/ElectronBrowserHost";
8 import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention";
9 import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer";
10 import { startSshPasswordPromptQueue } from "./components/desktop/SshPasswordPromptDialog";
@@ -142,6 +143,7 @@ export function startAppServices(): AppRouter {
143 startDefaultThemeAdoption();
144 startModelPreferencesMigration();
145 startAgentOpenedPreviews();
146 + if (isElectron) startElectronBrowserHost();
147 startThreadOverlayRetention(router);
148 startMainAppLocationTracking(router);
149 startBackgroundThreadAnnouncements(appAtomRegistry, router);
apps/web/src/browser/BrowserSurfaceSlot.tsx
+4 -6
@@ -21,13 +21,11 @@ export function BrowserSurfaceSlot(props: {
21 className,
22 fitSourceContent = false,
23 } = props;
24 - const elementRef = useRef<HTMLDivElement | null>(null);
24 const presentationRef = useRef({ visible, cornerRadius, zIndex });
25 const updateRef = useRef<(() => void) | null>(null);
26
28 - useLayoutEffect(() => {
29 - const element = elementRef.current;
30 - if (!element) return;
27 + // The lease lives as long as this element for one tab, so the ref callback owns it.
28 + const attachSurface = (element: HTMLDivElement) => {
29 let lease = acquireBrowserSurface(tabId, fitSourceContent);
30 const update = () => {
31 const rect = element.getBoundingClientRect();
@@ -77,7 +75,7 @@ export function BrowserSurfaceSlot(props: {
75 if (updateRef.current === update) updateRef.current = null;
76 lease.release();
77 };
80 - }, [fitSourceContent, tabId]);
78 + };
79
80 useLayoutEffect(() => {
81 presentationRef.current = { visible, cornerRadius, zIndex };
@@ -90,5 +88,5 @@ export function BrowserSurfaceSlot(props: {
88 zIndex,
89 ]);
90
93 - return <div ref={elementRef} className={className} data-browser-surface-slot={tabId} />;
91 + return <div ref={attachSurface} className={className} data-browser-surface-slot={tabId} />;
92 }
apps/web/src/browser/ElectronBrowserHost.tsx
+80 -62
@@ -1,21 +1,28 @@
1 import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
2 import {
3 AuthPreviewOperateScope,
4 + type DesktopPreviewBridge,
5 type DesktopPreviewOpenLinkEvent,
6 + type EnvironmentId,
7 FILL_PREVIEW_VIEWPORT,
8 } from "@t3tools/contracts";
9 import { useAtomValue } from "@effect/atom-react";
8 -import { type ComponentProps, useEffect, useEffectEvent, useState } from "react";
10 +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
11 +import { type ComponentProps, useState } from "react";
12
13 import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment";
14
15 import { isElectron } from "~/env";
16 import { useClientSettingsHydrated } from "~/hooks/useSettings";
17 import { useDesktopHostedPreviewSessions } from "~/components/preview/usePreviewSession";
15 -import { useActivePreviewSessions } from "~/previewStateStore";
18 +import {
19 + readActivePreviewSessions,
20 + type ThreadPreviewState,
21 + useActivePreviewSessions,
22 +} from "~/previewStateStore";
23 +import { appAtomRegistry } from "~/rpc/atomRegistry";
24 import { previewEnvironment } from "~/state/preview";
25 import { useEnvironmentScope } from "~/state/session";
18 -import { useAtomCommand } from "~/state/use-atom-command";
26
27 import { readPreviewAnnotationTheme } from "./annotationTheme";
28 import { useBrowserDefaults } from "./browserDefaults";
@@ -25,10 +32,11 @@ import { openUrlInPreview } from "./openFileInPreview";
32 import { rendersServerTabNatively } from "./previewRuntime";
33 import { previewRuntimeTabId } from "./previewRuntimeTabId";
34
28 -export function ElectronBrowserHost() {
29 - const previewByThreadKey = useActivePreviewSessions();
30 - const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom);
31 - useDesktopHostedPreviewSessions(primaryEnvironmentId);
35 +/** Every session this window renders as a hosted webview, in a fixed (non-display) order. */
36 +function hostedBrowserSessions(
37 + previewByThreadKey: Record<string, ThreadPreviewState>,
38 + primaryEnvironmentId: EnvironmentId | null,
39 +) {
40 const activeSessions = Object.entries(previewByThreadKey).flatMap(([threadKey, previewState]) => {
41 const threadRef = parseScopedThreadKey(threadKey);
42 return threadRef
@@ -50,68 +58,78 @@ export function ElectronBrowserHost() {
58 });
59 // Electron destroys a moved webview's guest, so the render order must not follow the server's
60 // updatedAt order. Any fixed order works; this one is not a display order.
53 - const sessions = activeSessions.toSorted((left, right) =>
61 + return activeSessions.toSorted((left, right) =>
62 left.runtimeTabId < right.runtimeTabId ? -1 : left.runtimeTabId > right.runtimeTabId ? 1 : 0,
63 );
64 +}
65
57 - useEffect(() => {
58 - const preview = window.desktopBridge?.preview;
59 - if (!preview) return;
60 -
61 - let lastSerializedTheme = "";
62 - const syncTheme = () => {
63 - const theme = readPreviewAnnotationTheme();
64 - const serializedTheme = JSON.stringify(theme);
65 - if (serializedTheme === lastSerializedTheme) return;
66 - lastSerializedTheme = serializedTheme;
67 - void preview.setAnnotationTheme(theme).catch(() => {
68 - lastSerializedTheme = "";
69 - });
70 - };
71 - const frameId = window.requestAnimationFrame(syncTheme);
72 - const observer = new MutationObserver(syncTheme);
73 - observer.observe(document.documentElement, {
74 - attributes: true,
75 - attributeFilter: ["class", "style"],
76 - });
77 - const headObserver = new MutationObserver(syncTheme);
78 - headObserver.observe(document.head, {
79 - childList: true,
80 - subtree: true,
81 - characterData: true,
66 +function startAnnotationThemeSync(preview: DesktopPreviewBridge): () => void {
67 + let lastSerializedTheme = "";
68 + const syncTheme = () => {
69 + const theme = readPreviewAnnotationTheme();
70 + const serializedTheme = JSON.stringify(theme);
71 + if (serializedTheme === lastSerializedTheme) return;
72 + lastSerializedTheme = serializedTheme;
73 + void preview.setAnnotationTheme(theme).catch(() => {
74 + lastSerializedTheme = "";
75 });
83 - return () => {
84 - window.cancelAnimationFrame(frameId);
85 - observer.disconnect();
86 - headObserver.disconnect();
87 - };
88 - }, []);
76 + };
77 + // App services start before the first paint, when the theme styles may not be applied yet.
78 + const frameId = window.requestAnimationFrame(syncTheme);
79 + const observer = new MutationObserver(syncTheme);
80 + observer.observe(document.documentElement, {
81 + attributes: true,
82 + attributeFilter: ["class", "style"],
83 + });
84 + const headObserver = new MutationObserver(syncTheme);
85 + headObserver.observe(document.head, {
86 + childList: true,
87 + subtree: true,
88 + characterData: true,
89 + });
90 + return () => {
91 + window.cancelAnimationFrame(frameId);
92 + observer.disconnect();
93 + headObserver.disconnect();
94 + };
95 +}
96
90 - useEffect(() => {
91 - const preview = window.desktopBridge?.preview;
92 - if (!preview) return;
93 - return preview.onPointerEvent((event) => {
97 +function openLinkInPreview({ tabId, url, background }: DesktopPreviewOpenLinkEvent): void {
98 + const source = hostedBrowserSessions(
99 + readActivePreviewSessions(),
100 + appAtomRegistry.get(primaryEnvironmentIdAtom),
101 + ).find((session) => session.runtimeTabId === tabId);
102 + if (!source) return;
103 + void openUrlInPreview({
104 + threadRef: source.threadRef,
105 + url,
106 + openPreview: (input) => runAtomCommand(appAtomRegistry, previewEnvironment.open, input),
107 + profileId: source.snapshot.profileId,
108 + background,
109 + });
110 +}
111 +
112 +/** App-lifetime listeners for the desktop preview bridge: annotation theme, agent pointer, links. */
113 +export function startElectronBrowserHost(): () => void {
114 + const preview = window.desktopBridge?.preview;
115 + if (!preview) return () => {};
116 + const disposers = [
117 + startAnnotationThemeSync(preview),
118 + preview.onPointerEvent((event) => {
119 useBrowserPointerStore.getState().apply(event);
95 - });
96 - }, []);
120 + }),
121 + preview.onOpenLink(openLinkInPreview),
122 + ];
123 + return () => {
124 + for (const dispose of disposers) dispose();
125 + };
126 +}
127
98 - const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: true });
99 - const onOpenLink = useEffectEvent(({ tabId, url, background }: DesktopPreviewOpenLinkEvent) => {
100 - const source = sessions.find((session) => session.runtimeTabId === tabId);
101 - if (!source) return;
102 - void openUrlInPreview({
103 - threadRef: source.threadRef,
104 - url,
105 - openPreview,
106 - profileId: source.snapshot.profileId,
107 - background,
108 - });
109 - });
110 - useEffect(() => {
111 - const preview = window.desktopBridge?.preview;
112 - if (!preview) return;
113 - return preview.onOpenLink(onOpenLink);
114 - }, []);
128 +export function ElectronBrowserHost() {
129 + const previewByThreadKey = useActivePreviewSessions();
130 + const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom);
131 + useDesktopHostedPreviewSessions(primaryEnvironmentId);
132 + const sessions = hostedBrowserSessions(previewByThreadKey, primaryEnvironmentId);
133
134 if (!isElectron) return null;
135 return (
apps/web/src/components/RightPanelTabs.tsx
+20 -28
@@ -981,10 +981,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
981 return () => document.removeEventListener("keydown", onNewSurfaceKeyDown, true);
982 }, [props.open]);
983
984 - const updateTabScrollState = () => {
985 - const viewport = tabScrollViewport(tabListRef.current);
986 - if (!viewport) return;
987 -
984 + const updateTabScrollState = (viewport: HTMLDivElement) => {
985 const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE;
986 const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE;
987 const canScrollRight =
@@ -1183,34 +1180,19 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
1180 setRenamingDevice(null);
1181 });
1182
1183 + // A newly active tab, or tabs that start overflowing, can sit outside the scrolled strip.
1184 useEffect(() => {
1185 if (!props.activeSurfaceId || !tabScrollState.hasOverflow) return;
1186 const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
1187 activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" });
1188 }, [props.activeSurfaceId, tabScrollState.hasOverflow]);
1189
1192 - useEffect(() => {
1193 - const viewport = tabScrollViewport(tabListRef.current);
1194 - if (!viewport) return;
1195 -
1196 - const content = viewport.firstElementChild;
1197 - const stopObserving = observeResize(
1198 - content ? [viewport, content] : viewport,
1199 - updateTabScrollState,
1200 - );
1201 - viewport.addEventListener("scroll", updateTabScrollState, { passive: true });
1202 - updateTabScrollState();
1203 -
1204 - return () => {
1205 - stopObserving();
1206 - viewport.removeEventListener("scroll", updateTabScrollState);
1207 - };
1208 - }, [updateTabScrollState]);
1209 -
1210 - useEffect(() => {
1211 - const viewport = tabScrollViewport(tabListRef.current);
1190 + const attachTabList = (root: HTMLDivElement | null) => {
1191 + tabListRef.current = root;
1192 + const viewport = tabScrollViewport(root);
1193 if (!viewport) return;
1194
1195 + const update = () => updateTabScrollState(viewport);
1196 const handleWheel = (event: WheelEvent) => {
1197 if (event.ctrlKey) return;
1198 let delta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;
@@ -1222,12 +1204,22 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
1204 viewport.scrollLeft += delta;
1205 if (viewport.scrollLeft === previousScrollLeft) return;
1206 event.preventDefault();
1225 - updateTabScrollState();
1207 + update();
1208 };
1209
1210 + const content = viewport.firstElementChild;
1211 + const stopObserving = observeResize(content ? [viewport, content] : viewport, update);
1212 + viewport.addEventListener("scroll", update, { passive: true });
1213 viewport.addEventListener("wheel", handleWheel, { passive: false });
1229 - return () => viewport.removeEventListener("wheel", handleWheel);
1230 - }, [updateTabScrollState]);
1214 + update();
1215 +
1216 + return () => {
1217 + tabListRef.current = null;
1218 + stopObserving();
1219 + viewport.removeEventListener("scroll", update);
1220 + viewport.removeEventListener("wheel", handleWheel);
1221 + };
1222 + };
1223
1224 return (
1225 <PreviewPanelShell
@@ -1250,7 +1242,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
1242 >
1243 <ScrollArea
1244 radius="none"
1253 - ref={tabListRef}
1245 + ref={attachTabList}
1246 hideScrollbars
1247 scrollFade
1248 className="min-w-0 flex-1"
apps/web/src/components/chat/ChatRightPanel.tsx
+1 -1
@@ -27,7 +27,7 @@ export function ChatRightPanel(props: ChatRightPanelProps) {
27 layoutControls,
28 ...tabs
29 } = props;
30 - const inlineSize = usePreviewPanelInlineSize(undefined, {
30 + const inlineSize = usePreviewPanelInlineSize({
31 container: workspaceLayoutElement,
32 widthStorageKey,
33 });
apps/web/src/components/preview/PreviewPanelShell.tsx
+25 -42
@@ -1,11 +1,4 @@
1 -import {
2 - type CSSProperties,
3 - type ReactNode,
4 - type RefObject,
5 - useLayoutEffect,
6 - useRef,
7 - useState,
8 -} from "react";
1 +import { type CSSProperties, type ReactNode, useLayoutEffect, useRef, useState } from "react";
2 import {
3 type PreviewPanelInlineSize,
4 usePreviewPanelInlineSize,
@@ -37,65 +30,55 @@ export function PreviewPanelShell(props: PreviewPanelShellProps) {
30 }
31
32 function ResizablePreviewPanelShell(props: PreviewPanelShellProps) {
40 - const hostRef = useRef<HTMLDivElement | null>(null);
41 - const inlineSize = usePreviewPanelInlineSize(hostRef, {
33 + const inlineSize = usePreviewPanelInlineSize({
34 enabled: props.mode === "inline" && !props.maximized,
35 widthStorageKey: props.widthStorageKey,
36 defaultWidth: props.defaultWidth,
37 });
46 - return <PreviewPanelShellFrame {...props} inlineSize={inlineSize} hostRef={hostRef} />;
38 + return <PreviewPanelShellFrame {...props} inlineSize={inlineSize} />;
39 }
40
41 function PreviewPanelShellFrame(
50 - props: PreviewPanelShellProps & {
51 - inlineSize: PreviewPanelInlineSize;
52 - hostRef?: RefObject<HTMLDivElement | null>;
53 - },
42 + props: PreviewPanelShellProps & { inlineSize: PreviewPanelInlineSize },
43 ) {
44 const isInline = props.mode === "inline";
45 const collapsible = isInline && props.open !== undefined;
46 const open = props.open ?? true;
47 const maximized = props.maximized ?? false;
59 - const localHostRef = useRef<HTMLDivElement | null>(null);
60 - const hostRef = props.hostRef ?? localHostRef;
48 + const hostRef = useRef<HTMLDivElement | null>(null);
49 const returnedFocus = useRef(false);
62 - const { width, handlers } = props.inlineSize;
63 - // Suppress transitions before commit so resize/maximize changes never start width transitions.
64 - const [layoutTransition, setLayoutTransition] = useState(() => ({
50 + const { width, handlers, observeRow } = props.inlineSize;
51 + // Width animates only for an open or close. Any other width change disables
52 + // the transition in the same commit that changes the width, so the browser
53 + // never starts one; the next open or close re-enables it in its own commit,
54 + // so nothing waits for a paint.
55 + const [widthTransition, setWidthTransition] = useState(() => ({
56 open,
57 width,
58 maximized,
68 - suppressed: false,
59 + enabled: true,
60 }));
61 if (
71 - layoutTransition.open !== open ||
72 - layoutTransition.width !== width ||
73 - layoutTransition.maximized !== maximized
62 + widthTransition.open !== open ||
63 + widthTransition.width !== width ||
64 + widthTransition.maximized !== maximized
65 ) {
75 - setLayoutTransition({
66 + setWidthTransition({
67 open,
68 width,
69 maximized,
79 - suppressed:
80 - collapsible &&
81 - layoutTransition.open === open &&
82 - (layoutTransition.width !== width || layoutTransition.maximized !== maximized),
70 + enabled: widthTransition.open !== open,
71 });
72 }
85 - const suppressWidthTransition = layoutTransition.suppressed;
86 - useLayoutEffect(() => {
87 - if (!suppressWidthTransition) return;
88 - let restoreFrame = 0;
89 - const paintFrame = window.requestAnimationFrame(() => {
90 - restoreFrame = window.requestAnimationFrame(() => {
91 - setLayoutTransition((current) => ({ ...current, suppressed: false }));
92 - });
93 - });
73 + const suppressWidthTransition = collapsible && !widthTransition.enabled;
74 + const attachHost = (host: HTMLDivElement) => {
75 + hostRef.current = host;
76 + const stopObservingRow = observeRow(host);
77 return () => {
95 - window.cancelAnimationFrame(paintFrame);
96 - window.cancelAnimationFrame(restoreFrame);
78 + hostRef.current = null;
79 + stopObservingRow();
80 };
98 - }, [suppressWidthTransition]);
81 + };
82 useLayoutEffect(() => {
83 const host = hostRef.current;
84 if (!host || !collapsible) return;
@@ -126,7 +109,7 @@ function PreviewPanelShellFrame(
109 }, [collapsible, open, hostRef]);
110 return (
111 <div
129 - ref={hostRef}
112 + ref={attachHost}
113 className={cn(
114 "relative flex h-full min-h-0 min-w-0 max-w-full flex-col self-stretch bg-background",
115 isInline
apps/web/src/components/ui/sidebar.browser.test.tsx new
+74
@@ -0,0 +1,74 @@
1 +import { page, userEvent } from "vite-plus/test/browser";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3 +
4 +import { render } from "../../../test/render";
5 +import { Sidebar, SidebarProvider, SidebarRail, SidebarTrigger, useSidebar } from "./sidebar";
6 +
7 +function CollapseFromInside() {
8 + const { setOpen } = useSidebar();
9 + return (
10 + <button type="button" onClick={() => setOpen(false)}>
11 + Collapse
12 + </button>
13 + );
14 +}
15 +
16 +function Harness(props: { readonly onResize?: (width: number) => void }) {
17 + return (
18 + <SidebarProvider defaultOpen>
19 + <Sidebar
20 + collapsible="offcanvas"
21 + resizable={{
22 + minWidth: 200,
23 + maxWidth: 600,
24 + ...(props.onResize ? { onResize: props.onResize } : {}),
25 + }}
26 + >
27 + <CollapseFromInside />
28 + <SidebarRail />
29 + </Sidebar>
30 + <SidebarTrigger />
31 + </SidebarProvider>
32 + );
33 +}
34 +
35 +describe("Sidebar", () => {
36 + it("hands focus to the outside trigger when it collapses around the focused control", async () => {
37 + await page.viewport(1280, 800);
38 + await using screen = await render(<Harness />, { router: false /* no routes involved */ });
39 +
40 + await userEvent.click(screen.getByRole("button", { name: "Collapse" }));
41 +
42 + const sidebar = screen.container.querySelector<HTMLElement>('[data-slot="sidebar"]')!;
43 + await vi.waitFor(() => expect(sidebar.inert).toBe(true));
44 + const trigger = screen.container.querySelector('[data-slot="sidebar-trigger"]');
45 + await vi.waitFor(() => expect(document.activeElement).toBe(trigger));
46 + });
47 +
48 + it("abandons a rail drag when the sidebar collapses mid-drag", async () => {
49 + await page.viewport(1280, 800);
50 + const onResize = vi.fn();
51 + await using screen = await render(<Harness onResize={onResize} />, {
52 + router: false /* no routes involved */,
53 + });
54 + const rail = screen.container.querySelector<HTMLElement>('[data-sidebar="rail"]')!;
55 + const { left, top } = rail.getBoundingClientRect();
56 + const pointer = { bubbles: true, cancelable: true, pointerId: 1, button: 0, clientY: top + 10 };
57 + const dragTo = (clientX: number) => {
58 + rail.dispatchEvent(new PointerEvent("pointerdown", { ...pointer, clientX: left }));
59 + rail.dispatchEvent(new PointerEvent("pointermove", { ...pointer, clientX }));
60 + };
61 + // A completed drag commits, so the abandoned one below is a real drag too.
62 + dragTo(left + 40);
63 + rail.dispatchEvent(new PointerEvent("pointerup", { ...pointer, clientX: left + 40 }));
64 + expect(onResize).toHaveBeenCalledTimes(1);
65 +
66 + dragTo(left + 80);
67 + await userEvent.click(
68 + screen.container.querySelector<HTMLElement>('[data-slot="sidebar-trigger"]')!,
69 + );
70 + rail.dispatchEvent(new PointerEvent("pointerup", { ...pointer, clientX: left + 80 }));
71 +
72 + expect(onResize).toHaveBeenCalledTimes(1);
73 + });
74 +});
apps/web/src/components/ui/sidebar.tsx
+114 -91
@@ -17,8 +17,8 @@ import {
17 } from "~/components/ui/sheet";
18 import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
19 import { useResizeDrag } from "~/hooks/useResizeDrag";
20 -import { useIsMobile } from "~/hooks/useMediaQuery";
21 -import { getLocalStorageItem, setLocalStorageItem } from "~/hooks/useLocalStorage";
20 +import { useMediaQuery } from "~/hooks/useMediaQuery";
21 +import { setLocalStorageItem } from "~/hooks/useLocalStorage";
22 import { resolveSidebarState, type ResponsiveSidebarState } from "./sidebarState";
23 import * as Schema from "effect/Schema";
24
@@ -40,6 +40,8 @@ type SidebarContextProps = {
40 setOpenMobile: (open: boolean) => void;
41 isMobile: boolean;
42 toggleSidebar: () => void;
43 + /** Runs before the desktop sidebar collapses. */
44 + onCollapse: (listener: () => void) => () => void;
45 };
46
47 type SidebarResizableOptions = {
@@ -94,48 +96,101 @@ function useSidebarVisibility() {
96 return isMobile ? openMobile : open;
97 }
98
99 +// Same breakpoint as useIsMobile, also read when a shortcut fires.
100 +const SIDEBAR_MOBILE_QUERY = "(max-width: 767px)";
101 +
102 +function isMobileViewport(): boolean {
103 + return typeof window !== "undefined" && window.matchMedia(SIDEBAR_MOBILE_QUERY).matches;
104 +}
105 +
106 +async function persistSidebarOpen(open: boolean) {
107 + await cookieStore.set({
108 + expires: Date.now() + SIDEBAR_COOKIE_MAX_AGE * 1000,
109 + name: SIDEBAR_COOKIE_NAME,
110 + path: "/",
111 + value: String(open),
112 + });
113 +}
114 +
115 +// An offcanvas sidebar turns inert once collapsed, which drops focus to the body.
116 +function moveFocusOutOfCollapsingSidebar() {
117 + const sidebar = document.activeElement?.closest<HTMLElement>(
118 + '[data-slot="sidebar"][data-collapsible-mode="offcanvas"]',
119 + );
120 + const wrapper = sidebar?.closest<HTMLElement>('[data-slot="sidebar-wrapper"]');
121 + if (!sidebar || !wrapper) return;
122 + const trigger = Array.from(
123 + wrapper.querySelectorAll<HTMLElement>('[data-sidebar="trigger"]'),
124 + ).find((element) => !sidebar.contains(element));
125 + trigger?.focus({ preventScroll: true });
126 +}
127 +
128 +interface SidebarOpenState {
129 + readonly open: boolean;
130 + readonly openMobile: boolean;
131 +}
132 +
133 +/** Per-provider open state, kept outside React so shortcuts can toggle it at event time. */
134 +function createSidebarOpenStore(defaultOpen: boolean) {
135 + let state: SidebarOpenState = { open: defaultOpen, openMobile: false };
136 + const listeners = new Set<() => void>();
137 + const collapseListeners = new Set<() => void>();
138 + const publish = (next: SidebarOpenState) => {
139 + state = next;
140 + for (const listener of listeners) listener();
141 + };
142 + const setOpen = (open: boolean) => {
143 + if (!open && state.open) {
144 + for (const listener of collapseListeners) listener();
145 + moveFocusOutOfCollapsingSidebar();
146 + }
147 + if (open !== state.open) publish({ ...state, open });
148 + void persistSidebarOpen(open);
149 + };
150 + const setOpenMobile = (openMobile: boolean) => {
151 + if (openMobile !== state.openMobile) publish({ ...state, openMobile });
152 + };
153 + return {
154 + subscribe: (listener: () => void) => {
155 + listeners.add(listener);
156 + return () => {
157 + listeners.delete(listener);
158 + };
159 + },
160 + getSnapshot: () => state,
161 + setOpen,
162 + setOpenMobile,
163 + toggle: () => (isMobileViewport() ? setOpenMobile(!state.openMobile) : setOpen(!state.open)),
164 + onCollapse: (listener: () => void) => {
165 + collapseListeners.add(listener);
166 + return () => {
167 + collapseListeners.delete(listener);
168 + };
169 + },
170 + };
171 +}
172 +
173 function SidebarProvider({
174 defaultOpen = true,
99 - open: openProp,
100 - onOpenChange: setOpenProp,
175 className,
176 style,
177 children,
178 ...props
179 }: React.ComponentProps<"div"> & {
180 defaultOpen?: boolean;
107 - open?: boolean;
108 - onOpenChange?: (open: boolean) => void;
181 }) {
110 - const isMobile = useIsMobile();
111 - const [openMobile, setOpenMobile] = React.useState(false);
182 + const isMobile = useMediaQuery(SIDEBAR_MOBILE_QUERY);
183 + const [store] = React.useState(() => createSidebarOpenStore(defaultOpen));
184 + const { open, openMobile } = React.useSyncExternalStore(
185 + store.subscribe,
186 + store.getSnapshot,
187 + store.getSnapshot,
188 + );
189 const [mobileSheetMounted, setMobileSheetMounted] = React.useState(false);
190 const setMobileSheetElement = (element: HTMLDivElement | null) => {
191 setMobileSheetMounted(element !== null);
192 };
193
117 - const [_open, _setOpen] = React.useState(defaultOpen);
118 - const open = openProp ?? _open;
119 - const setOpen = async (value: boolean | ((value: boolean) => boolean)) => {
120 - const openState = typeof value === "function" ? value(open) : value;
121 - if (setOpenProp) {
122 - setOpenProp(openState);
123 - } else {
124 - _setOpen(openState);
125 - }
126 -
127 - await cookieStore.set({
128 - expires: Date.now() + SIDEBAR_COOKIE_MAX_AGE * 1000,
129 - name: SIDEBAR_COOKIE_NAME,
130 - path: "/",
131 - value: String(openState),
132 - });
133 - };
134 -
135 - const toggleSidebar = () => {
136 - return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
137 - };
138 -
194 const state = resolveSidebarState({ isMobile, open, openMobile });
195
196 const contextValue: SidebarContextProps = {
@@ -144,10 +199,11 @@ function SidebarProvider({
199 openMobile,
200 mobileSheetMounted,
201 setMobileSheetElement,
147 - setOpen,
148 - setOpenMobile,
202 + setOpen: store.setOpen,
203 + setOpenMobile: store.setOpenMobile,
204 state,
150 - toggleSidebar,
205 + toggleSidebar: store.toggle,
206 + onCollapse: store.onCollapse,
207 };
208
209 return (
@@ -215,24 +271,8 @@ function Sidebar({
271 resizable?: boolean | SidebarResizableOptions;
272 }) {
273 const { isMobile, state, openMobile, setOpenMobile, setMobileSheetElement } = useSidebar();
218 - const desktopSidebarRef = React.useRef<HTMLDivElement>(null);
274 const offcanvasCollapsed = !isMobile && collapsible === "offcanvas" && state === "collapsed";
275
221 - React.useLayoutEffect(() => {
222 - const sidebar = desktopSidebarRef.current;
223 - if (!sidebar) return;
224 -
225 - // Transfer focus before inert causes the browser to clear the focused descendant.
226 - if (offcanvasCollapsed && sidebar.contains(document.activeElement)) {
227 - const wrapper = sidebar.closest('[data-slot="sidebar-wrapper"]');
228 - const trigger = Array.from(
229 - wrapper?.querySelectorAll<HTMLElement>('[data-sidebar="trigger"]') ?? [],
230 - ).find((element) => !sidebar.contains(element));
231 - trigger?.focus({ preventScroll: true });
232 - }
233 - sidebar.toggleAttribute("inert", offcanvasCollapsed);
234 - }, [offcanvasCollapsed]);
235 -
276 const resolvedResizable = resolveSidebarResizable({ collapsible, isMobile, resizable });
277 const instanceContextValue: SidebarInstanceContextProps = { side, resizable: resolvedResizable };
278
@@ -297,9 +337,10 @@ function Sidebar({
337 return (
338 <SidebarInstanceContext value={instanceContextValue}>
339 <div
300 - ref={desktopSidebarRef}
340 className="group peer hidden text-sidebar-foreground md:block"
341 data-collapsible={state === "collapsed" ? collapsible : ""}
342 + data-collapsible-mode={collapsible}
343 + inert={offcanvasCollapsed}
344 data-side={side}
345 data-slot="sidebar"
346 data-state={state}
@@ -386,17 +427,16 @@ function SidebarRail({
427 onPointerUp,
428 ...props
429 }: React.ComponentProps<"button">) {
389 - const { open, toggleSidebar } = useSidebar();
430 + const { open, toggleSidebar, onCollapse } = useSidebar();
431 const sidebarInstance = React.use(SidebarInstanceContext);
391 - const railRef = React.useRef<HTMLButtonElement | null>(null);
432 const suppressClickRef = React.useRef(false);
433 const resolvedResizable = sidebarInstance?.resizable ?? null;
394 - const latestResizable = React.useRef(resolvedResizable);
434 const canResize = resolvedResizable !== null && open;
435 const railLabel = canResize ? "Resize Sidebar" : "Toggle Sidebar";
436 const railTitle = canResize ? "Drag to resize sidebar" : "Toggle Sidebar";
437 const resize = useResizeDrag<HTMLButtonElement>((event) => {
399 - if (!resolvedResizable || !open) return null;
438 + const options = resolvedResizable;
439 + if (!options || !open) return null;
440 const rail = event.currentTarget;
441 const wrapper = rail.closest<HTMLElement>("[data-slot='sidebar-wrapper']");
442 const sidebarRoot = rail.closest<HTMLElement>("[data-slot='sidebar']");
@@ -406,10 +446,7 @@ function SidebarRail({
446 if (!wrapper || !sidebarRoot || !sidebarContainer) return null;
447
448 const side = sidebarInstance?.side ?? "left";
409 - let width = clampSidebarWidth(
410 - sidebarContainer.getBoundingClientRect().width,
411 - resolvedResizable,
412 - );
449 + let width = clampSidebarWidth(sidebarContainer.getBoundingClientRect().width, options);
450 // Write width only to gap/container during drag; inherited --sidebar-width restyles the whole app, so
451 // update it at commit.
452 const widthTargets = [
@@ -429,10 +466,8 @@ function SidebarRail({
466 return {
467 width,
468 edge: side === "left" ? "right" : "left",
432 - resize(value) {
433 - const options = latestResizable.current;
434 - if (!options) return width;
435 - const nextWidth = clampSidebarWidth(value, options);
469 + bounds: { min: options.minWidth, max: options.maxWidth },
470 + resize(nextWidth) {
471 const accepted =
472 options.shouldAcceptWidth?.({
473 currentWidth: width,
@@ -451,15 +486,14 @@ function SidebarRail({
486 finish(finalWidth, moved) {
487 wrapper.style.setProperty("--sidebar-width", `${finalWidth}px`);
488 suppressClickRef.current = moved;
454 - const options = latestResizable.current;
455 - if (options?.storageKey) {
489 + if (options.storageKey) {
490 try {
491 setLocalStorageItem(options.storageKey, finalWidth, Schema.Finite);
492 } catch (error) {
493 console.error("Could not persist sidebar width.", error);
494 }
495 }
462 - options?.onResize?.(finalWidth);
496 + options.onResize?.(finalWidth);
497 },
498 cleanup() {
499 widthTargets.forEach((element) => {
@@ -468,12 +502,21 @@ function SidebarRail({
502 });
503 },
504 };
471 - }, String(open));
472 - const refreshResize = React.useEffectEvent(() => resize.refresh());
473 - React.useLayoutEffect(() => {
474 - latestResizable.current = resolvedResizable;
475 - refreshResize();
476 - }, [resolvedResizable]);
505 + });
506 + // Collapsing mid-drag abandons the drag instead of committing a width to a hidden sidebar.
507 + // Created once: a new ref callback would run the old one's cleanup, which ends a live drag.
508 + const [railRef] = React.useState(() => {
509 + const { ref: dragRef, cancel } = resize;
510 + return (node: HTMLButtonElement | null) => {
511 + const releaseDrag = dragRef(node);
512 + if (!releaseDrag) return undefined;
513 + const stopCancelOnCollapse = onCollapse(cancel);
514 + return () => {
515 + stopCancelOnCollapse();
516 + releaseDrag();
517 + };
518 + };
519 + });
520
521 const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
522 onClick?.(event);
@@ -490,26 +533,6 @@ function SidebarRail({
533 toggleSidebar();
534 };
535
493 - React.useLayoutEffect(() => {
494 - if (!resolvedResizable?.storageKey || typeof window === "undefined") return;
495 - const rail = railRef.current;
496 - if (!rail) return;
497 - const wrapper = rail.closest<HTMLElement>("[data-slot='sidebar-wrapper']");
498 - if (!wrapper) return;
499 -
500 - let storedWidth: number | null;
501 - try {
502 - storedWidth = getLocalStorageItem(resolvedResizable.storageKey, Schema.Finite);
503 - } catch (error) {
504 - console.error("Could not restore persisted sidebar width.", error);
505 - return;
506 - }
507 - if (storedWidth === null) return;
508 - const clampedWidth = clampSidebarWidth(storedWidth, resolvedResizable);
509 - wrapper.style.setProperty("--sidebar-width", `${clampedWidth}px`);
510 - resolvedResizable.onResize?.(clampedWidth);
511 - }, [resolvedResizable]);
512 -
536 return (
537 <Tooltip>
538 <TooltipTrigger
apps/web/src/hooks/usePreviewPanelInlineSize.ts
+17 -20
@@ -1,4 +1,4 @@
1 -import { type RefObject, useLayoutEffect, useState } from "react";
1 +import { useState } from "react";
2
3 import { type ResizableWidthHandlers, useResizableWidth } from "./useResizableWidth";
4 import { observeResize } from "../lib/observeResize";
@@ -6,6 +6,8 @@ import { observeResize } from "../lib/observeResize";
6 export interface PreviewPanelInlineSize {
7 readonly width: number;
8 readonly handlers: ResizableWidthHandlers;
9 + /** Ref-callback body for the panel host: measures the row the panel shares. */
10 + readonly observeRow: (host: HTMLElement) => () => void;
11 }
12
13 const PREVIEW_PANEL_WIDTH_STORAGE_KEY = "t3code:preview-panel-width";
@@ -16,7 +18,6 @@ const SIBLING_COLUMN_MIN_WIDTH = 360;
18 const PREVIEW_PANEL_DEFAULT_WIDTH = 540;
19
20 export function usePreviewPanelInlineSize(
19 - hostRef?: RefObject<HTMLElement | null>,
21 options: {
22 readonly enabled?: boolean | undefined;
23 readonly widthStorageKey?: string | undefined;
@@ -24,28 +25,23 @@ export function usePreviewPanelInlineSize(
25 readonly container?: HTMLElement | null | undefined;
26 } = {},
27 ): PreviewPanelInlineSize {
27 - const maxWidth = useViewportClampedMaxWidth(hostRef, options.enabled ?? true, options.container);
28 - return useResizableWidth({
28 + const enabled = options.enabled ?? true;
29 + const container = options.container;
30 + const [maxWidth, setMaxWidth] = useState(() =>
31 + getPreviewPanelMaxWidth(typeof window === "undefined" ? 1280 : window.innerWidth),
32 + );
33 + const { width, handlers } = useResizableWidth({
34 storageKey: options.widthStorageKey ?? PREVIEW_PANEL_WIDTH_STORAGE_KEY,
35 defaultWidth: options.defaultWidth ?? PREVIEW_PANEL_DEFAULT_WIDTH,
36 minWidth: PREVIEW_PANEL_MIN_WIDTH,
37 maxWidth,
38 edge: "left",
39 });
35 -}
36 -
37 -function useViewportClampedMaxWidth(
38 - hostRef: RefObject<HTMLElement | null> | undefined,
39 - enabled: boolean,
40 - container: HTMLElement | null | undefined,
41 -): number {
42 - const [maxWidth, setMaxWidth] = useState(() =>
43 - getPreviewPanelMaxWidth(typeof window === "undefined" ? 1280 : window.innerWidth),
44 - );
45 - useLayoutEffect(() => {
46 - if (typeof window === "undefined") return;
47 - const row = container ?? (enabled ? hostRef?.current?.parentElement : null) ?? null;
48 - // Clamp before paint to avoid flashing; store only the cap, which rarely changes during sidebar drags.
40 + const observeRow = (host: HTMLElement) => {
41 + const row = container ?? (enabled ? host.parentElement : null) ?? null;
42 + // Ref callbacks run before paint, so the width is clamped without an over-wide
43 + // flash on mount. Only the derived cap is stored: the row resizes every frame
44 + // of a sidebar drag, but an unchanged cap skips re-rendering the owner.
45 const measure = () => {
46 setMaxWidth(getPreviewPanelMaxWidth(window.innerWidth, row?.clientWidth));
47 };
@@ -65,9 +61,10 @@ function useViewportClampedMaxWidth(
61 if (frame !== 0) window.cancelAnimationFrame(frame);
62 stopObserving?.();
63 };
68 - }, [container, hostRef, enabled]);
69 - return maxWidth;
64 + };
65 + return { width, handlers, observeRow };
66 }
67 +
68 function getPreviewPanelMaxWidth(viewportWidth: number, containerWidth?: number): number {
69 const fractionCap = Math.floor(viewportWidth * PREVIEW_PANEL_MAX_WIDTH_FRACTION);
70 const containerCap =
apps/web/src/hooks/useResizableWidth.ts
+29 -18
@@ -1,5 +1,5 @@
1 import * as Schema from "effect/Schema";
2 -import { type PointerEvent as ReactPointerEvent, useLayoutEffect, useRef, useState } from "react";
2 +import { type PointerEvent as ReactPointerEvent, useLayoutEffect, useState } from "react";
3
4 import { getLocalStorageItem, setLocalStorageItem } from "./useLocalStorage";
5 import { useResizeDrag } from "./useResizeDrag";
@@ -18,6 +18,7 @@ export interface UseResizableWidthOptions {
18 }
19
20 export interface ResizableWidthHandlers {
21 + readonly ref: (node: HTMLElement | null) => (() => void) | undefined;
22 readonly onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;
23 readonly onPointerMove: (event: ReactPointerEvent<HTMLElement>) => void;
24 readonly onPointerUp: (event: ReactPointerEvent<HTMLElement>) => void;
@@ -53,42 +54,52 @@ export function useResizableWidth(options: UseResizableWidthOptions): {
54 }
55
56 const clampedWidth = clamp(widthState.width);
56 - const latestOptions = useRef({ clamp, storageKey, width: clampedWidth });
57 - useLayoutEffect(() => {
58 - latestOptions.current = { clamp, storageKey, width: clampedWidth };
59 - }, [clamp, clampedWidth, storageKey]);
57
61 - const { refresh, ...handlers } = useResizeDrag<HTMLElement>((event) => {
58 + const drag = useResizeDrag<HTMLElement>((event) => {
59 const host = event.currentTarget.parentElement;
60 // Disable drag transitions through transition-property; the host renders transition-duration.
61 host?.style.setProperty("transition-property", "none");
62 + // The drag commits to the key and width it started from, even if the panel
63 + // switches keys before the pointer is released.
64 + const startStorageKey = storageKey;
65 + const startWidth = clampedWidth;
66 return {
66 - width: clampedWidth,
67 + width: startWidth,
68 edge,
68 - resize(value) {
69 - const nextWidth = latestOptions.current.clamp(value);
69 + bounds: { min: minWidth, max: maxWidth },
70 + resize(nextWidth) {
71 host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${nextWidth}px`);
72 return nextWidth;
73 },
74 finish(finalWidth) {
74 - setWidthState({ storageKey, width: finalWidth });
75 + setWidthState({ storageKey: startStorageKey, width: finalWidth });
76 try {
76 - setLocalStorageItem(latestOptions.current.storageKey, finalWidth, WidthSchema);
77 + setLocalStorageItem(startStorageKey, finalWidth, WidthSchema);
78 } catch (error) {
79 console.error("Could not persist panel width.", error);
80 }
81 },
82 cleanup(committed) {
83 host?.style.removeProperty("transition-property");
83 - if (!committed) {
84 - host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${latestOptions.current.width}px`);
85 - }
84 + if (!committed) host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${startWidth}px`);
85 },
86 };
88 - }, storageKey);
87 + });
88
90 - // Mid-drag bound changes rewrite committed width; restore the live pointer position.
91 - useLayoutEffect(refresh, [clamp, clampedWidth, refresh]);
89 + // Bounds can change mid-drag (sidebar opens, window narrows), and the render
90 + // that carries them rewrites the committed width, so re-apply the live pointer position.
91 + const { refresh } = drag;
92 + useLayoutEffect(() => refresh({ min: minWidth, max: maxWidth }), [refresh, minWidth, maxWidth]);
93
93 - return { width: clampedWidth, handlers };
94 + return {
95 + width: clampedWidth,
96 + handlers: {
97 + ref: drag.ref,
98 + onPointerDown: drag.onPointerDown,
99 + onPointerMove: drag.onPointerMove,
100 + onPointerUp: drag.onPointerUp,
101 + onPointerCancel: drag.onPointerCancel,
102 + onLostPointerCapture: drag.onLostPointerCapture,
103 + },
104 + };
105 }
apps/web/src/hooks/useResizeDrag.ts
+65 -46
@@ -1,43 +1,57 @@
1 -import { type PointerEvent, useEffect, useEffectEvent, useLayoutEffect, useRef } from "react";
1 +import { type PointerEvent, useState } from "react";
2 +
3 +export interface ResizeBounds {
4 + readonly min: number;
5 + readonly max: number;
6 +}
7
8 interface ResizeSession {
9 width: number;
10 edge: "left" | "right";
11 + /** Pointer widths are clamped to these before `resize` sees them. */
12 + bounds: ResizeBounds;
13 resize: (width: number) => number;
14 finish: (width: number, moved: boolean) => void;
15 cleanup?: (committed: boolean) => void;
16 }
17
11 -export function useResizeDrag<T extends HTMLElement>(
12 - start: (event: PointerEvent<T>) => ResizeSession | null,
13 - resetKey?: string,
14 -) {
15 - const drag = useRef<{
16 - session: ResizeSession;
17 - target: T;
18 - pointerId: number;
19 - startX: number;
20 - pendingX: number;
21 - width: number;
22 - moved: boolean;
23 - frame: number | null;
24 - } | null>(null);
18 +function clampToBounds(width: number, bounds: ResizeBounds): number {
19 + return Math.max(bounds.min, Math.min(bounds.max, width));
20 +}
21 +
22 +interface ActiveDrag<T extends HTMLElement> {
23 + session: ResizeSession;
24 + target: T;
25 + pointerId: number;
26 + startX: number;
27 + pendingX: number;
28 + width: number;
29 + moved: boolean;
30 + frame: number | null;
31 + onBlur: () => void;
32 +}
33 +
34 +function createResizeDrag<T extends HTMLElement>() {
35 + let drag: ActiveDrag<T> | null = null;
36
37 const flush = () => {
27 - const active = drag.current;
38 + const active = drag;
39 if (!active) return;
40 const delta = (active.pendingX - active.startX) * (active.session.edge === "left" ? -1 : 1);
41 if (Math.abs(delta) > 2) active.moved = true;
31 - active.width = active.session.resize(active.session.width + delta);
42 + active.width = active.session.resize(
43 + clampToBounds(active.session.width + delta, active.session.bounds),
44 + );
45 };
46
34 - const finish = (commit = true) => {
35 - const active = drag.current;
47 + const finish = (commit: boolean) => {
48 + const active = drag;
49 if (!active) return;
50 if (active.frame !== null) cancelAnimationFrame(active.frame);
51 + window.removeEventListener("blur", active.onBlur);
52 if (commit) flush();
53 // Release can synchronously dispatch lostpointercapture.
40 - drag.current = null;
54 + drag = null;
55 try {
56 if (active.target.hasPointerCapture(active.pointerId)) {
57 active.target.releasePointerCapture(active.pointerId);
@@ -49,37 +63,24 @@ export function useResizeDrag<T extends HTMLElement>(
63 if (commit) active.session.finish(active.width, active.moved);
64 };
65
52 - const finishDrag = useEffectEvent((commit: boolean) => finish(commit));
53 -
54 - const previousResetKey = useRef(resetKey);
55 - useLayoutEffect(() => {
56 - if (previousResetKey.current !== resetKey) {
57 - finishDrag(false);
58 - previousResetKey.current = resetKey;
59 - }
60 - }, [resetKey]);
61 -
62 - useEffect(() => {
63 - const onBlur = () => finishDrag(true);
64 - window.addEventListener("blur", onBlur);
65 - return () => {
66 - window.removeEventListener("blur", onBlur);
67 - finishDrag(false);
68 - };
69 - }, []);
70 -
66 const end = (event: PointerEvent<T>, usePosition: boolean) => {
72 - const active = drag.current;
67 + const active = drag;
68 if (!active || active.pointerId !== event.pointerId) return;
69 event.preventDefault();
70 if (usePosition) active.pendingX = event.clientX;
76 - finish();
71 + finish(true);
72 };
73
74 return {
80 - refresh: flush,
81 - onPointerDown(event: PointerEvent<T>) {
82 - if (event.button !== 0 || drag.current) return;
75 + ref: (node: T | null) => (node === null ? undefined : () => finish(false)),
76 + cancel: () => finish(false),
77 + refresh(bounds?: ResizeBounds) {
78 + if (!drag) return;
79 + if (bounds) drag.session.bounds = bounds;
80 + flush();
81 + },
82 + begin(event: PointerEvent<T>, start: (event: PointerEvent<T>) => ResizeSession | null) {
83 + if (event.button !== 0 || drag) return;
84 const session = start(event);
85 if (!session) return;
86 try {
@@ -90,7 +91,10 @@ export function useResizeDrag<T extends HTMLElement>(
91 }
92 event.preventDefault();
93 event.stopPropagation();
93 - drag.current = {
94 + // Leaving the window mid-drag commits where the pointer was.
95 + const onBlur = () => finish(true);
96 + window.addEventListener("blur", onBlur);
97 + drag = {
98 session,
99 target: event.currentTarget,
100 pointerId: event.pointerId,
@@ -99,12 +103,13 @@ export function useResizeDrag<T extends HTMLElement>(
103 width: session.width,
104 moved: false,
105 frame: null,
106 + onBlur,
107 };
108 document.body.style.cursor = "col-resize";
109 document.body.style.userSelect = "none";
110 },
111 onPointerMove(event: PointerEvent<T>) {
107 - const active = drag.current;
112 + const active = drag;
113 if (!active || active.pointerId !== event.pointerId) return;
114 event.preventDefault();
115 active.pendingX = event.clientX;
@@ -120,3 +125,17 @@ export function useResizeDrag<T extends HTMLElement>(
125 onLostPointerCapture: (event: PointerEvent<T>) => end(event, false),
126 };
127 }
128 +
129 +/**
130 + * A pointer drag that resizes along one edge. The session `start` returns owns
131 + * everything the drag needs, so options read at pointer-down hold for the whole
132 + * drag. Attach `ref` to the handle so unmounting it abandons the drag.
133 + */
134 +export function useResizeDrag<T extends HTMLElement>(
135 + start: (event: PointerEvent<T>) => ResizeSession | null,
136 +) {
137 + // Created once: `ref` must keep its identity, or a re-render mid-drag would run its cleanup.
138 + const [drag] = useState(createResizeDrag<T>);
139 + const { begin, ...rest } = drag;
140 + return { ...rest, onPointerDown: (event: PointerEvent<T>) => begin(event, start) };
141 +}
apps/web/src/previewStateStore.ts
+4
@@ -171,6 +171,10 @@ export function useActivePreviewSessions(): Record<string, ThreadPreviewState> {
171 return useAtomValue(activePreviewSessionsAtom);
172 }
173
174 +export function readActivePreviewSessions(): Record<string, ThreadPreviewState> {
175 + return appAtomRegistry.get(activePreviewSessionsAtom);
176 +}
177 +
178 export function readThreadPreviewState(ref: ScopedThreadRef): ThreadPreviewState {
179 return appAtomRegistry.get(previewStateAtom(scopedThreadKey(ref)));
180 }