TypeScript
fix(web): find bar and thread details panel stop covering each other (#17858)
Matthew Ferozf92afe79c921
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex d2ec0af4ed2..e442fae36aa 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -7998,11 +7998,6 @@ export default function ChatView(props: ChatViewProps) {const [isThreadFindActive, setIsThreadFindActive] = useState(false);const openThreadFind = useCallback(() => threadFindControlsRef.current?.open(), []);const closeThreadFind = useCallback(() => threadFindControlsRef.current?.close(), []);- // The details popover hangs off the header over the find bar; opening find dismisses it.- useEffect(() => {- if (!isThreadFindActive || threadPanelPresentation !== "popover" || !activeThreadRef) return;- useRightPanelStore.getState().setThreadPanelOpen(activeThreadRef, "popover", false);- }, [activeThreadRef, isThreadFindActive, threadPanelPresentation]);useEffect(() => {const handler = (event: globalThis.KeyboardEvent) => {diff --git a/apps/web/src/components/chat/ChatCanvas.test.tsx b/apps/web/src/components/chat/ChatCanvas.test.tsxnew file mode 100644index 00000000000..5ab43b81cb2--- /dev/null+++ b/apps/web/src/components/chat/ChatCanvas.test.tsx@@ -0,0 +1,119 @@+// @vitest-environment jsdom++import { act, useLayoutEffect } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";+import { ChatCanvas } from "./ChatCanvas";+import { useChatCanvas } from "./ChatCanvasContext";++const resize = vi.hoisted(() => ({ callbacks: new Set<() => void>() }));+vi.mock("../../lib/observeResize", () => ({+ observeResize: (_elements: unknown, callback: () => void) => {+ resize.callbacks.add(callback);+ return () => resize.callbacks.delete(callback);+ },+}));++let root: Root;+let container: HTMLDivElement;+let fontSize = 16;+let canvas: ReturnType<typeof useChatCanvas>;++function Preview({ x }: { x: number }) {+ const current = useChatCanvas();+ useLayoutEffect(() => {+ canvas = current;+ }, [current]);+ const reportPreview = current?.reportPreview;+ useLayoutEffect(() => {+ reportPreview?.({+ key: "browser:one",+ width: 240,+ source: { width: 240, height: 365 },+ position: { x, y: 12 },+ lastInteraction: "drag",+ });+ }, [reportPreview, x]);+ return null;+}++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ fontSize = 16;+ vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(1800);+ vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(1000);+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (+ this: HTMLElement,+ ) {+ // A nonzero canvas origin catches viewport coordinates used as canvas coordinates.+ if (this.hasAttribute("data-thread-find-bar")) {+ const gap = 0.75 * fontSize;+ return new DOMRect(+ 200 + 1800 - gap - 17.5 * fontSize,+ 100 + gap,+ 17.5 * fontSize,+ 2.25 * fontSize,+ );+ }+ return new DOMRect(200, 100, 1800, 1000);+ });+ vi.spyOn(window, "getComputedStyle").mockReturnValue({+ paddingLeft: "48px",+ width: "736px",+ minWidth: "640px",+ } as CSSStyleDeclaration);+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(() => root.unmount());+ container.remove();+ resize.callbacks.clear();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++async function renderFind(open: boolean, previewX = 1548) {+ await act(() =>+ root.render(+ <ChatCanvas composerOverlayElement={null} detailsCardTopInset={open ? 48 : 0}>+ {open ? <div data-thread-find-bar /> : null}+ <Preview x={previewX} />+ </ChatCanvas>,+ ),+ );+}++it.each([16, 24])(+ "keeps a preview below Find and releases its space on close at a %spx root font",+ async (size) => {+ fontSize = size;+ await renderFind(false);+ expect(canvas?.layout.frame?.y).toBe(12);++ await renderFind(true);+ expect(canvas?.detailsCardTopInset).toBe(3 * size);+ expect(canvas?.layout.frame?.y).toBe(3 * size + 12);++ await renderFind(false);+ expect(canvas?.detailsCardTopInset).toBe(0);+ expect(canvas?.layout.frame?.y).toBe(12);++ await renderFind(true);+ expect(canvas?.layout.frame?.y).toBe(3 * size + 12);+ },+);++it("remeasures the open bar when its font size changes without resizing the canvas", async () => {+ await renderFind(true, 1200);+ expect(canvas?.layout.frame?.y).toBe(12);++ fontSize = 24;+ await act(() => {+ for (const callback of resize.callbacks) callback();+ });+ expect(canvas?.detailsCardTopInset).toBe(72);+ expect(canvas?.layout.frame?.y).toBe(84);+});diff --git a/apps/web/src/components/chat/ChatCanvas.tsx b/apps/web/src/components/chat/ChatCanvas.tsxindex 35f96656585..809443c8f68 100644--- a/apps/web/src/components/chat/ChatCanvas.tsx+++ b/apps/web/src/components/chat/ChatCanvas.tsx@@ -47,6 +47,9 @@ export function ChatCanvas({minChatWidth: 640,composerHeight: 0,timelineGutter: 0,+ findBarLeft: 0,+ findBarRight: 0,+ findBarBottom: 0,});const reportPreview = useCallback((next: ChatCanvasPreview) => {setPreview((current) =>@@ -69,9 +72,16 @@ export function ChatCanvas({const element = elementRef.current;const probe = widthProbeRef.current;if (!element || !probe) return;+ const findBar =+ detailsCardTopInset > 0 ? element.querySelector<HTMLElement>("[data-thread-find-bar]") : null;const measure = () => {+ const canvasBounds = element.getBoundingClientRect();+ const findBarBounds = findBar?.getBoundingClientRect();const styles = getComputedStyle(probe);const next = {+ findBarLeft: findBarBounds ? findBarBounds.left - canvasBounds.left : 0,+ findBarRight: findBarBounds ? findBarBounds.right - canvasBounds.left : 0,+ findBarBottom: findBarBounds ? findBarBounds.bottom - canvasBounds.top : 0,width: element.clientWidth,height: element.clientHeight,padding: Number.parseFloat(styles.paddingLeft),@@ -92,22 +102,37 @@ export function ChatCanvas({};measure();const observed: Element[] = [element, probe];+ if (findBar) observed.push(findBar);if (composerOverlayElement) observed.push(composerOverlayElement);if (timelineElement) observed.push(timelineElement);return observeResize(observed, measure);- }, [composerOverlayElement, timelineElement]);+ }, [composerOverlayElement, timelineElement, detailsCardTopInset]);const context = useMemo(() => {const container = { width: measurements.width, height: measurements.height };+ const findBar =+ detailsCardTopInset > 0+ ? {+ left: measurements.findBarLeft,+ right: measurements.findBarRight,+ bottom: measurements.findBarBottom,+ }+ : null;return {container,lane: { padding: measurements.padding, minChatWidth: measurements.minChatWidth },- layout: resolveChatCanvasLayout({ ...measurements, container, preview, detailsCard }),+ layout: resolveChatCanvasLayout({+ ...measurements,+ container,+ preview,+ detailsCard,+ findBar,+ }),previewKey: preview?.key ?? null,reportPreview,clearPreview,registerTimeline,reportDetailsCard,- detailsCardTopInset,+ detailsCardTopInset: findBar?.bottom ?? 0,};}, [measurements,diff --git a/apps/web/src/components/chat/ThreadDetailsCard.tsx b/apps/web/src/components/chat/ThreadDetailsCard.tsxindex 4aa4ce400b8..0b0ebb8398b 100644--- a/apps/web/src/components/chat/ThreadDetailsCard.tsx+++ b/apps/web/src/components/chat/ThreadDetailsCard.tsx@@ -7,6 +7,7 @@ import { selectThreadPanelOpen, useRightPanelStore } from "../../rightPanelStoreimport type { ThreadPanelPresentation } from "../../rightPanelLayout";import { useChatCanvas } from "./ChatCanvasContext";import {+ THREAD_DETAILS_CARD_GAP,resolveThreadDetailsCardDensity,resolveThreadDetailsCardLayout,} from "./threadDetailsCardLayout";@@ -45,6 +46,7 @@ export function ThreadDetailsCard({}): null;const mode = placement ? "inline" : "popover";+ const topInset = canvas?.detailsCardTopInset ?? 0;const inlineOpen = useRightPanelStore((state) =>selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "inline"),);@@ -137,17 +139,38 @@ export function ThreadDetailsCard({<Popoverhandle={handle}open={mode === "popover" && popoverOpen}- onOpenChange={(open) =>- useRightPanelStore.getState().setThreadPanelOpen(threadRef, "popover", open)- }+ onOpenChange={(open, details) => {+ // The find bar sits beside the card, so clicking or focusing it does not+ // dismiss the card. Escape still does.+ const target =+ details.reason === "focus-out"+ ? (details.event as FocusEvent).relatedTarget+ : details.reason === "outside-press"+ ? details.event.target+ : null;+ if (!open && target instanceof Element && target.closest("[data-thread-find-bar]")) {+ details.cancel();+ return;+ }+ useRightPanelStore.getState().setThreadPanelOpen(threadRef, "popover", open);+ }}>{placement ? (inlineOpen ? (<asidearia-label="Thread details"- className="absolute z-20"+ // Slides down to make room for the find bar, but returns in the same frame+ // the bar closes: a floating preview below moves up at once and would+ // otherwise overlap the card mid-slide.+ className={cn(+ "absolute z-20",+ topInset > 0 &&+ "transition-[top] duration-150 ease-out motion-reduce:transition-none",+ )}style={{- left: placement.x,+ // Anchored to the right edge like the find bar, so both follow a resizing+ // canvas in the same frame instead of waiting for its next measurement.+ right: placement.right,top: placement.y,width: placement.width,maxHeight: height,@@ -162,10 +185,11 @@ export function ThreadDetailsCard({<PopoverPopupanchor={anchor}align="end"- alignOffset={0}+ // Lines the card up with the find bar: the panel pads its card by 8px.+ alignOffset={THREAD_DETAILS_CARD_GAP - 8}collisionAvoidance={{ side: "shift", align: "shift", fallbackAxisSide: "none" }}side="bottom"- sideOffset={0}+ sideOffset={topInset}variant="panel"padding="none">diff --git a/apps/web/src/components/chat/ThreadFindBar.tsx b/apps/web/src/components/chat/ThreadFindBar.tsxindex 21e3eeee2d6..b4284be34c0 100644--- a/apps/web/src/components/chat/ThreadFindBar.tsx+++ b/apps/web/src/components/chat/ThreadFindBar.tsx@@ -59,65 +59,71 @@ export function ThreadFindBar(props: ThreadFindBarProps) {};return (- <InputGroup- variant="popover"- size="lg"- onContextMenu={(event) => event.stopPropagation()}- role="search"- aria-label="Find in thread"- aria-busy={props.status === "loading" || props.counting === true}- className="absolute top-3 right-3 z-40 w-[min(24rem,calc(100%-1.5rem))]"+ // Fades in while the details popover slides out from under it.+ <div+ data-thread-find-bar+ className="absolute top-3 right-3 z-40 w-[min(var(--thread-details-panel-width),calc(100%-1.5rem))] transition-opacity duration-150 ease-out starting:opacity-0 motion-reduce:transition-none">- <InputGroupInput- ref={inputRef}- type="search"- size="sm"- value={props.query}+ <InputGroup+ variant="popover"+ size="lg"+ onContextMenu={(event) => event.stopPropagation()}+ role="search"aria-label="Find in thread"- placeholder="Find in thread"- maxLength={200}- spellCheck={false}- autoComplete="off"- onChange={(event) => props.onQueryChange(event.target.value)}- onKeyDown={handleKeyDown}- />- <InputGroupAddon align="inline-end" inset="pill">- <span- aria-live="polite"- className={cn(- "min-w-10 text-center text-xs tabular-nums",- noResults ? "text-destructive" : "text-muted-foreground",- )}- >- {label}- </span>- {props.status === "error" ? (- <Button size="xs" variant="ghost" onClick={props.onRetry}>- Retry+ aria-busy={props.status === "loading" || props.counting === true}+ className="w-full"+ >+ <InputGroupInput+ ref={inputRef}+ type="search"+ size="sm"+ value={props.query}+ aria-label="Find in thread"+ placeholder="Find in thread"+ maxLength={200}+ spellCheck={false}+ autoComplete="off"+ onChange={(event) => props.onQueryChange(event.target.value)}+ onKeyDown={handleKeyDown}+ />+ <InputGroupAddon align="inline-end" inset="pill">+ <span+ aria-live="polite"+ className={cn(+ "min-w-10 text-center text-xs tabular-nums",+ noResults ? "text-destructive" : "text-muted-foreground",+ )}+ >+ {label}+ </span>+ {props.status === "error" ? (+ <Button size="xs" variant="ghost" onClick={props.onRetry}>+ Retry+ </Button>+ ) : null}+ <Button+ size="icon-xs"+ variant="ghost"+ aria-label="Previous match"+ disabled={navigationDisabled}+ onClick={props.onPrevious}+ >+ <ChevronUpIcon /></Button>- ) : null}- <Button- size="icon-xs"- variant="ghost"- aria-label="Previous match"- disabled={navigationDisabled}- onClick={props.onPrevious}- >- <ChevronUpIcon />- </Button>- <Button- size="icon-xs"- variant="ghost"- aria-label="Next match"- disabled={navigationDisabled}- onClick={props.onNext}- >- <ChevronDownIcon />- </Button>- <Button size="icon-xs" variant="ghost" aria-label="Close find" onClick={props.onClose}>- <XIcon />- </Button>- </InputGroupAddon>- </InputGroup>+ <Button+ size="icon-xs"+ variant="ghost"+ aria-label="Next match"+ disabled={navigationDisabled}+ onClick={props.onNext}+ >+ <ChevronDownIcon />+ </Button>+ <Button size="icon-xs" variant="ghost" aria-label="Close find" onClick={props.onClose}>+ <XIcon />+ </Button>+ </InputGroupAddon>+ </InputGroup>+ </div>);}diff --git a/apps/web/src/components/chat/ThreadFindProvider.tsx b/apps/web/src/components/chat/ThreadFindProvider.tsxindex f35fcea8f92..4573f041b70 100644--- a/apps/web/src/components/chat/ThreadFindProvider.tsx+++ b/apps/web/src/components/chat/ThreadFindProvider.tsx@@ -1,8 +1,8 @@import {createContext,use,- useEffect,useImperativeHandle,+ useLayoutEffect,type ReactNode,type ComponentProps,type Ref,@@ -49,7 +49,8 @@ export function ThreadFindProvider({find.open,find.close,]);- useEffect(() => onOpenChange(find.isOpen), [find.isOpen, onOpenChange]);+ // Before paint, so the details card makes room in the same frame the bar appears.+ useLayoutEffect(() => onOpenChange(find.isOpen), [find.isOpen, onOpenChange]);return (<ThreadFindBarContext value={find.barProps}><ThreadFindTimelineContext value={find.timelineProps}>{children}</ThreadFindTimelineContext>diff --git a/apps/web/src/components/chat/chatCanvasLayout.test.ts b/apps/web/src/components/chat/chatCanvasLayout.test.tsindex 2d6f77af1b4..936f2193a7b 100644--- a/apps/web/src/components/chat/chatCanvasLayout.test.ts+++ b/apps/web/src/components/chat/chatCanvasLayout.test.ts@@ -135,6 +135,46 @@ describe("chat canvas layout", () => {expect(result.overlapsDetailsCard).toBe(false);expect(result.chat).toEqual({ left: 424, width: 736, insetStart: 0, insetEnd: 0 });});+ it("keeps a dragged or resized preview below the open find bar", () => {+ const findBar = { left: 1292, right: 1572, bottom: 48 };+ const layout = (lastInteraction: "drag" | "resize") =>+ resolveChatCanvasLayout({+ container: { width: 1584, height: 988 },+ maxChatWidth: 736,+ composerHeight: 180,+ findBar,+ preview: {+ ...preview,+ width: 240,+ source: { width: 240, height: 365 },+ position: { x: 1332, y: 12 },+ lastInteraction,+ },+ });+ for (const lastInteraction of ["drag", "resize"] as const) {+ const result = layout(lastInteraction);+ expect(result.frame).toEqual({ x: 1332, y: 60, width: 240, height: 365 });+ expect(result.overlapsDetailsCard).toBe(false);+ expect(result.chat).toEqual({ left: 424, width: 736, insetStart: 0, insetEnd: 0 });+ }+ });+ it("keeps a preview clear of a find bar wider than the inline details card", () => {+ const result = resolveChatCanvasLayout({+ container: { width: 1800, height: 1000 },+ findBar: { left: 1362, right: 1782, bottom: 72 },+ detailsCard: { left: 1508, right: 1788, bottom: 400 },+ preview: {+ ...preview,+ width: 240,+ source: { width: 240, height: 365 },+ position: { x: 1200, y: 12 },+ lastInteraction: "drag",+ },+ });+ const frame = result.frame!;+ expect(frame.x + frame.width <= 1362 || frame.y >= 84).toBe(true);+ expect(result.overlapsDetailsCard).toBe(false);+ });it("uses space beside the full card if a tall preview cannot fit below it", () => {const result = resolveChatCanvasLayout({container: { width: 1584, height: 988 },diff --git a/apps/web/src/components/chat/chatCanvasLayout.ts b/apps/web/src/components/chat/chatCanvasLayout.tsindex 01c5d527ccb..c13af0765da 100644--- a/apps/web/src/components/chat/chatCanvasLayout.ts+++ b/apps/web/src/components/chat/chatCanvasLayout.ts@@ -32,6 +32,7 @@ export function resolveChatCanvasLayout({minChatWidth = 640,composerHeight = 0,detailsCard = null,+ findBar = null,}: {container: PreviewMiniPlayerSize;preview: ChatCanvasPreview | null;@@ -40,6 +41,8 @@ export function resolveChatCanvasLayout({minChatWidth?: number;composerHeight?: number;detailsCard?: PreviewMiniPlayerObstacles["detailsCard"];+ /** The open find bar. It only keeps the floating preview clear; chat stays put. */+ findBar?: PreviewMiniPlayerObstacles["detailsCard"];}) {const centeredWidth = Math.max(0, Math.min(maxChatWidth, container.width - padding * 2));// A workspace card that does not fit beside the centered chat first moves@@ -90,13 +93,23 @@ export function resolveChatCanvasLayout({});}}+ const findBarObstacles = findBar ? { detailsCard: findBar, composer: null } : undefined;const preferredFrame = {...frame,- ...clampPreviewMiniPlayerPosition(frame, container, frame, undefined, minimumPreviewX),+ ...clampPreviewMiniPlayerPosition(frame, container, frame, findBarObstacles, minimumPreviewX),};// A resize keeps its anchored edge and consumes card height first. A drag// clears the full card whenever it can, so moving alone never folds it.- const cardObstacle = preview.lastInteraction === "resize" ? null : detailsCard;+ // The find bar can be wider than the inline card when the root font is enlarged.+ const dragObstacle =+ detailsCard && findBar+ ? {+ left: Math.min(detailsCard.left, findBar.left),+ right: Math.max(detailsCard.right, findBar.right),+ bottom: Math.max(detailsCard.bottom, findBar.bottom),+ }+ : (detailsCard ?? findBar);+ const cardObstacle = preview.lastInteraction === "resize" ? findBar : dragObstacle;frame = {...frame,...clampPreviewMiniPlayerPosition(@@ -166,7 +179,7 @@ export function resolveChatCanvasLayout({frame,container,frame,- { composer: obstacles.composer, detailsCard: null },+ { composer: obstacles.composer, detailsCard: findBar },minimumPreviewX,),};diff --git a/apps/web/src/components/chat/threadDetailsCardLayout.test.ts b/apps/web/src/components/chat/threadDetailsCardLayout.test.tsindex 923dbc4e521..0814e13a9bb 100644--- a/apps/web/src/components/chat/threadDetailsCardLayout.test.ts+++ b/apps/web/src/components/chat/threadDetailsCardLayout.test.ts@@ -16,6 +16,7 @@ describe("workspace card", () => {it("pins to the top right at a fixed width", () => {expect(resolve(1600, 900)).toEqual({x: 1308,+ right: 12,y: 12,width: 280,height: 876,@@ -30,7 +31,7 @@ describe("workspace card", () => {frame: null,topInset: 48,}),- ).toEqual({ x: 1308, y: 60, width: 280, height: 828 });+ ).toEqual({ x: 1308, right: 12, y: 60, width: 280, height: 828 });});it("hides when a readable chat lane cannot fit beside it", () => {expect(resolve(1012, 900)).toMatchObject({ x: 720 });@@ -38,7 +39,7 @@ describe("workspace card", () => {});it("keeps the card at the top right while the preview is freely dragged vertically", () => {for (const y of [12, 170, 250, 400, 648]) {- expect(resolve(1600, 900, y)).toEqual({ x: 1308, y: 12, width: 280, height: 876 });+ expect(resolve(1600, 900, y)).toEqual({ x: 1308, right: 12, y: 12, width: 280, height: 876 });}});it("keeps full height while a preview stays clear of the card", () => {diff --git a/apps/web/src/components/chat/threadDetailsCardLayout.ts b/apps/web/src/components/chat/threadDetailsCardLayout.tsindex 8353a3883ba..3a95787a84b 100644--- a/apps/web/src/components/chat/threadDetailsCardLayout.ts+++ b/apps/web/src/components/chat/threadDetailsCardLayout.ts@@ -3,6 +3,8 @@ import { DETAILS_CARD_CLEARANCE } from "./chatCanvasLayout";/** Inset of the card from the canvas edges; the find bar shares it to line up. */export const THREAD_DETAILS_CARD_GAP = 12;+// Keep in sync with --thread-details-panel-width, which sizes the popover and the find bar.+const THREAD_DETAILS_CARD_WIDTH = 280;export function resolveThreadDetailsCardDensity(height: number,@@ -32,8 +34,7 @@ export function resolveThreadDetailsCardLayout({topInset?: number;}) {const gap = THREAD_DETAILS_CARD_GAP;- // Keep in sync with --thread-details-panel-width, which sizes the popover.- const width = 280;+ const width = THREAD_DETAILS_CARD_WIDTH;const x = container.width - width - gap;if (x - DETAILS_CARD_CLEARANCE - lane.padding < lane.minChatWidth) return null;const y = gap + topInset;@@ -46,6 +47,7 @@ export function resolveThreadDetailsCardLayout({if (height < 160) return null;return {x,+ right: gap,width,y,height,diff --git a/apps/web/src/components/ui/popover.tsx b/apps/web/src/components/ui/popover.tsxindex 87995d512ad..4690cc2380c 100644--- a/apps/web/src/components/ui/popover.tsx+++ b/apps/web/src/components/ui/popover.tsx@@ -72,10 +72,15 @@ function PopoverPopup({alignOffset={alignOffset}anchor={anchor}collisionAvoidance={collisionAvoidance}+ // A panel's card already sits inside its own padding, so the panel can reach the edge.+ collisionPadding={variant === "panel" ? 0 : undefined}className={cn("h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-transform data-instant:transition-none",variant === "panel"- ? "z-(--z-sheet) w-[min(var(--thread-details-panel-width),var(--anchor-width))] transition-none"+ ? // The card inside is the panel width, or the anchor less 12px per side; the viewport+ // pads it by --spacing(2) per side. Panels slide when their offset changes, e.g. to make+ // room for a bar below the header, even when opened from the keyboard (data-instant).+ "z-(--z-sheet) w-[min(calc(var(--thread-details-panel-width)+--spacing(4)),calc(var(--anchor-width)---spacing(2)))] transition-[top] duration-150 ease-out data-instant:transition-[top] motion-reduce:transition-none motion-reduce:data-instant:transition-none": "z-[130]",)}data-slot="popover-positioner"