From 6be6a4b82806925fc0cc17e75841fb7724fe099f Mon Sep 17 00:00:00 2001 From: Gil Birman Date: Tue, 24 Nov 2026 14:25:33 -0600 Subject: [PATCH 1/5] feat(conversation): render a page's aside beside the workspace reader A workspace page can pass `aside`, with `asideWidth`, `asideOpen` and `onAsideOpenChange`. The host docks it in a column of that width beside the reader, or floats it over the history's end edge when the reader would get too narrow. Rows under the overlay are not read. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Gil Birman --- docs/plugin-authoring-guide.md | 12 + src/bundled/channels/Channels.module.css | 37 +++ src/bundled/channels/PageTabs.test.tsx | 31 ++ src/bundled/channels/PageTabs.tsx | 98 +++--- src/bundled/channels/WorkspaceRow.test.tsx | 165 ++++++++++ src/bundled/channels/WorkspaceRow.tsx | 187 +++++++++++ src/bundled/channels/index.test.tsx | 2 +- src/bundled/channels/index.tsx | 2 +- src/features/conversation/contracts.ts | 19 ++ src/features/messages/use-reading.test.ts | 22 +- src/features/messages/use-reading.ts | 30 +- src/plugins/author.ts | 1 + tests/browser/aside-fixture.tsx | 42 +++ tests/browser/plugin-fixtures.tsx | 36 ++- tests/browser/workspace-aside.spec.mjs | 353 +++++++++++++++++++++ 15 files changed, 983 insertions(+), 54 deletions(-) create mode 100644 src/bundled/channels/WorkspaceRow.test.tsx create mode 100644 src/bundled/channels/WorkspaceRow.tsx create mode 100644 tests/browser/aside-fixture.tsx create mode 100644 tests/browser/workspace-aside.spec.mjs diff --git a/docs/plugin-authoring-guide.md b/docs/plugin-authoring-guide.md index 491dcff54c..d908e7dc88 100644 --- a/docs/plugin-authoring-guide.md +++ b/docs/plugin-authoring-guide.md @@ -112,6 +112,18 @@ holds. Keep its controls in view with `position: sticky; bottom: 0` and an opaque background, and draw its outline with a box shadow rather than a bottom border. +Check `ctx.conversation.workspaceSlots?.aside === true` before passing `aside` +to `ui.Workspace`. The host places it: a column of `asideWidth` (default 320) +beside the reader, which narrows to leave it room, or, when the reader would +get too narrow, an overlay over the history's end edge. Fill the box and scroll +your content inside it; use `ui` popovers so they can escape over the history. +Drive it from your own header control with `asideOpen` and +`onAsideOpenChange`: docked, it shows by default; floating, it shows only once +opened. The host closes it as it floats, restores the docked state when the +reader widens, and closes the overlay on Escape or a press elsewhere in the +reader, reporting each change. Without that control a floating aside stays +closed. Messages under the overlay are not marked read. + For `ctx.agents.ui.Transcript`, give each turn a unique `turnId` that stays the same across reads. Return a new turn when it changes. Leave previously returned turns and their items untouched. ## Migration writes diff --git a/src/bundled/channels/Channels.module.css b/src/bundled/channels/Channels.module.css index 12a1dc21e9..33ea8fdcac 100644 --- a/src/bundled/channels/Channels.module.css +++ b/src/bundled/channels/Channels.module.css @@ -51,11 +51,48 @@ .soloConversation { container: solo-conversation / inline-size; } +/* A workspace's main reader and the page's aside (WorkspaceRow). Isolated, a + floating aside stacks over the reader, never over a narrow dock. */ +.workspaceRow { + position: relative; + isolation: isolate; + display: flex; + height: 100%; + min-width: 0; + min-height: 0; + overflow: hidden; +} .workspaceReader { flex: 1; min-height: 0; min-width: 0; } +/* The aside's box, which its content fills and scrolls itself. */ +.workspaceAside, +.floatingAside { + display: grid; + grid-template-rows: minmax(0, 1fr); + min-height: 0; +} +.workspaceAside { + flex: none; + border-inline-start: 1px solid var(--border-standard); +} +/* Over the history's end edge, beside its scrollbar, never over the composer. */ +.floatingAside { + @apply floating-surface; + position: absolute; + z-index: 1; + inset-block-start: calc(var(--aside-top, 0px) + var(--space-2)); + inset-inline-end: calc(var(--aside-scrollbar, 0px) + var(--space-2)); + block-size: calc(var(--aside-height, 100%) - 2 * var(--space-2)); + max-inline-size: calc(100% - 2 * var(--space-2)); + overflow: hidden; +} +.workspaceAside[hidden], +.floatingAside[hidden] { + display: none; +} .conversation :is( [data-tab-pane-toggle], diff --git a/src/bundled/channels/PageTabs.test.tsx b/src/bundled/channels/PageTabs.test.tsx index bb4df20df2..abe991a95e 100644 --- a/src/bundled/channels/PageTabs.test.tsx +++ b/src/bundled/channels/PageTabs.test.tsx @@ -512,6 +512,37 @@ it("a workspace gives its trailing content to its main reader", () => { expect(screen.getByText("Decision card")).toBeVisible(); }); +it.each([ + ["channel", { channelId: "alpha" }, "conversation in alpha"], + ["thread", { channelId: "alpha", threadId: "root" }, "thread in alpha"], +] as const)( + "a workspace docks its aside beside a %s reader", + (_, target, label) => { + const f = fixture(); + cleanup(); + vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue( + new DOMRect(0, 0, 1200, 600), + ); + render( + } + asideWidth={280} + />, + ); + const reader = screen.getByText(label, { exact: false }); + const aside = screen.getByRole("complementary", { name: "Task dashboard" }); + expect(reader.parentElement?.nextElementSibling).toBe(aside.parentElement); + expect(aside.parentElement).toHaveStyle({ inlineSize: "280px" }); + expect(screen.getByRole("tabpanel")).toContainElement(aside); + }, +); + it.each([false, true])( "a workspace shows its header actions before the actions menu (menu=%s)", (menu) => { diff --git a/src/bundled/channels/PageTabs.tsx b/src/bundled/channels/PageTabs.tsx index b460d7520f..0c6e267e32 100644 --- a/src/bundled/channels/PageTabs.tsx +++ b/src/bundled/channels/PageTabs.tsx @@ -50,6 +50,7 @@ import { panelOpening } from "../../features/panels/service"; import { coveringDock, useCoveredByDock } from "./useCoveredByDock"; import styles from "./Channels.module.css"; import { BOARD_MAIN_MIN_REM } from "./panel-split"; +import { WorkspaceRow } from "./WorkspaceRow"; export type { PageTabOptions, PageTabsProps, PageTabTarget }; @@ -553,53 +554,56 @@ export function PageTabs({ ), actions: workspace?.actions, content: workspace ? ( -
-
- {primaryTab && - primaryChannel && - secondary.canOpenConversation(primaryChannel.id) ? ( - - secondary.openConversationLink( - primaryChannel.id, - url, - origin, - ) - } - canOpenLink={(target) => - !!host.panels.resolve(target) - } - openThread={(messageId, rootId, intent) => - secondary.openConversationThread( - primaryChannel.id, - messageId, - rootId, - intent, - ) - } - close={() => {}} - /> - ) : ( -

- This conversation is no longer available. -

- )} -
-
+ + {primaryTab && + primaryChannel && + secondary.canOpenConversation(primaryChannel.id) ? ( + + secondary.openConversationLink( + primaryChannel.id, + url, + origin, + ) + } + canOpenLink={(target) => + !!host.panels.resolve(target) + } + openThread={(messageId, rootId, intent) => + secondary.openConversationThread( + primaryChannel.id, + messageId, + rootId, + intent, + ) + } + close={() => {}} + /> + ) : ( +

+ This conversation is no longer available. +

+ )} +
) : ( children(open, close, isOpen) ), diff --git a/src/bundled/channels/WorkspaceRow.test.tsx b/src/bundled/channels/WorkspaceRow.test.tsx new file mode 100644 index 0000000000..6fb86b089b --- /dev/null +++ b/src/bundled/channels/WorkspaceRow.test.tsx @@ -0,0 +1,165 @@ +// @vitest-environment jsdom +import "@testing-library/jest-dom/vitest"; +import { + act, + cleanup, + fireEvent, + render, + screen, +} from "@testing-library/react"; +import { useContext, useState } from "react"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { ReadingCovers } from "../../features/messages/use-reading"; +import { asideLayout, WorkspaceRow } from "./WorkspaceRow"; + +let width = 1200; +const observers = new Set<() => void>(); +class TestResizeObserver { + constructor(private callback: () => void) {} + observe() { + observers.add(this.callback); + } + unobserve() {} + disconnect() { + observers.delete(this.callback); + } +} +function resize(next: number) { + width = next; + act(() => { + for (const callback of observers) callback(); + }); +} + +beforeEach(() => { + width = 1200; + vi.stubGlobal("ResizeObserver", TestResizeObserver); + vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation( + () => new DOMRect(0, 0, width, 600), + ); +}); +afterEach(() => { + cleanup(); + observers.clear(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +let covers: () => readonly DOMRect[] = () => []; +function Covers() { + covers = useContext(ReadingCovers); + return null; +} +/** A page whose header button drives the aside, as the contract asks. */ +function Page({ onOpenChange }: { onOpenChange?: (open: boolean) => void }) { + const [open, setOpen] = useState(true); + return ( + <> + + + + + } + width={undefined} + open={open} + onOpenChange={(next) => { + onOpenChange?.(next); + setOpen(next); + }} + > +
History
+ +
+ + ); +} +const plan = () => + screen.queryByRole("complementary", { name: "Plan", hidden: true }); + +it("docks an aside only while its reader keeps the minimum width", () => { + expect(asideLayout(920)).toEqual({ docked: true, width: 320 }); + expect(asideLayout(919)).toEqual({ docked: false, width: 320 }); + expect(asideLayout(300)).toEqual({ docked: false, width: 300 }); + expect(asideLayout(999, 400)).toEqual({ docked: false, width: 400 }); + expect(asideLayout(1000, 400)).toEqual({ docked: true, width: 400 }); +}); + +it("docks the aside in a column after the reader, shown by the page's control", () => { + render(); + const box = plan()?.parentElement; + expect(box).toHaveAttribute("data-workspace-aside", "docked"); + expect(box).toHaveStyle({ inlineSize: "320px" }); + expect(screen.getByText("History").parentElement?.nextElementSibling).toBe( + box, + ); + expect(plan()).toBeVisible(); + expect(covers()).toEqual([]); + fireEvent.click(screen.getByRole("button", { name: "Plan" })); + expect(plan()).not.toBeVisible(); +}); + +it("closes the aside as it floats and restores the docked state after", () => { + const changes: boolean[] = []; + render( changes.push(open)} />); + const reader = screen.getByText("History"); + resize(800); + expect(changes).toEqual([false]); + expect(plan()?.parentElement).toHaveAttribute( + "data-workspace-aside", + "floating", + ); + expect(plan()).not.toBeVisible(); + resize(1200); + expect(changes).toEqual([false, true]); + expect(plan()).toBeVisible(); + // A docked aside hidden by its page stays hidden when it docks again. + fireEvent.click(screen.getByRole("button", { name: "Plan" })); + resize(800); + resize(1200); + expect(plan()).not.toBeVisible(); + // The reader never remounts. + expect(screen.getByText("History")).toBe(reader); +}); + +it("an aside that first measures narrow starts closed", () => { + width = 700; + const changes: boolean[] = []; + render( changes.push(open)} />); + expect(changes).toEqual([false]); + expect(plan()).not.toBeVisible(); +}); + +it("a floating aside takes focus, covers reading, and closes alone on Escape or a press beside it", () => { + width = 800; + const changes: boolean[] = []; + render( changes.push(open)} />); + const toggle = screen.getByRole("button", { name: "Plan" }); + toggle.focus(); + fireEvent.click(toggle); + const box = plan()?.parentElement as HTMLElement; + expect(plan()).toBeVisible(); + expect(box).toHaveFocus(); + expect(covers()).toHaveLength(1); + + const outer = vi.fn(); + document.addEventListener("keydown", outer); + fireEvent.keyDown(screen.getByRole("button", { name: "Step" }), { + key: "Escape", + }); + document.removeEventListener("keydown", outer); + expect(outer).not.toHaveBeenCalled(); + expect(plan()).not.toBeVisible(); + expect(toggle).toHaveFocus(); + expect(covers()).toEqual([]); + + fireEvent.click(toggle); + fireEvent.pointerDown(screen.getByRole("button", { name: "Step" })); + expect(plan()).toBeVisible(); + fireEvent.pointerDown(screen.getByText("History")); + expect(plan()).not.toBeVisible(); + expect(changes).toEqual([false, false, false]); +}); diff --git a/src/bundled/channels/WorkspaceRow.tsx b/src/bundled/channels/WorkspaceRow.tsx new file mode 100644 index 0000000000..c495800456 --- /dev/null +++ b/src/bundled/channels/WorkspaceRow.tsx @@ -0,0 +1,187 @@ +import { + useCallback, + useEffect, + useEffectEvent, + useLayoutEffect, + useRef, + useState, + type CSSProperties, + type ReactNode, +} from "react"; +import type { WorkspaceAsideWidth } from "../../features/conversation/contracts"; +import { + ReadingCovers, + readingPositioned, +} from "../../features/messages/use-reading"; +import styles from "./Channels.module.css"; + +const DEFAULT_WIDTH = 320; +/** The narrowest reader a docked aside leaves beside it. */ +const MIN_READER = 600; + +/** + * Where an aside goes in a row this wide, and how wide it is. The only place + * that decides the aside's placement, from the host's own row width; a later + * width form adds its rule here. + */ +export function asideLayout( + rowWidth: number, + width: WorkspaceAsideWidth = DEFAULT_WIDTH, +) { + const docked = rowWidth - width >= MIN_READER; + return { docked, width: docked ? width : Math.min(width, rowWidth) }; +} + +type Props = { + aside: ReactNode; + width: WorkspaceAsideWidth | undefined; + open: boolean | undefined; + onOpenChange: ((open: boolean) => void) | undefined; + children: ReactNode; +}; + +/** + * A workspace's reader and its page's aside: a column beside the reader, or, + * when the reader would get too narrow, an overlay over the history's end edge + * while open. Rows under the overlay aren't read. + */ +export function WorkspaceRow({ + aside, + width, + open: controlled, + onOpenChange, + children, +}: Props) { + const row = useRef(null); + const reader = useRef(null); + const box = useRef(null); + const [rowWidth, setRowWidth] = useState(); + const [inner, setInner] = useState(true); + const open = controlled ?? inner; + const change = useEffectEvent((next: boolean) => { + setInner(next); + onOpenChange?.(next); + }); + const layout = + rowWidth === undefined ? undefined : asideLayout(rowWidth, width); + const docked = layout?.docked ?? true; + const floating = aside != null && !docked && open; + + useLayoutEffect(() => { + const element = row.current; + if (!element) return; + const measure = () => setRowWidth(element.getBoundingClientRect().width); + measure(); + const observer = new ResizeObserver(measure); + observer.observe(element); + return () => observer.disconnect(); + }, []); + + // Narrowing to a floating aside closes it; widening again restores the + // docked state. An aside that first measures narrow narrows from docked. + const dockedOpen = useRef(open); + const transition = useEffectEvent((docked: boolean) => { + if (!docked) { + dockedOpen.current = open; + if (open) change(false); + } else if (open !== dockedOpen.current) change(dockedOpen.current); + }); + const wasDocked = useRef(true); + useLayoutEffect(() => { + if (wasDocked.current === docked) return; + wasDocked.current = docked; + transition(docked); + }, [docked]); + + // The overlay spans the history, beside its scrollbar, not the composer. + // Its owner wakes reading whenever the overlay opens, moves or closes. + const [geometry, setGeometry] = useState(); + const wasFloating = useRef(false); + useLayoutEffect(() => { + const scroller = reader.current?.querySelector( + "[data-message-scroller]", + ); + if (!floating) { + setGeometry(undefined); + if (wasFloating.current) readingPositioned(scroller ?? null); + wasFloating.current = false; + return; + } + wasFloating.current = true; + const container = row.current; + if (!container || !scroller) return; + const measure = () => { + const outer = container.getBoundingClientRect(); + const history = scroller.getBoundingClientRect(); + setGeometry({ + "--aside-top": `${history.top - outer.top}px`, + "--aside-height": `${history.height}px`, + "--aside-scrollbar": `${scroller.offsetWidth - scroller.clientWidth}px`, + } as CSSProperties); + readingPositioned(scroller); + }; + measure(); + const observer = new ResizeObserver(measure); + observer.observe(container); + observer.observe(scroller); + return () => observer.disconnect(); + }, [floating]); + + // A nested surface: Escape and a press elsewhere in the row close only it. + useEffect(() => { + const element = box.current; + const container = row.current; + if (!floating || !element || !container) return; + const previous = + document.activeElement instanceof HTMLElement + ? document.activeElement + : null; + element.focus({ preventScroll: true }); + const keydown = (event: KeyboardEvent) => { + if (event.key !== "Escape" || event.defaultPrevented) return; + event.preventDefault(); + event.stopPropagation(); + change(false); + previous?.focus({ preventScroll: true }); + }; + const pointerdown = (event: PointerEvent) => { + const target = event.target as Node; + if (container.contains(target) && !element.contains(target)) + change(false); + }; + element.addEventListener("keydown", keydown); + document.addEventListener("pointerdown", pointerdown, true); + return () => { + element.removeEventListener("keydown", keydown); + document.removeEventListener("pointerdown", pointerdown, true); + }; + }, [floating]); + + // Stable, so opening the overlay doesn't rerender the readers. + const covers = useCallback(() => { + const element = box.current; + return element?.dataset.workspaceAside === "floating" && !element.hidden + ? [element.getBoundingClientRect()] + : []; + }, []); + + return ( +
+
+ {children} +
+ {aside != null && ( + + )} +
+ ); +} diff --git a/src/bundled/channels/index.test.tsx b/src/bundled/channels/index.test.tsx index b68c04e937..8999cc7d87 100644 --- a/src/bundled/channels/index.test.tsx +++ b/src/bundled/channels/index.test.tsx @@ -62,7 +62,7 @@ it("declares the workspace slots that Channels renders", () => { const registerWorkspace = vi.fn(); registered(registerWorkspace); expect(registerWorkspace).toHaveBeenCalledWith(expect.any(Function), { - slots: { headerActions: true, trailing: true }, + slots: { headerActions: true, trailing: true, aside: true }, }); }); diff --git a/src/bundled/channels/index.tsx b/src/bundled/channels/index.tsx index 5f36420c8a..99170a7202 100644 --- a/src/bundled/channels/index.tsx +++ b/src/bundled/channels/index.tsx @@ -82,7 +82,7 @@ export const apply: PluginModule["apply"] = (ctx) => { (props) => ( ), - { slots: { headerActions: true, trailing: true } }, + { slots: { headerActions: true, trailing: true, aside: true } }, ); const relay = ctx.relay; const navigator = ctx.navigation; diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index 8fe659c6f2..c0cd337025 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -509,9 +509,13 @@ export type PageTabTarget = { unreadSince?: number; }; /** Optional `ConversationWorkspaceProps` a workspace provider renders. */ +/** An aside's width in pixels. A later host may also accept an object form, + * such as a share of a wide reader. */ +export type WorkspaceAsideWidth = number; export type WorkspaceSlots = Readonly<{ headerActions?: true; trailing?: true; + aside?: true; }>; /** A page-owned conversation with the host's reader, composer, and side pane. */ export type ConversationWorkspaceProps = { @@ -537,6 +541,21 @@ export type ConversationWorkspaceProps = { restHeight: number; content(state: { expanded: boolean; toggle(): void }): ReactNode; }; + /** Content beside the main tab's reader. The host gives it a column of + * `asideWidth` at the reader's end edge, between the reader's top and its + * bottom, and the reader narrows by that width. When the reader would get + * too narrow, the aside floats instead: an overlay over the history's end + * edge, shown only while open. The content fills the box and scrolls itself. */ + aside?: ReactNode; + /** The aside's width. Defaults to 320. */ + asideWidth?: WorkspaceAsideWidth; + /** Whether the aside shows: docked by default, floating once opened. The + * host closes a floating aside when the reader narrows to it, restores the + * docked state when it widens again, and closes the overlay on Escape or a + * press outside it, reporting each change. A page drives it from its own + * control; without one, a floating aside stays closed. */ + asideOpen?: boolean; + onAsideOpenChange?(open: boolean): void; /** Actions in the pane's menu and the main tab's context menu. */ actions?: readonly { label: string; run(): void }[]; /** Select this panel on entry. Closing it keeps the main conversation. */ diff --git a/src/features/messages/use-reading.test.ts b/src/features/messages/use-reading.test.ts index 1a1390e695..cc779392ed 100644 --- a/src/features/messages/use-reading.test.ts +++ b/src/features/messages/use-reading.test.ts @@ -3,7 +3,7 @@ import { act, cleanup, renderHook } from "@testing-library/react"; import { createElement, useEffect, type ReactNode } from "react"; import { afterEach, expect, it, vi } from "vitest"; import { MessageEditScope, useMessageEditScope } from "./MessageEditScope"; -import { readingPositioned, useReading } from "./use-reading"; +import { ReadingCovers, readingPositioned, useReading } from "./use-reading"; import type { RelaySession } from "../relay/session"; afterEach(() => { @@ -33,6 +33,7 @@ function setup({ concealed = false, focus = "element" as "element" | "composer" | "parent" | "outside" | "header", trailing = undefined as (() => number | undefined) | undefined, + covers = (() => []) as () => readonly DOMRect[], } = {}) { vi.useFakeTimers(); vi.spyOn(document, "hasFocus").mockReturnValue(focused); @@ -143,7 +144,7 @@ function setup({ MessageEditScope, null, createElement(Composer, { input: composer }), - children, + createElement(ReadingCovers, { value: covers }, children), ), ), }); @@ -786,6 +787,23 @@ it.each([ }, ); +it("rows under a floating overlay are not read until it closes and dwell wakes", () => { + let boxes = [new DOMRect(300, 220, 200, 200)]; + const h = setup({ latestMessageId: "covered", covers: () => boxes }); + h.setRows([row("visible", 100, 200), row("covered", 250, 350)]); + h.mutation(); + vi.advanceTimersToNextFrame(); + vi.advanceTimersByTime(300); + expect(h.dwelled()?.observe).toHaveBeenCalledExactlyOnceWith(["visible"]); + expect(h.dwelled()?.catchUp).not.toHaveBeenCalled(); + boxes = []; + readingPositioned(h.element); + vi.advanceTimersByTime(300); + expect(h.dwelled()?.catchUp).toHaveBeenCalledExactlyOnceWith( + "covered", + undefined, + ); +}); it("settled notification starts dwell without changed rows, focus or geometry", () => { const h = setup({ focus: "header", settled: false }); vi.advanceTimersByTime(300); diff --git a/src/features/messages/use-reading.ts b/src/features/messages/use-reading.ts index 18de5345f7..7121865a6f 100644 --- a/src/features/messages/use-reading.ts +++ b/src/features/messages/use-reading.ts @@ -1,4 +1,6 @@ import { + createContext, + useContext, useEffect, useEffectEvent, useLayoutEffect, @@ -57,6 +59,10 @@ type Reading = { * shown. */ trailing?: (() => number | undefined) | undefined; }; +/** Boxes of content floating over the rows below: a row any of them overlaps + * isn't shown. Its provider wakes dwell, with `readingPositioned`, when they + * change. */ +export const ReadingCovers = createContext<() => readonly DOMRect[]>(() => []); /** `useReading` for an owner that renders its own `MessageEditScope`. */ export function Reading(props: Reading) { useReading(props); @@ -80,6 +86,7 @@ export function useReading({ trailing, }: Reading) { const composer = useMessageEditScope()?.input; + const covers = useContext(ReadingCovers); // Read at measurement time: a new latest message mutates the list, which // already remeasures in the next frame, so it must not restart observation. const latestId = useEffectEvent(() => latestMessageId); @@ -87,8 +94,10 @@ export function useReading({ // A ref, not an effect event: unread attention asks whether a row is shown // while it renders. const trailingEdge = useRef(trailing); + const covering = useRef(covers); useLayoutEffect(() => { trailingEdge.current = trailing; + covering.current = covers; }); useEffect(() => { if (!enabled || !scroller.current) return; @@ -187,9 +196,14 @@ export function useReading({ } // Within a pixel: scroll offsets snap to whole pixels but rows sit at // fractional ones, so an exact reveal can leave its row a sliver past an edge. - function shown(row: HTMLElement, viewport: DOMRect) { + function shown( + row: HTMLElement, + viewport: DOMRect, + covers = covering.current(), + ) { const bounds = row.getBoundingClientRect(); return ( + !covered(bounds, covers) && row.dataset.membershipRow === undefined && row.dataset.huddleRow === undefined && bounds.height > 0 && @@ -201,6 +215,16 @@ export function useReading({ bounds.right <= Math.min(viewport.right, window.innerWidth) + 1 ); } + // Overlapping by more than a pixel, like the edges above. + function covered(bounds: DOMRect, covers: readonly DOMRect[]) { + return covers.some( + (box) => + box.left < bounds.right - 1 && + box.right > bounds.left + 1 && + box.top < bounds.bottom - 1 && + box.bottom > bounds.top + 1, + ); + } function shownBottom(viewport: DOMRect) { return Math.min( viewport.bottom, @@ -209,9 +233,10 @@ export function useReading({ } function visibleIds() { const viewport = element.getBoundingClientRect(); + const covers = covering.current(); return [...element.querySelectorAll("[data-message-id]")] .flatMap((row) => - row.dataset.messageId && shown(row, viewport) + row.dataset.messageId && shown(row, viewport, covers) ? [row.dataset.messageId] : [], ) @@ -250,6 +275,7 @@ export function useReading({ ); const bounds = row?.getBoundingClientRect(); return bounds && + !covered(bounds, covering.current()) && bounds.height > 0 && bounds.width > 0 && bounds.bottom > Math.max(viewport.top, 0) && diff --git a/src/plugins/author.ts b/src/plugins/author.ts index 5858abc81c..7e02f982ed 100644 --- a/src/plugins/author.ts +++ b/src/plugins/author.ts @@ -93,6 +93,7 @@ export type { export type { ConversationWorkspaceProps, WorkspaceSlots, + WorkspaceAsideWidth, PageTabTarget, PageTabOptions, PageTabsProps, diff --git a/tests/browser/aside-fixture.tsx b/tests/browser/aside-fixture.tsx new file mode 100644 index 0000000000..b92dc3fe99 --- /dev/null +++ b/tests/browser/aside-fixture.tsx @@ -0,0 +1,42 @@ +import { + PopoverPopup, + PopoverRoot, + PopoverTrigger, +} from "../../src/shared/design-system/ui/Popover"; + +// A dashboard shaped like a plugin's Plan tile. It fills the box the host +// gives it and scrolls its own content; its Details popover escapes the box, +// over the history. `short` fits in a window, `tall` is taller than one. +const STEP = + "Check the rollout dashboard, confirm error rates stay flat, then post the summary."; + +export type AsideSize = "short" | "tall"; + +export function AsideWidget({ size }: { size: AsideSize }) { + const steps = size === "tall" ? 28 : 5; + return ( +
+

+ Plan · {steps} steps{" "} + + Details + + Step details escape the Plan, over the history. + + +

+
    + {Array.from({ length: steps }, (_, index) => index + 1).map((step) => ( +
  1. + Step {step}. {STEP} +
  2. + ))} +
+

End of plan

+
+ ); +} diff --git a/tests/browser/plugin-fixtures.tsx b/tests/browser/plugin-fixtures.tsx index a10458c11d..1f6ad4df99 100644 --- a/tests/browser/plugin-fixtures.tsx +++ b/tests/browser/plugin-fixtures.tsx @@ -2,6 +2,7 @@ import { soloRegionFixture } from "./solo-region-fixture"; import { companionPlugins } from "./companion-fixture"; import { trailingBrief, trailingCard } from "./trailing-fixture"; +import { AsideWidget, type AsideSize } from "./aside-fixture"; import * as shortcutCounter from "../../examples/plugins/shortcut-counter/plugin.js"; import shortcutManifest from "../../examples/plugins/shortcut-counter/manifest.json"; import { useEffect, useMemo, useState, useSyncExternalStore } from "react"; @@ -59,6 +60,8 @@ declare global { stalePanelClose?: () => void; fixtureNavigation?: Navigation; fixtureNotify?: (input: NotificationInput) => Promise; + /** Adds or removes the reader's aside in place; undefined follows the route. */ + fixtureAside?: (size: AsideSize | null | undefined) => void; fixturePageBroken?: boolean; fixtureSidebarWorkIconThrows?: boolean; fixtureSidebarRecovery?: boolean; @@ -500,13 +503,28 @@ export const fixturePlugins: readonly BundledPlugin[] = [ route?.kind === "page" ? (route.route?.params as PageTabTarget & { trailing?: "none" | "short" | "long"; + aside?: AsideSize; }) : undefined; const trailing = params?.trailing; + // A plugin adds or removes its aside in place, as its content arrives. + const [shownAside, setShownAside] = useState(); + // The page's own control drives the aside, as the contract asks. + const [asideOpen, setAsideOpen] = useState(true); + useEffect(() => { + window.fixtureAside = setShownAside; + return () => { + delete window.fixtureAside; + }; + }, []); + const asideSize = + shownAside === undefined + ? params?.aside + : (shownAside ?? undefined); // The route's own target, kept stable across renders. const target = useMemo(() => { if (!params) return undefined; - const { trailing: _, ...target } = params; + const { trailing: _, aside: __, ...target } = params; return target; }, [params]); // Approving removes the card in place, as a plugin's decision does. @@ -547,6 +565,15 @@ export const fixturePlugins: readonly BundledPlugin[] = [ > Jump retained transcript + {asideSize && ( + + )}
, + asideOpen, + onAsideOpenChange: setAsideOpen, + } + : {})} latestRequest={ request && request.opening === opening ? request.signal diff --git a/tests/browser/workspace-aside.spec.mjs b/tests/browser/workspace-aside.spec.mjs new file mode 100644 index 0000000000..8427c6a7c3 --- /dev/null +++ b/tests/browser/workspace-aside.spec.mjs @@ -0,0 +1,353 @@ +// A workspace's aside docks in a column of its declared width beside the +// reader, or floats over the history's end edge when the reader is narrow. +import { test, expect } from "./fixture.mjs"; +import { open, settle } from "./timeline.mjs"; + +test.use({ + pluginFixtures: true, + historyCounts: { alpha: 640, beta: 3 }, + viewport: { width: 1280, height: 800 }, +}); + +const history = (page) => + page.getByRole("region", { name: "Channel message history" }); +// The host's box around the plugin's content. +const aside = (page) => page.locator("[data-workspace-aside]"); +const plan = (page) => page.getByRole("region", { name: "Fixture dashboard" }); + +async function openReader(page, params) { + await expect + .poll(() => + page.evaluate(async (params) => { + const result = await window.fixtureNavigation + ?.open({ + version: 1, + kind: "page", + pluginId: "fixture.session", + pageId: "reader", + route: { version: 1, params: { channelId: "alpha", ...params } }, + }) + .catch(() => undefined); + return result?.status; + }, params), + ) + .toBe("opened"); +} + +async function openAside(page, params = {}) { + await openReader(page, { aside: "tall", ...params }); + await expect(plan(page)).toBeVisible(); +} + +// The history, its list, the aside and the composer, in viewport pixels. +const layout = (page) => + history(page).evaluate((element) => { + const box = (node) => { + const { top, right, bottom, left, width, height } = + node.getBoundingClientRect(); + return { top, right, bottom, left, width, height }; + }; + const widget = document.querySelector("[data-workspace-aside]"); + const region = widget.querySelector("[data-fixture-aside-scroll]"); + return { + history: box(element), + scrollbar: element.offsetWidth - element.clientWidth, + list: box(element.querySelector("ol")), + aside: box(widget), + reader: box(widget.previousElementSibling), + composer: box(element.parentElement.querySelector("form")), + region: { + scrollHeight: region.scrollHeight, + clientHeight: region.clientHeight, + scrollTop: region.scrollTop, + }, + }; + }); + +// The offset past the latest message, less any trailing card's growth. +const past = (region) => + region.evaluate((element) => { + const content = element.querySelector( + '[aria-label="Fixture card"]', + )?.parentElement; + const card = -Number.parseFloat(content?.style.bottom || "0"); + return ( + element.scrollTop - + Math.max(0, element.scrollHeight - element.clientHeight - card) + ); + }); + +test("a docked aside takes a column of its width beside the history and composer", async ({ + page, + app, +}) => { + await open(page, app); + await openAside(page); + const region = history(page); + await settle(page, region); + const at = await layout(page); + expect(at.aside.width).toBe(320); + expect(Math.abs(at.reader.right - at.aside.left)).toBeLessThanOrEqual(1); + expect(at.history.right).toBeLessThanOrEqual(at.aside.left + 1); + expect(at.composer.right).toBeLessThanOrEqual(at.aside.left + 1); + // The composer stays centered under the narrowed history. It spans the + // frame and the list the scrollport, so a classic scrollbar moves the + // list's center by half its width. + expect( + Math.abs( + at.composer.left + + at.composer.width / 2 - + (at.list.left + at.list.width / 2) - + at.scrollbar / 2, + ), + ).toBeLessThanOrEqual(2); + // The column runs the reader's height, and the plan scrolls inside it. + expect(Math.abs(at.aside.top - at.reader.top)).toBeLessThanOrEqual(1); + expect(Math.abs(at.aside.bottom - at.reader.bottom)).toBeLessThanOrEqual(1); + expect(at.region.scrollHeight).toBeGreaterThan(at.region.clientHeight); + + // Wheeling over the aside scrolls only the plan. + const offset = await region.evaluate((element) => element.scrollTop); + await plan(page).hover(); + for (let i = 0; i < 3; i++) await page.mouse.wheel(0, 120); + await expect + .poll(async () => (await layout(page)).region.scrollTop) + .toBeGreaterThan(100); + expect(await region.evaluate((element) => element.scrollTop)).toBe(offset); + + // The page's control hides it, and the history takes the width back. + await page.getByRole("button", { name: "Hide plan" }).click(); + await expect(plan(page)).toBeHidden(); + await expect + .poll(async () => + history(page).evaluate( + (element) => element.getBoundingClientRect().right, + ), + ) + .toBeGreaterThan(at.aside.right - 2); +}); + +test("an aside's popover escapes over the history", async ({ page, app }) => { + await open(page, app); + await openAside(page); + await settle(page, history(page)); + await plan(page).getByRole("button", { name: "Details" }).click(); + const popup = page.getByText("Step details escape the Plan"); + await expect(popup).toBeVisible(); + const shown = await popup.evaluate((node) => { + const box = node.getBoundingClientRect(); + const x = box.left + 8; + const y = box.top + box.height / 2; + return { + left: box.left, + asideLeft: document + .querySelector("[data-workspace-aside]") + .getBoundingClientRect().left, + // It sits above the history's rows under it. + onTop: node.contains(document.elementFromPoint(x, y)), + }; + }); + expect(shown.left).toBeLessThan(shown.asideLeft - 20); + expect(shown.onTop).toBe(true); +}); + +test("adding and removing the aside keeps the reader at the latest message", async ({ + page, + app, +}) => { + await open(page, app); + await openReader(page, {}); + const region = history(page); + await settle(page, region); + expect(Math.abs(await past(region))).toBeLessThanOrEqual(1); + // The same scroller stays mounted throughout. + await region.evaluate((element) => { + window.asideScroller = element; + }); + const same = () => + region.evaluate((element) => element === window.asideScroller); + // As a plugin does when its content arrives, without a navigation. + await page.evaluate(() => window.fixtureAside("tall")); + await expect(plan(page)).toBeVisible(); + await settle(page, region); + expect(Math.abs(await past(region))).toBeLessThanOrEqual(1); + expect(await same()).toBe(true); + await page.evaluate(() => window.fixtureAside(null)); + await expect(aside(page)).toHaveCount(0); + await settle(page, region); + expect(Math.abs(await past(region))).toBeLessThanOrEqual(1); + expect(await same()).toBe(true); +}); + +test("a narrow reader floats the aside over the history while the page opens it", async ({ + page, + app, +}) => { + await open(page, app); + await openAside(page); + const region = history(page); + await settle(page, region); + const docked = (await layout(page)).list.width; + // Narrowing closes it, and the history takes the full width. + await page.setViewportSize({ width: 900, height: 800 }); + await expect(plan(page)).toBeHidden(); + const show = page.getByRole("button", { name: "Show plan" }); + await expect(show).toHaveAttribute("aria-expanded", "false"); + const closed = await layout(page); + expect( + Math.abs(closed.history.right - closed.reader.right), + ).toBeLessThanOrEqual(1); + const full = await region.evaluate((element) => element.clientWidth); + + // Opened, it floats over the history's end edge, not the composer, takes + // no width, holds focus, and scrolls its own content. WebKit doesn't focus + // a clicked button, so the control opens it from the keyboard. + await show.focus(); + await page.keyboard.press("Enter"); + await expect(plan(page)).toBeVisible(); + await expect(aside(page)).toBeFocused(); + await settle(page, region); + const at = await layout(page); + expect(at.aside.top).toBeGreaterThanOrEqual(at.history.top); + expect(at.aside.bottom).toBeLessThanOrEqual(at.history.bottom); + expect(at.aside.bottom).toBeLessThan(at.composer.top); + expect(at.aside.right).toBeLessThanOrEqual(at.history.right - at.scrollbar); + expect(await region.evaluate((element) => element.clientWidth)).toBe(full); + const offset = await region.evaluate((element) => element.scrollTop); + await plan(page).hover(); + for (let i = 0; i < 3; i++) await page.mouse.wheel(0, 120); + await expect + .poll(async () => (await layout(page)).region.scrollTop) + .toBeGreaterThan(100); + expect(await region.evaluate((element) => element.scrollTop)).toBe(offset); + + // Escape closes only the overlay and returns focus to the page's control. + await page.keyboard.press("Escape"); + await expect(plan(page)).toBeHidden(); + await expect(show).toBeFocused(); + // A press on the history closes it too. + await show.click(); + await expect(plan(page)).toBeVisible(); + await region.click({ position: { x: 40, y: 40 } }); + await expect(plan(page)).toBeHidden(); + + // Widening docks it again, restoring the docked state. + await page.setViewportSize({ width: 1280, height: 800 }); + await expect(plan(page)).toBeVisible(); + await expect(page.getByRole("button", { name: "Hide plan" })).toBeVisible(); + await expect + .poll(async () => (await layout(page)).list.width) + .toBeCloseTo(docked, 0); + await settle(page, region); + expect(Math.abs(await past(region))).toBeLessThanOrEqual(1); +}); + +test("a live resize beside an aside keeps the reader at rest", async ({ + page, + app, +}) => { + await open(page, app); + await openAside(page, { trailing: "long" }); + const region = history(page); + await settle(page, region); + expect(Math.abs(await past(region))).toBeLessThanOrEqual(1); + // A window drag resizes faster than the timeline renders, undocking and + // docking the aside and rewrapping the card as it goes. + for (const [from, to] of [ + [1280, 860], + [860, 1320], + ]) { + for (let step = 1; step <= 30; step++) + await page.setViewportSize({ + width: Math.round(from + ((to - from) * step) / 30), + height: 800, + }); + await settle(page, region); + expect( + Math.abs(await past(region)), + `at rest after resizing to ${to}`, + ).toBeLessThanOrEqual(1); + } +}); + +test.describe("in a thread", () => { + test.use({ + readState: true, + threadUnread: true, + historyCounts: { alpha: 40, beta: 3 }, + }); + + test("a thread target docks the aside beside the thread", async ({ + page, + app, + }) => { + await open(page, app); + const root = app.histories + .get("primary/alpha") + .find((row) => row.content === "Thread root 1"); + await openAside(page, { threadId: root.id }); + const thread = aside(page) + .locator("xpath=preceding-sibling::*[1]") + .locator("[data-message-scroller]"); + await expect(thread).toBeVisible(); + const [box, column] = await Promise.all([ + thread.boundingBox(), + aside(page).boundingBox(), + ]); + expect(column.width).toBe(320); + expect(box.x + box.width).toBeLessThanOrEqual(column.x + 1); + }); +}); + +test.describe("beside a narrow dock", () => { + test.use({ + readState: true, + threadUnread: true, + historyCounts: { alpha: 40, beta: 3 }, + viewport: { width: 600, height: 800 }, + }); + + test("a narrow dock covers the floating aside", async ({ page, app }) => { + await open(page, app); + await openReader(page, { aside: "tall" }); + const region = history(page); + await settle(page, region); + await page.getByRole("button", { name: "Show plan" }).click(); + await expect(plan(page)).toBeVisible(); + const box = await plan(page).boundingBox(); + const center = { x: box.x + box.width / 2, y: box.y + box.height / 2 }; + const root = app.histories + .get("primary/alpha") + .find((row) => row.content === "Thread root 1"); + const row = region.locator(`[data-message-id="${root.id}"]`); + await row.scrollIntoViewIfNeeded(); + await row.hover({ position: { x: 24, y: 8 } }); + // A click alone, as a press on the history would close the overlay. + await row + .getByRole("button", { name: /^View thread:/ }) + .dispatchEvent("click"); + const dock = page.locator("[data-panel-dock]"); + await expect(dock).toBeVisible(); + await dock.evaluate((element) => + Promise.allSettled( + element.getAnimations().map((animation) => animation.finished), + ), + ); + // The dock paints over the overlay. Hit testing skips the covered, inert + // reader, so the probe lifts that while it reads the paint order. + expect( + await page.evaluate(({ x, y }) => { + const widget = document.querySelector("[data-workspace-aside]"); + const covered = widget.closest("[inert]"); + covered?.removeAttribute("inert"); + const hit = document.elementFromPoint(x, y); + covered?.setAttribute("inert", ""); + return { + open: !widget.hidden, + covered: !!covered, + docked: !!hit?.closest("[data-panel-dock]"), + }; + }, center), + ).toEqual({ open: true, covered: true, docked: true }); + }); +}); From c0d646ae214592ddc08fe749207088aa4a5954d5 Mon Sep 17 00:00:00 2001 From: Gil Birman Date: Tue, 24 Nov 2026 14:35:55 -0600 Subject: [PATCH 2/5] docs(plugins): say how an aside's popover escapes its box Co-Authored-By: Claude Opus 5.5 Signed-off-by: Gil Birman --- docs/plugin-authoring-guide.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/plugin-authoring-guide.md b/docs/plugin-authoring-guide.md index d908e7dc88..b05d83ce93 100644 --- a/docs/plugin-authoring-guide.md +++ b/docs/plugin-authoring-guide.md @@ -116,7 +116,8 @@ Check `ctx.conversation.workspaceSlots?.aside === true` before passing `aside` to `ui.Workspace`. The host places it: a column of `asideWidth` (default 320) beside the reader, which narrows to leave it room, or, when the reader would get too narrow, an overlay over the history's end edge. Fill the box and scroll -your content inside it; use `ui` popovers so they can escape over the history. +your content inside it. A popover escapes over the history only from a +portal, as `ui.Menu`'s does. Drive it from your own header control with `asideOpen` and `onAsideOpenChange`: docked, it shows by default; floating, it shows only once opened. The host closes it as it floats, restores the docked state when the From 20bf2b93312efa5b9c7cde208131578e166206be Mon Sep 17 00:00:00 2001 From: Gil Birman Date: Tue, 24 Nov 2026 15:31:22 -0600 Subject: [PATCH 3/5] feat(conversation): keep a docked aside over the history's end edge A workspace aside now sits over the history's end edge in both modes, left of the history's scrollbar and above the composer. Docked, the history still spans the reader, so its scrollbar stays at the far end, and the rows, composer, queue and typing label keep to the width beside the aside through --timeline-aside-width, set from the declared width. The box draws nothing: the page's content draws its card, sizes to it and scrolls itself, and only that content takes pointer input, so the wheel beside or below the card scrolls the history. The floating aside loses its surface but keeps Escape and outside-press dismissal. A new onAsideFloatingChange tells the page whether the aside floats. The row finds the history again when the reader replaces it or shows it late, as a loading thread does. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Gil Birman --- docs/plugin-authoring-guide.md | 16 ++- src/bundled/channels/Channels.module.css | 37 +++--- src/bundled/channels/PageTabs.tsx | 1 + src/bundled/channels/WorkspaceRow.test.tsx | 44 +++++-- src/bundled/channels/WorkspaceRow.tsx | 90 +++++++++---- src/features/conversation/contracts.ts | 16 ++- src/features/messages/Messages.module.css | 23 +++- .../messages/QueuedFollowUps.module.css | 8 +- .../messages/TypingIndicator.module.css | 13 +- tests/browser/aside-fixture.tsx | 20 ++- tests/browser/plugin-fixtures.tsx | 3 + tests/browser/workspace-aside.spec.mjs | 119 ++++++++++++++---- 12 files changed, 292 insertions(+), 98 deletions(-) diff --git a/docs/plugin-authoring-guide.md b/docs/plugin-authoring-guide.md index b05d83ce93..ccb84d85aa 100644 --- a/docs/plugin-authoring-guide.md +++ b/docs/plugin-authoring-guide.md @@ -113,17 +113,21 @@ opaque background, and draw its outline with a box shadow rather than a bottom border. Check `ctx.conversation.workspaceSlots?.aside === true` before passing `aside` -to `ui.Workspace`. The host places it: a column of `asideWidth` (default 320) -beside the reader, which narrows to leave it room, or, when the reader would -get too narrow, an overlay over the history's end edge. Fill the box and scroll -your content inside it. A popover escapes over the history only from a -portal, as `ui.Menu`'s does. +to `ui.Workspace`. The host places it in a box of `asideWidth` (default 320) +over the history's end edge, left of its scrollbar and above the composer. +Docked, the history's rows and the composer keep to the width beside it; when +the reader would get too narrow, it floats over the history instead. The box +draws nothing in either mode: draw your own card, let it size to its content, +and scroll inside it when it is taller than the box. Only your content takes +pointer input, so the wheel beside or below it scrolls the history. A popover +escapes over the history only from a portal, as `ui.Menu`'s does. Drive it from your own header control with `asideOpen` and `onAsideOpenChange`: docked, it shows by default; floating, it shows only once opened. The host closes it as it floats, restores the docked state when the reader widens, and closes the overlay on Escape or a press elsewhere in the reader, reporting each change. Without that control a floating aside stays -closed. Messages under the overlay are not marked read. +closed. `onAsideFloatingChange` tells you whether it floats, for example to +close it after a pick. Messages under the overlay are not marked read. For `ctx.agents.ui.Transcript`, give each turn a unique `turnId` that stays the same across reads. Return a new turn when it changes. Leave previously returned turns and their items untouched. diff --git a/src/bundled/channels/Channels.module.css b/src/bundled/channels/Channels.module.css index 33ea8fdcac..ee4ad2bdb4 100644 --- a/src/bundled/channels/Channels.module.css +++ b/src/bundled/channels/Channels.module.css @@ -67,30 +67,27 @@ min-height: 0; min-width: 0; } -/* The aside's box, which its content fills and scrolls itself. */ -.workspaceAside, -.floatingAside { - display: grid; - grid-template-rows: minmax(0, 1fr); - min-height: 0; -} +/* The page's aside, over the history's end edge beside its scrollbar, never + over the composer, docked or floating. It draws nothing itself: its content + draws its card, sizes to it, and scrolls itself past the history's height. + Only that content takes pointer input, so the wheel beside or below it + scrolls the history. */ .workspaceAside { - flex: none; - border-inline-start: 1px solid var(--border-standard); -} -/* Over the history's end edge, beside its scrollbar, never over the composer. */ -.floatingAside { - @apply floating-surface; position: absolute; z-index: 1; - inset-block-start: calc(var(--aside-top, 0px) + var(--space-2)); - inset-inline-end: calc(var(--aside-scrollbar, 0px) + var(--space-2)); - block-size: calc(var(--aside-height, 100%) - 2 * var(--space-2)); - max-inline-size: calc(100% - 2 * var(--space-2)); - overflow: hidden; + display: flex; + flex-direction: column; + inset-block-start: var(--aside-top, 0px); + inset-inline-end: var(--aside-scrollbar, 0px); + max-block-size: var(--aside-height, 100%); + max-inline-size: 100%; + pointer-events: none; +} +.workspaceAside > * { + min-block-size: 0; + pointer-events: auto; } -.workspaceAside[hidden], -.floatingAside[hidden] { +.workspaceAside[hidden] { display: none; } .conversation diff --git a/src/bundled/channels/PageTabs.tsx b/src/bundled/channels/PageTabs.tsx index 0c6e267e32..3c2d05560f 100644 --- a/src/bundled/channels/PageTabs.tsx +++ b/src/bundled/channels/PageTabs.tsx @@ -559,6 +559,7 @@ export function PageTabs({ width={workspace.asideWidth} open={workspace.asideOpen} onOpenChange={workspace.onAsideOpenChange} + onFloatingChange={workspace.onAsideFloatingChange} > {primaryTab && primaryChannel && diff --git a/src/bundled/channels/WorkspaceRow.test.tsx b/src/bundled/channels/WorkspaceRow.test.tsx index 6fb86b089b..ec09dc9a7d 100644 --- a/src/bundled/channels/WorkspaceRow.test.tsx +++ b/src/bundled/channels/WorkspaceRow.test.tsx @@ -51,7 +51,13 @@ function Covers() { return null; } /** A page whose header button drives the aside, as the contract asks. */ -function Page({ onOpenChange }: { onOpenChange?: (open: boolean) => void }) { +function Page({ + onOpenChange, + onFloatingChange, +}: { + onOpenChange?: (open: boolean) => void; + onFloatingChange?: (floating: boolean) => void; +}) { const [open, setOpen] = useState(true); return ( <> @@ -70,6 +76,7 @@ function Page({ onOpenChange }: { onOpenChange?: (open: boolean) => void }) { onOpenChange?.(next); setOpen(next); }} + onFloatingChange={onFloatingChange} >
History
@@ -88,26 +95,41 @@ it("docks an aside only while its reader keeps the minimum width", () => { expect(asideLayout(1000, 400)).toEqual({ docked: true, width: 400 }); }); -it("docks the aside in a column after the reader, shown by the page's control", () => { +it("docks the aside after the reader, which keeps its width beside it while shown", () => { render(); const box = plan()?.parentElement; + const reader = screen.getByText("History").parentElement as HTMLElement; expect(box).toHaveAttribute("data-workspace-aside", "docked"); expect(box).toHaveStyle({ inlineSize: "320px" }); - expect(screen.getByText("History").parentElement?.nextElementSibling).toBe( - box, - ); + expect(reader.nextElementSibling).toBe(box); + expect(reader.style.getPropertyValue("--timeline-aside-width")).toBe("320px"); + expect(reader).toHaveAttribute("data-aside-docked"); expect(plan()).toBeVisible(); expect(covers()).toEqual([]); fireEvent.click(screen.getByRole("button", { name: "Plan" })); expect(plan()).not.toBeVisible(); + expect(reader.style.getPropertyValue("--timeline-aside-width")).toBe(""); + expect(reader).not.toHaveAttribute("data-aside-docked"); }); it("closes the aside as it floats and restores the docked state after", () => { const changes: boolean[] = []; - render( changes.push(open)} />); + const floats: boolean[] = []; + render( + changes.push(open)} + onFloatingChange={(floating) => floats.push(floating)} + />, + ); const reader = screen.getByText("History"); + expect(floats).toEqual([false]); resize(800); expect(changes).toEqual([false]); + expect(floats).toEqual([false, true]); + // A floating aside leaves the history its full width. + expect( + reader.parentElement?.style.getPropertyValue("--timeline-aside-width"), + ).toBe(""); expect(plan()?.parentElement).toHaveAttribute( "data-workspace-aside", "floating", @@ -115,6 +137,7 @@ it("closes the aside as it floats and restores the docked state after", () => { expect(plan()).not.toBeVisible(); resize(1200); expect(changes).toEqual([false, true]); + expect(floats).toEqual([false, true, false]); expect(plan()).toBeVisible(); // A docked aside hidden by its page stays hidden when it docks again. fireEvent.click(screen.getByRole("button", { name: "Plan" })); @@ -128,8 +151,15 @@ it("closes the aside as it floats and restores the docked state after", () => { it("an aside that first measures narrow starts closed", () => { width = 700; const changes: boolean[] = []; - render( changes.push(open)} />); + const floats: boolean[] = []; + render( + changes.push(open)} + onFloatingChange={(floating) => floats.push(floating)} + />, + ); expect(changes).toEqual([false]); + expect(floats).toEqual([true]); expect(plan()).not.toBeVisible(); }); diff --git a/src/bundled/channels/WorkspaceRow.tsx b/src/bundled/channels/WorkspaceRow.tsx index c495800456..15aac5e08b 100644 --- a/src/bundled/channels/WorkspaceRow.tsx +++ b/src/bundled/channels/WorkspaceRow.tsx @@ -37,19 +37,23 @@ type Props = { width: WorkspaceAsideWidth | undefined; open: boolean | undefined; onOpenChange: ((open: boolean) => void) | undefined; + onFloatingChange: ((floating: boolean) => void) | undefined; children: ReactNode; }; /** - * A workspace's reader and its page's aside: a column beside the reader, or, - * when the reader would get too narrow, an overlay over the history's end edge - * while open. Rows under the overlay aren't read. + * A workspace's reader and its page's aside, placed over the history's end + * edge. Docked, the history, composer, queue and typing label keep to the + * reader's width beside it, so the history's scrollbar stays at the reader's + * end. When the reader would get too narrow, it floats over the history + * instead, while open, and rows under it aren't read. */ export function WorkspaceRow({ aside, width, open: controlled, onOpenChange, + onFloatingChange, children, }: Props) { const row = useRef(null); @@ -65,7 +69,9 @@ export function WorkspaceRow({ const layout = rowWidth === undefined ? undefined : asideLayout(rowWidth, width); const docked = layout?.docked ?? true; - const floating = aside != null && !docked && open; + const shown = aside != null && open; + const floating = shown && !docked; + const asideWidth = layout?.width ?? width ?? DEFAULT_WIDTH; useLayoutEffect(() => { const element = row.current; @@ -93,24 +99,26 @@ export function WorkspaceRow({ transition(docked); }, [docked]); - // The overlay spans the history, beside its scrollbar, not the composer. - // Its owner wakes reading whenever the overlay opens, moves or closes. + const measured = layout !== undefined; + const reportFloating = useEffectEvent((floating: boolean) => + onFloatingChange?.(floating), + ); + useLayoutEffect(() => { + if (measured) reportFloating(!docked); + }, [measured, docked]); + + // The box spans the history, beside its scrollbar, not the composer. It + // wakes reading whenever it shows, moves, floats, docks or hides. A reader + // can show its history later, as a thread does once loaded, or replace it. const [geometry, setGeometry] = useState(); - const wasFloating = useRef(false); + // biome-ignore lint/correctness/useExhaustiveDependencies: docking or floating changes what covers the rows, so reading wakes. useLayoutEffect(() => { - const scroller = reader.current?.querySelector( - "[data-message-scroller]", - ); - if (!floating) { - setGeometry(undefined); - if (wasFloating.current) readingPositioned(scroller ?? null); - wasFloating.current = false; - return; - } - wasFloating.current = true; const container = row.current; - if (!container || !scroller) return; + const frame = reader.current; + if (!shown || !container || !frame) return; + let scroller: HTMLElement | null = null; const measure = () => { + if (!scroller?.isConnected) return find(); const outer = container.getBoundingClientRect(); const history = scroller.getBoundingClientRect(); setGeometry({ @@ -120,12 +128,29 @@ export function WorkspaceRow({ } as CSSProperties); readingPositioned(scroller); }; - measure(); - const observer = new ResizeObserver(measure); - observer.observe(container); - observer.observe(scroller); - return () => observer.disconnect(); - }, [floating]); + // A removed history reports one last resize, so only a reader without + // one is watched for it to appear. + const resize = new ResizeObserver(measure); + const appear = new MutationObserver(() => find()); + const find = () => { + resize.disconnect(); + appear.disconnect(); + scroller = frame.querySelector("[data-message-scroller]"); + if (!scroller) { + appear.observe(frame, { childList: true, subtree: true }); + return; + } + resize.observe(container); + resize.observe(scroller); + measure(); + }; + find(); + return () => { + resize.disconnect(); + appear.disconnect(); + if (scroller) readingPositioned(scroller); + }; + }, [shown, floating]); // A nested surface: Escape and a press elsewhere in the row close only it. useEffect(() => { @@ -167,17 +192,28 @@ export function WorkspaceRow({ return (
-
+
{children}
{aside != null && ( diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index c0cd337025..4316062951 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -541,11 +541,14 @@ export type ConversationWorkspaceProps = { restHeight: number; content(state: { expanded: boolean; toggle(): void }): ReactNode; }; - /** Content beside the main tab's reader. The host gives it a column of - * `asideWidth` at the reader's end edge, between the reader's top and its - * bottom, and the reader narrows by that width. When the reader would get - * too narrow, the aside floats instead: an overlay over the history's end - * edge, shown only while open. The content fills the box and scrolls itself. */ + /** Content beside the main tab's history. The host places it in a box of + * `asideWidth` over the history's end edge, beside its scrollbar and above + * the composer; the history and composer keep to the width beside it. When + * the reader would get too narrow, the aside floats over the history + * instead, shown only while open. The box draws nothing: the content draws + * its own card, sizes to it, and scrolls itself when taller than the box. + * Only the content takes pointer input, so the wheel beside or below it + * scrolls the history. */ aside?: ReactNode; /** The aside's width. Defaults to 320. */ asideWidth?: WorkspaceAsideWidth; @@ -556,6 +559,9 @@ export type ConversationWorkspaceProps = { * control; without one, a floating aside stays closed. */ asideOpen?: boolean; onAsideOpenChange?(open: boolean): void; + /** Called with whether the aside floats, once the host first places it and + * whenever it moves between docked and floating. */ + onAsideFloatingChange?(floating: boolean): void; /** Actions in the pane's menu and the main tab's context menu. */ actions?: readonly { label: string; run(): void }[]; /** Select this panel on entry. Closing it keeps the main conversation. */ diff --git a/src/features/messages/Messages.module.css b/src/features/messages/Messages.module.css index 4c37b2fbba..9e5419b910 100644 --- a/src/features/messages/Messages.module.css +++ b/src/features/messages/Messages.module.css @@ -57,6 +57,16 @@ scrollbar-gutter: stable; scrollbar-width: thin; } +/* A docked workspace aside sits over the history's end edge, left of its + scrollbar; WorkspaceRow marks the reader and sets --timeline-aside-width to + its width. The rows keep to the space beside it. A docked reader is wider + than the narrow rules that follow. */ +[data-aside-docked] .feed { + padding-inline-end: calc( + var(--space-panel-inset) + + var(--timeline-aside-width) + ); +} /* Narrow conversations keep the shared compact inset beside the app dock. */ @container messages (max-width: 30rem) { .feed { @@ -856,11 +866,16 @@ html[data-keyboard-navigation] .attachmentImage:focus-visible { min-width: 0; align-self: stretch; flex-shrink: 0; - width: min(calc(100% - 2 * var(--space-4)), var(--buzz-message-width, 52rem)); + width: min( + calc(100% - var(--timeline-aside-width, 0px) - 2 * var(--space-4)), + var(--buzz-message-width, 52rem) + ); margin: 0 auto var(--space-4); + /* Beside a docked workspace aside, centered in the history's width. */ + inset-inline-start: calc(var(--timeline-aside-width, 0px) / -2); } :where(html[data-message-density="compact"]) .composerDock { - width: calc(100% - 2 * var(--space-4)); + width: calc(100% - var(--timeline-aside-width, 0px) - 2 * var(--space-4)); } @media (max-width: 40.625rem) { .composerDock { @@ -1146,6 +1161,10 @@ html[data-keyboard-navigation] .attachmentImage:focus-visible { scrollbar-gutter: stable; scrollbar-width: thin; } +/* Beside a docked workspace aside, as in .feed. */ +[data-aside-docked] .threadHistory { + padding-inline-end: calc(var(--space-4) + var(--timeline-aside-width)); +} /* Compact gives conversations the window's full width, as list layouts do. */ :where(html[data-message-density="compact"]) :is(.feed, .threadHistory) { --timeline-measure: 100%; diff --git a/src/features/messages/QueuedFollowUps.module.css b/src/features/messages/QueuedFollowUps.module.css index ca9a095a21..6c2db7fc6a 100644 --- a/src/features/messages/QueuedFollowUps.module.css +++ b/src/features/messages/QueuedFollowUps.module.css @@ -1,8 +1,14 @@ .queue { box-sizing: border-box; flex-shrink: 0; - width: min(calc(100% - 2 * var(--space-4)), var(--buzz-message-width, 52rem)); + position: relative; + width: min( + calc(100% - var(--timeline-aside-width, 0px) - 2 * var(--space-4)), + var(--buzz-message-width, 52rem) + ); margin: 0 auto var(--space-2); + /* Beside a docked workspace aside, as the composer is. */ + inset-inline-start: calc(var(--timeline-aside-width, 0px) / -2); color: var(--text-secondary); } .list { diff --git a/src/features/messages/TypingIndicator.module.css b/src/features/messages/TypingIndicator.module.css index bced0f1e8f..37b4a40e44 100644 --- a/src/features/messages/TypingIndicator.module.css +++ b/src/features/messages/TypingIndicator.module.css @@ -90,9 +90,11 @@ .typing[data-audience="humans"] { position: absolute; inset-block-end: calc(100% + var(--space-half)); - inset-inline: var(--space-4); + /* Beside a docked workspace aside, as the composer is. */ + inset-inline: var(--space-4) + calc(var(--space-4) + var(--timeline-aside-width, 0px)); inline-size: min( - calc(100% - 2 * var(--space-4)), + calc(100% - var(--timeline-aside-width, 0px) - 2 * var(--space-4)), var(--buzz-message-width, 52rem) ); margin-inline: auto; @@ -102,5 +104,10 @@ } /* Matches the composer, which spans a compact list's full width. */ :where(html[data-message-density="compact"]) .typing[data-audience="humans"] { - inline-size: calc(100% - 2 * var(--space-4)); + inline-size: calc( + 100% - + var(--timeline-aside-width, 0px) - + 2 * + var(--space-4) + ); } diff --git a/tests/browser/aside-fixture.tsx b/tests/browser/aside-fixture.tsx index b92dc3fe99..72d4b3715b 100644 --- a/tests/browser/aside-fixture.tsx +++ b/tests/browser/aside-fixture.tsx @@ -4,21 +4,31 @@ import { PopoverTrigger, } from "../../src/shared/design-system/ui/Popover"; -// A dashboard shaped like a plugin's Plan tile. It fills the box the host -// gives it and scrolls its own content; its Details popover escapes the box, -// over the history. `short` fits in a window, `tall` is taller than one. +// A dashboard shaped like a plugin's Plan tile. It draws its own card, sizes +// to it in the box the host gives it, and scrolls its own content past the +// box's height; its Details popover escapes the box, over the history. +// `short` fits in a window, `tall` is taller than one. const STEP = "Check the rollout dashboard, confirm error rates stay flat, then post the summary."; export type AsideSize = "short" | "tall"; export function AsideWidget({ size }: { size: AsideSize }) { - const steps = size === "tall" ? 28 : 5; + const steps = size === "tall" ? 28 : 2; return (

Plan · {steps} steps{" "} diff --git a/tests/browser/plugin-fixtures.tsx b/tests/browser/plugin-fixtures.tsx index 1f6ad4df99..a610687bcf 100644 --- a/tests/browser/plugin-fixtures.tsx +++ b/tests/browser/plugin-fixtures.tsx @@ -511,6 +511,7 @@ export const fixturePlugins: readonly BundledPlugin[] = [ const [shownAside, setShownAside] = useState(); // The page's own control drives the aside, as the contract asks. const [asideOpen, setAsideOpen] = useState(true); + const [asideFloating, setAsideFloating] = useState(); useEffect(() => { window.fixtureAside = setShownAside; return () => { @@ -569,6 +570,7 @@ export const fixturePlugins: readonly BundledPlugin[] = [ + - - + present ? ( + + ) : undefined } width={undefined} open={open} - onOpenChange={(next) => { - onOpenChange?.(next); - setOpen(next); - }} + // As a plugin passes it, with its aside. + onOpenChange={ + present + ? (next) => { + onOpenChange?.(next); + setOpen(next); + } + : undefined + } onFloatingChange={onFloatingChange} >
History
+
@@ -193,3 +219,42 @@ it("a floating aside takes focus, covers reading, and closes alone on Escape or expect(plan()).not.toBeVisible(); expect(changes).toEqual([false, false, false]); }); + +it("narrowing under an open aside closes it without taking focus", () => { + render(); + const composer = screen.getByRole("button", { name: "Composer" }); + composer.focus(); + resize(800); + expect(plan()).not.toBeVisible(); + expect(composer).toHaveFocus(); +}); + +it("an aside that arrives in a narrow row starts closed", () => { + width = 800; + const changes: boolean[] = []; + render( changes.push(open)} />); + const composer = screen.getByRole("button", { name: "Composer" }); + composer.focus(); + fireEvent.click(screen.getByRole("button", { name: "Add plan" })); + expect(changes).toEqual([false]); + expect(plan()).not.toBeVisible(); +}); + +it("the aside's own controls and popovers take Escape first", () => { + width = 800; + render(); + fireEvent.click(screen.getByRole("button", { name: "Plan" })); + expect(plan()).toBeVisible(); + fireEvent.keyDown(screen.getByRole("textbox", { name: "Step name" }), { + key: "Escape", + }); + expect(plan()).toBeVisible(); + fireEvent.keyDown(screen.getByRole("button", { name: "Portaled" }), { + key: "Escape", + }); + expect(plan()).toBeVisible(); + fireEvent.keyDown(screen.getByRole("button", { name: "Step" }), { + key: "Escape", + }); + expect(plan()).not.toBeVisible(); +}); diff --git a/src/bundled/channels/WorkspaceRow.tsx b/src/bundled/channels/WorkspaceRow.tsx index 15aac5e08b..e4c383cf4a 100644 --- a/src/bundled/channels/WorkspaceRow.tsx +++ b/src/bundled/channels/WorkspaceRow.tsx @@ -6,6 +6,7 @@ import { useRef, useState, type CSSProperties, + type KeyboardEvent, type ReactNode, } from "react"; import type { WorkspaceAsideWidth } from "../../features/conversation/contracts"; @@ -84,7 +85,9 @@ export function WorkspaceRow({ }, []); // Narrowing to a floating aside closes it; widening again restores the - // docked state. An aside that first measures narrow narrows from docked. + // docked state. An aside that first measures narrow, or arrives in a narrow + // row, narrows from docked. + const placedDocked = aside == null || docked; const dockedOpen = useRef(open); const transition = useEffectEvent((docked: boolean) => { if (!docked) { @@ -94,10 +97,19 @@ export function WorkspaceRow({ }); const wasDocked = useRef(true); useLayoutEffect(() => { - if (wasDocked.current === docked) return; - wasDocked.current = docked; - transition(docked); - }, [docked]); + if (wasDocked.current === placedDocked) return; + wasDocked.current = placedDocked; + transition(placedDocked); + }, [placedDocked]); + + // Only a page opening the floating aside moves focus into it, not a row + // narrowing under an open aside it is about to close. + const wasOpen = useRef(open); + const opened = useRef(false); + useLayoutEffect(() => { + opened.current = open && !wasOpen.current; + wasOpen.current = open; + }); const measured = layout !== undefined; const reportFloating = useEffectEvent((floating: boolean) => @@ -153,34 +165,42 @@ export function WorkspaceRow({ }, [shown, floating]); // A nested surface: Escape and a press elsewhere in the row close only it. + const previous = useRef(null); useEffect(() => { const element = box.current; const container = row.current; if (!floating || !element || !container) return; - const previous = - document.activeElement instanceof HTMLElement - ? document.activeElement - : null; - element.focus({ preventScroll: true }); - const keydown = (event: KeyboardEvent) => { - if (event.key !== "Escape" || event.defaultPrevented) return; - event.preventDefault(); - event.stopPropagation(); - change(false); - previous?.focus({ preventScroll: true }); - }; + previous.current = null; + if (opened.current) { + previous.current = + document.activeElement instanceof HTMLElement + ? document.activeElement + : null; + element.focus({ preventScroll: true }); + } const pointerdown = (event: PointerEvent) => { const target = event.target as Node; if (container.contains(target) && !element.contains(target)) change(false); }; - element.addEventListener("keydown", keydown); document.addEventListener("pointerdown", pointerdown, true); - return () => { - element.removeEventListener("keydown", keydown); - document.removeEventListener("pointerdown", pointerdown, true); - }; + return () => document.removeEventListener("pointerdown", pointerdown, true); }, [floating]); + // After the aside's own controls, which may take Escape first; a portaled + // popover's Escape is its own. + const keydown = (event: KeyboardEvent) => { + if ( + event.key !== "Escape" || + event.defaultPrevented || + !event.currentTarget.contains(event.target as Node) + ) + return; + event.preventDefault(); + event.nativeEvent.stopPropagation(); + setInner(false); + onOpenChange?.(false); + previous.current?.focus({ preventScroll: true }); + }; // Stable, so opening the overlay doesn't rerender the readers. const covers = useCallback(() => { @@ -207,12 +227,14 @@ export function WorkspaceRow({ {children}

{aside != null && ( + // biome-ignore lint/a11y/noStaticElementInteractions: hears Escape from the aside's controls; the box takes no input of its own.