diff --git a/docs/plugin-authoring-guide.md b/docs/plugin-authoring-guide.md index 491dcff54c..45119fa279 100644 --- a/docs/plugin-authoring-guide.md +++ b/docs/plugin-authoring-guide.md @@ -112,6 +112,24 @@ 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 in a box of `asideWidth` (default 320) +over the history's end edge, left of its scrollbar. Docked, it runs from the +history's top to the reader's bottom, and 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, above the composer. 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. `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. ## Migration writes diff --git a/src/bundled/channels/Channels.module.css b/src/bundled/channels/Channels.module.css index 12a1dc21e9..9b8a937549 100644 --- a/src/bundled/channels/Channels.module.css +++ b/src/bundled/channels/Channels.module.css @@ -51,11 +51,49 @@ .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 page's aside, from the history's top over its end edge, beside its + scrollbar. Docked, it may run to the reader's bottom, beside the composer; + floating, it stops at the history's bottom, above the composer. It draws + nothing itself: its content draws its card, sizes to it, and scrolls itself + when taller. Only that content takes pointer input, so the wheel beside or + below it scrolls the history. */ +.workspaceAside { + position: absolute; + z-index: 1; + 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[data-workspace-aside="docked"] { + max-block-size: calc(100% - var(--aside-top, 0px)); +} +.workspaceAside > * { + min-block-size: 0; + pointer-events: auto; +} +.workspaceAside[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..3c2d05560f 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,57 @@ 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..4685173da2 --- /dev/null +++ b/src/bundled/channels/WorkspaceRow.test.tsx @@ -0,0 +1,260 @@ +// @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 { createPortal } from "react-dom"; +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, + onFloatingChange, + arrives = false, +}: { + onOpenChange?: (open: boolean) => void; + onFloatingChange?: (floating: boolean) => void; + /** The aside arrives after the row first measures. */ + arrives?: boolean; +}) { + const [open, setOpen] = useState(true); + const [present, setPresent] = useState(!arrives); + return ( + <> + + + + + { + if (event.key === "Escape") event.preventDefault(); + }} + /> + {createPortal( + , + document.body, + )} + + ) : undefined + } + width={undefined} + open={open} + // As a plugin passes it, with its aside. + onOpenChange={ + present + ? (next) => { + onOpenChange?.(next); + setOpen(next); + } + : undefined + } + onFloatingChange={onFloatingChange} + > +
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 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(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[] = []; + 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", + ); + 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" })); + 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[] = []; + const floats: boolean[] = []; + render( + changes.push(open)} + onFloatingChange={(floating) => floats.push(floating)} + />, + ); + expect(changes).toEqual([false]); + expect(floats).toEqual([true]); + 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]); +}); + +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 new file mode 100644 index 0000000000..b3aadb6c7b --- /dev/null +++ b/src/bundled/channels/WorkspaceRow.tsx @@ -0,0 +1,245 @@ +import { + useCallback, + useEffect, + useEffectEvent, + useLayoutEffect, + useRef, + useState, + type CSSProperties, + type KeyboardEvent, + 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; + onFloatingChange: ((floating: boolean) => void) | undefined; + children: ReactNode; +}; + +/** + * 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); + 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 shown = aside != null && open; + const floating = shown && !docked; + const asideWidth = layout?.width ?? width ?? DEFAULT_WIDTH; + + 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, 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) { + dockedOpen.current = open; + if (open) change(false); + } else if (open !== dockedOpen.current) change(dockedOpen.current); + }); + const wasDocked = useRef(true); + useLayoutEffect(() => { + 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) => + onFloatingChange?.(floating), + ); + useLayoutEffect(() => { + if (measured) reportFloating(!docked); + }, [measured, docked]); + + // The box starts at the history's top, beside its scrollbar; floating, it + // stops at the history's bottom, above 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(); + // biome-ignore lint/correctness/useExhaustiveDependencies: docking or floating changes what covers the rows, so reading wakes. + useLayoutEffect(() => { + const container = row.current; + 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({ + "--aside-top": `${history.top - outer.top}px`, + "--aside-height": `${history.height}px`, + "--aside-scrollbar": `${scroller.offsetWidth - scroller.clientWidth}px`, + } as CSSProperties); + readingPositioned(scroller); + }; + // 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. + const previous = useRef(null); + useEffect(() => { + const element = box.current; + const container = row.current; + if (!floating || !element || !container) return; + 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); + }; + document.addEventListener("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(() => { + const element = box.current; + return element?.dataset.workspaceAside === "floating" && !element.hidden + ? [element.getBoundingClientRect()] + : []; + }, []); + + return ( +
+
+ {children} +
+ {aside != null && ( + // biome-ignore lint/a11y/noStaticElementInteractions: hears Escape from the aside's controls; the box takes no input of its own. + + )} +
+ ); +} 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..822c289baf 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,28 @@ export type ConversationWorkspaceProps = { restHeight: number; content(state: { expanded: boolean; toggle(): void }): ReactNode; }; + /** 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, from the + * history's top to the reader's bottom; the history and composer keep to + * the width beside it. When the reader would get too narrow, the aside + * floats over the history instead, above the composer, 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; + /** 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; + /** 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/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..72d4b3715b --- /dev/null +++ b/tests/browser/aside-fixture.tsx @@ -0,0 +1,52 @@ +import { + PopoverPopup, + PopoverRoot, + PopoverTrigger, +} from "../../src/shared/design-system/ui/Popover"; + +// 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 : 2; + 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..a610687bcf 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,29 @@ 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); + const [asideFloating, setAsideFloating] = useState(); + 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 +566,16 @@ export const fixturePlugins: readonly BundledPlugin[] = [ > Jump retained transcript + {asideSize && ( + + )}
, + asideOpen, + onAsideOpenChange: setAsideOpen, + onAsideFloatingChange: setAsideFloating, + } + : {})} 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..24e06aeda1 --- /dev/null +++ b/tests/browser/workspace-aside.spec.mjs @@ -0,0 +1,461 @@ +// A workspace's aside sits over the history's end edge, left of its scrollbar. +// Docked, the history's content and the composer keep to the width beside it; +// when the reader is narrow, it floats over the history while open. +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: { + bottom: region.getBoundingClientRect().bottom, + 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 keeps the history and composer beside it", 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(at.list.right).toBeLessThanOrEqual(at.aside.left); + expect(at.composer.right).toBeLessThanOrEqual(at.aside.left + 1); + // The composer stays centered under the history's rows. 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); + // A tall plan runs from the history's top to the reader's bottom, beside + // the composer, and scrolls itself. + expect(Math.abs(at.aside.top - at.history.top)).toBeLessThanOrEqual(1); + expect(Math.abs(at.aside.bottom - at.reader.bottom)).toBeLessThanOrEqual(1); + expect(at.aside.bottom).toBeGreaterThan(at.composer.bottom); + expect(at.region.scrollHeight).toBeGreaterThan(at.region.clientHeight); + + // Wheeling over the plan 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); + + // Scrolled to its end, the plan's card ends inside the box and the window. + await plan(page).evaluate((element) => { + element.scrollTop = element.scrollHeight; + }); + const end = await layout(page); + expect(end.region.scrollTop).toBeGreaterThanOrEqual( + end.region.scrollHeight - end.region.clientHeight - 1, + ); + expect(end.region.bottom).toBeLessThan(end.aside.bottom); + expect(end.aside.bottom).toBeLessThanOrEqual(page.viewportSize().height); + await expect(plan(page).getByText("End of plan")).toBeInViewport(); + + // The page's control hides it, and the rows take 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.querySelector("ol").getBoundingClientRect().right, + ), + ) + .toBeGreaterThan(at.aside.left + 100); +}); + +test("the history's scrollbar stays at the reader's end, right of a docked aside", { + tag: "@classic-scrollbars", +}, async ({ page, app }) => { + test.skip( + process.platform !== "linux" && !process.env.BUZZ_CLASSIC_SCROLLBARS, + "Set BUZZ_CLASSIC_SCROLLBARS=1 on a Mac whose scrollbars take space", + ); + await open(page, app); + await openAside(page); + const region = history(page); + await settle(page, region); + const at = await layout(page); + // The history spans the reader, and its scrollport runs under the aside. + expect(Math.abs(at.history.right - at.reader.right)).toBeLessThanOrEqual(1); + expect( + Math.abs(at.aside.right - (at.history.right - at.scrollbar)), + ).toBeLessThanOrEqual(1); + // The scrollbar beside the aside belongs to the history. + expect(at.scrollbar).toBeGreaterThan(0); + expect( + await region.evaluate( + (element, { x, y }) => element === document.elementFromPoint(x, y), + { + x: at.history.right - at.scrollbar / 2, + y: (at.aside.top + at.aside.bottom) / 2, + }, + ), + ).toBe(true); +}); + +test("the wheel beside or below a short docked plan scrolls the history", async ({ + page, + app, +}) => { + await open(page, app); + await openAside(page, { aside: "short" }); + const region = history(page); + await settle(page, region); + const at = await layout(page); + const card = await plan(page).boundingBox(); + // The box sizes to the plan's card, which leaves the column below it empty. + expect(at.aside.bottom).toBeLessThan(at.history.bottom - 100); + for (const point of [ + // Below the card. + { x: card.x + card.width / 2, y: at.aside.bottom + 60 }, + // In the card's margin, inside the aside's box. + { x: at.aside.left + 3, y: card.y + card.height / 2 }, + ]) { + const before = await region.evaluate((element) => element.scrollTop); + await page.mouse.move(point.x, point.y); + for (let i = 0; i < 3; i++) await page.mouse.wheel(0, -120); + await expect + .poll(() => region.evaluate((element) => element.scrollTop)) + .toBeLessThan(before - 100); + } +}); + +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"); + // The page hears that the aside floats. + await expect(show).toHaveAttribute("data-aside-floating", "true"); + 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).toBeLessThanOrEqual(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); + + // Scrolled to its end, the plan's card ends inside the box and the window. + await plan(page).evaluate((element) => { + element.scrollTop = element.scrollHeight; + }); + const end = await layout(page); + expect(end.region.scrollTop).toBeGreaterThanOrEqual( + end.region.scrollHeight - end.region.clientHeight - 1, + ); + expect(end.region.bottom).toBeLessThan(end.aside.bottom); + expect(end.aside.bottom).toBeLessThanOrEqual(page.viewportSize().height); + await expect(plan(page).getByText("End of plan")).toBeInViewport(); + + // 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" })).toHaveAttribute( + "data-aside-floating", + "false", + ); + 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 over the thread's end edge", 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 at = await thread.evaluate((element) => { + const box = (node) => node.getBoundingClientRect().toJSON(); + const widget = document.querySelector("[data-workspace-aside]"); + return { + thread: box(element), + scrollbar: element.offsetWidth - element.clientWidth, + rows: box(element.querySelector("[data-thread-rows]")), + composer: box( + widget.previousElementSibling.querySelector( + '[contenteditable="true"]', + ), + ), + aside: box(widget), + reader: box(widget.previousElementSibling), + }; + }); + expect(at.aside.width).toBe(320); + expect(at.rows.right).toBeLessThanOrEqual(at.aside.left); + expect(Math.abs(at.thread.right - at.reader.right)).toBeLessThanOrEqual(1); + expect( + Math.abs(at.aside.right - (at.thread.right - at.scrollbar)), + ).toBeLessThanOrEqual(1); + expect(at.aside.top).toBeGreaterThanOrEqual(at.thread.top - 1); + expect(at.composer.right).toBeLessThanOrEqual(at.aside.left + 1); + expect(at.aside.bottom).toBeLessThanOrEqual(at.reader.bottom + 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 }); + }); +});