fix(ui): hide mobile task composer and bottom nav while reading back

Scrolling the task chat thread away from the latest message now slides
the composer and the bottom navigation out of view. Scrolling back toward
the latest message brings them back. An open keyboard keeps the composer
on screen. Adds unit tests and Storybook stories.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
cryppadottaandClaude Opus 5.5 committed 2026-12-04 02:45:52 +00:00
1 parent 3f882fc589
commit 012311e8ec
8 files changed
+436 -22

No files matched your search

+1
View File
@@ -548,6 +548,7 @@ export function Layout() {
<main
id="main-content"
ref={mainContentRef}
data-mobile-nav={isMobile ? (mobileNavVisible ? "visible" : "hidden") : undefined}
tabIndex={-1}
// Publish the pinned-composer bottom offset to descendants
// (PAP-495): while the auto-hiding mobile nav is on screen, raise
+1
View File
@@ -622,6 +622,7 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
<main
id="main-content"
ref={mainContentRef}
data-mobile-nav={isMobile ? (mobileNavVisible ? "visible" : "hidden") : undefined}
tabIndex={-1}
// Publish the pinned-composer bottom offset to descendants
// (PAP-495): while the auto-hiding mobile nav is on screen, raise
@@ -16,7 +16,11 @@ export function TaskChatComposerDock({ children, mobile, streamlined, concealed
if (placeholder) return;
const dock = dockRef.current;
const thread = dock?.closest<HTMLElement>('[data-testid="task-chat-thread"]');
if (!dock || !thread || !thread.closest(".coordinator-workspace")) return;
if (!dock || !thread) return;
const coordinator = thread.closest(".coordinator-workspace") !== null;
// Coordinator overlays the dock on the thread; mobile collapses it while
// the auto-hiding chrome is tucked away. Both need its measured height.
if (!coordinator && !mobile) return;
const forwardGapWheel = (event: WheelEvent) => {
if (event.target !== dock || event.ctrlKey || event.defaultPrevented) return;
const scroller = thread.querySelector<HTMLElement>('[data-testid="task-chat-scroller"]');
@@ -35,7 +39,7 @@ export function TaskChatComposerDock({ children, mobile, streamlined, concealed
: deltaMode === WheelEvent.DOM_DELTA_PAGE ? scroller.clientWidth : 1;
scroller.scrollBy({ left: deltaX * horizontalUnit, top: deltaY * verticalUnit, behavior: "instant" });
};
dock.addEventListener("wheel", forwardGapWheel, { passive: false });
if (coordinator) dock.addEventListener("wheel", forwardGapWheel, { passive: false });
const measure = () => thread.style.setProperty("--task-composer-dock-height", `${dock.getBoundingClientRect().height}px`);
measure();
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
@@ -45,7 +49,7 @@ export function TaskChatComposerDock({ children, mobile, streamlined, concealed
observer?.disconnect();
thread.style.removeProperty("--task-composer-dock-height");
};
}, [placeholder]);
}, [placeholder, mobile]);
return <div
ref={dockRef}
data-testid={placeholder ? "task-chat-loading-composer" : "task-chat-composer-dock"}
@@ -371,6 +371,9 @@ export function TaskMessageScroller({ children, contentKey, className, scrolling
className,
)}
data-testid="task-chat-scroller"
// Mobile: reading away from the latest message tucks the bottom nav
// and composer away; heading back toward it brings them back.
data-mobile-chrome-scroll="bottom"
>
{scrollingHistory ? <>
{scrollingHistory && (scrollingHistory.hasMore || scrollingHistory.loading || scrollingHistory.error) ? (
@@ -0,0 +1,148 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useMobileNavVisibility } from "./useMobileNavVisibility";
let visible: boolean | null = null;
function Host({ enabled = true }: { enabled?: boolean }) {
visible = useMobileNavVisibility(enabled, "/PAP/issues/PAP-1");
return null;
}
let root: Root;
let container: HTMLDivElement;
let frames: FrameRequestCallback[] = [];
let thread: HTMLDivElement;
let geometry: { scrollHeight: number; clientHeight: number; bottom: number };
function flushFrames() {
const pending = frames;
frames = [];
act(() => pending.forEach((callback) => callback(0)));
}
/** Scroll the thread to `fromBottom` CSS pixels above its latest message. */
function scrollThread(fromBottom: number) {
thread.scrollTop = geometry.scrollHeight - geometry.clientHeight - fromBottom;
thread.dispatchEvent(new Event("scroll"));
flushFrames();
}
/** Grow or shrink the thread viewport at its bottom edge, as the dock does. */
function resizeThread(clientHeight: number) {
geometry.bottom += clientHeight - geometry.clientHeight;
geometry.clientHeight = clientHeight;
}
beforeEach(() => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => frames.push(callback));
vi.stubGlobal("cancelAnimationFrame", () => {});
const tokens = document.documentElement.style;
tokens.setProperty("--mobile-nav-scroll-top-zone", "24px");
tokens.setProperty("--mobile-nav-scroll-hide-distance", "32px");
tokens.setProperty("--mobile-nav-scroll-show-distance", "16px");
geometry = { scrollHeight: 4000, clientHeight: 500, bottom: 560 };
thread = document.createElement("div");
thread.setAttribute("data-mobile-chrome-scroll", "bottom");
Object.defineProperty(thread, "scrollHeight", { configurable: true, get: () => geometry.scrollHeight });
let scrollTop = 0;
Object.defineProperty(thread, "scrollTop", { configurable: true, get: () => scrollTop, set: (value: number) => { scrollTop = value; } });
Object.defineProperty(thread, "clientHeight", { configurable: true, get: () => geometry.clientHeight });
thread.getBoundingClientRect = () => ({ bottom: geometry.bottom, top: geometry.bottom - geometry.clientHeight } as DOMRect);
document.body.append(thread);
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
thread.remove();
document.documentElement.removeAttribute("style");
document.body.querySelectorAll(".paperclip-app-shell").forEach((node) => node.remove());
frames = [];
visible = null;
vi.unstubAllGlobals();
});
describe("useMobileNavVisibility with a bottom-anchored task thread", () => {
it("tucks the chrome away when reading back from the latest message and restores it heading back", () => {
act(() => root.render(<Host />));
scrollThread(0);
expect(visible).toBe(true);
// Small drags near the latest message keep the composer reachable.
scrollThread(20);
scrollThread(50);
expect(visible).toBe(true);
scrollThread(60);
expect(visible).toBe(false);
// Keep reading older messages: the chrome stays out of the way.
scrollThread(600);
expect(visible).toBe(false);
// A deliberate drag back toward the latest message reveals it.
scrollThread(590);
expect(visible).toBe(false);
scrollThread(580);
expect(visible).toBe(true);
});
it("returns the chrome when the reader reaches the latest message", () => {
act(() => root.render(<Host />));
scrollThread(0);
scrollThread(400);
expect(visible).toBe(false);
scrollThread(300);
scrollThread(320);
scrollThread(10);
expect(visible).toBe(true);
});
it("does not bounce back when tucking the composer away grows the thread viewport", () => {
act(() => root.render(<Host />));
scrollThread(0);
scrollThread(80);
expect(visible).toBe(false);
// The dock and nav collapse: the viewport grows 150px at its bottom while
// the reading position holds, so the newest text slides into view.
const scrollTop = thread.scrollTop;
resizeThread(650);
thread.scrollTop = scrollTop;
thread.dispatchEvent(new Event("scroll"));
flushFrames();
expect(visible).toBe(false);
});
it("keeps the composer on screen while the keyboard is open", () => {
const shell = document.createElement("div");
shell.className = "paperclip-app-shell";
shell.dataset.keyboardOpen = "true";
document.body.append(shell);
act(() => root.render(<Host />));
scrollThread(0);
scrollThread(400);
expect(visible).toBe(true);
});
it("ignores threads that did not opt in and stays visible on desktop", () => {
thread.removeAttribute("data-mobile-chrome-scroll");
act(() => root.render(<Host />));
scrollThread(0);
scrollThread(400);
expect(visible).toBe(true);
thread.setAttribute("data-mobile-chrome-scroll", "bottom");
act(() => root.render(<Host enabled={false} />));
scrollThread(0);
scrollThread(400);
expect(visible).toBe(true);
});
});
+87 -19
View File
@@ -1,6 +1,21 @@
import { useEffect, useState } from "react";
import { MobileNavScrollTracker } from "../lib/mobile-nav-scroll";
/**
* Opt-in marker for a nested scroll container that should drive the
* auto-hiding mobile chrome (bottom nav and pinned composer). The value is the
* container's resting edge: `"bottom"` for a chat thread that rests at its
* latest message, so moving away from the bottom hides the chrome and moving
* back toward it reveals the chrome again.
*/
export const MOBILE_CHROME_SCROLL_ATTRIBUTE = "data-mobile-chrome-scroll";
function bottomAnchoredScroller(target: EventTarget | null): HTMLElement | null {
return target instanceof HTMLElement && target.getAttribute(MOBILE_CHROME_SCROLL_ATTRIBUTE) === "bottom"
? target
: null;
}
export function useMobileNavVisibility(enabled: boolean, pathname: string): boolean {
const [visible, setVisible] = useState(true);
@@ -10,35 +25,88 @@ export function useMobileNavVisibility(enabled: boolean, pathname: string): bool
const styles = getComputedStyle(document.documentElement);
const distance = (token: string) => Number.parseFloat(styles.getPropertyValue(token)) || 0;
const scrollBounds = () => {
const options = {
topZone: distance("--mobile-nav-scroll-top-zone"),
hideDistance: distance("--mobile-nav-scroll-hide-distance"),
showDistance: distance("--mobile-nav-scroll-show-distance"),
};
const documentBounds = () => {
const root = document.scrollingElement ?? document.documentElement;
return {
top: window.scrollY || root.scrollTop || 0,
max: Math.max(0, root.scrollHeight - root.clientHeight),
};
};
const initial = scrollBounds();
const tracker = new MobileNavScrollTracker({
topZone: distance("--mobile-nav-scroll-top-zone"),
hideDistance: distance("--mobile-nav-scroll-hide-distance"),
showDistance: distance("--mobile-nav-scroll-show-distance"),
}, initial.top, initial.max);
let frame: number | null = null;
const onScroll = () => {
if (frame !== null) return;
frame = requestAnimationFrame(() => {
frame = null;
const { top, max } = scrollBounds();
const previous = tracker.visible;
const next = tracker.update(top, max);
if (next !== previous) setVisible(next);
let current = true;
// A bottom-anchored thread is measured from its latest message, so the
// tracker's resting zone is the bottom of the thread instead of the top.
// Tucking the composer away grows the thread viewport; measuring against
// the bottom edge it had while the chrome was visible keeps that growth
// from reading as a return to the latest message (which would flicker).
const restingBottoms = new WeakMap<HTMLElement, number>();
const threadBounds = (scroller: HTMLElement) => {
const bottom = scroller.getBoundingClientRect().bottom;
if (current || !restingBottoms.has(scroller)) restingBottoms.set(scroller, bottom);
const restingHeight = scroller.clientHeight - (bottom - restingBottoms.get(scroller)!);
const scrollTop = Math.max(0, Math.min(scroller.scrollTop, scroller.scrollHeight - scroller.clientHeight));
const max = Math.max(0, scroller.scrollHeight - restingHeight);
return { top: max - scrollTop, max };
};
const initial = documentBounds();
const documentTracker = new MobileNavScrollTracker(options, initial.top, initial.max);
const threadTrackers = new WeakMap<HTMLElement, MobileNavScrollTracker>();
// Typing in the composer keeps it on screen; the keyboard resize is not a swipe.
const keyboardOpen = () => document.querySelector('.paperclip-app-shell[data-keyboard-open="true"]') !== null;
const apply = (next: boolean) => {
if (next === current) return;
current = next;
setVisible(next);
};
let documentFrame: number | null = null;
const onDocumentScroll = () => {
if (documentFrame !== null) return;
documentFrame = requestAnimationFrame(() => {
documentFrame = null;
const { top, max } = documentBounds();
apply(documentTracker.update(top, max));
});
};
window.addEventListener("scroll", onScroll, { passive: true });
let threadFrame: number | null = null;
let pendingThread: HTMLElement | null = null;
const onNestedScroll = (event: Event) => {
const scroller = bottomAnchoredScroller(event.target);
if (!scroller) return;
pendingThread = scroller;
if (threadFrame !== null) return;
threadFrame = requestAnimationFrame(() => {
threadFrame = null;
const target = pendingThread;
pendingThread = null;
if (!target?.isConnected) return;
const { top, max } = threadBounds(target);
let tracker = threadTrackers.get(target);
if (!tracker) {
// The first event only establishes a baseline; it is never a swipe.
tracker = new MobileNavScrollTracker(options, top, max);
threadTrackers.set(target, tracker);
return;
}
const next = tracker.update(top, max);
apply(keyboardOpen() ? true : next);
});
};
window.addEventListener("scroll", onDocumentScroll, { passive: true });
// Element scroll events do not bubble, so observe nested threads in capture.
document.addEventListener("scroll", onNestedScroll, { passive: true, capture: true });
return () => {
window.removeEventListener("scroll", onScroll);
if (frame !== null) cancelAnimationFrame(frame);
window.removeEventListener("scroll", onDocumentScroll);
document.removeEventListener("scroll", onNestedScroll, { capture: true });
if (documentFrame !== null) cancelAnimationFrame(documentFrame);
if (threadFrame !== null) cancelAnimationFrame(threadFrame);
};
}, [enabled, pathname]);
+31
View File
@@ -1058,6 +1058,37 @@ html:has(.paperclip-app-shell[data-keyboard-open="true"] [data-classic-task-shel
padding-bottom: 0;
}
/* Reading away from the latest message tucks the composer away with
the auto-hiding bottom nav so the thread takes the full height; heading back
toward the latest message brings both back. The shell clips the dock as it
slides below the main column. Typing (keyboard open) never collapses it. */
.paperclip-app-shell[data-mobile="true"]:not([data-keyboard-open="true"]):has([data-task-chat-shell]) #main-content {
transition: padding-bottom var(--mobile-nav-motion-duration, var(--motion-mobile-nav-enter)) var(--mobile-nav-motion-ease, var(--motion-ease-out-expo));
}
.paperclip-app-shell[data-mobile="true"]:not([data-keyboard-open="true"]) #main-content [data-task-chat-shell] [data-testid="task-chat-composer-dock"] {
transition:
margin-bottom var(--mobile-nav-motion-duration, var(--motion-mobile-nav-enter)) var(--mobile-nav-motion-ease, var(--motion-ease-out-expo)),
visibility 0s;
}
.paperclip-app-shell[data-mobile="true"]:not([data-keyboard-open="true"]):has([data-task-chat-shell]) #main-content[data-mobile-nav="hidden"] {
padding-bottom: 0;
}
.paperclip-app-shell[data-mobile="true"]:not([data-keyboard-open="true"]) #main-content[data-mobile-nav="hidden"] [data-task-chat-shell] [data-testid="task-chat-composer-dock"] {
margin-bottom: calc(-1 * var(--task-composer-dock-height, 0px));
visibility: hidden;
pointer-events: none;
transition:
margin-bottom var(--mobile-nav-motion-duration, var(--motion-mobile-nav-exit)) var(--mobile-nav-motion-ease, var(--motion-ease-standard)),
visibility 0s linear var(--mobile-nav-motion-duration, var(--motion-mobile-nav-exit));
}
.paperclip-app-shell[data-mobile="true"]:not([data-keyboard-open="true"]) #main-content[data-mobile-nav="hidden"] [data-task-chat-shell] [data-testid="task-chat-scroller"] ~ button {
bottom: calc(var(--sz-safe-bottom) + var(--spacing) * 3);
}
@media (prefers-reduced-motion: reduce) {
:root {
--motion-mobile-nav-enter: 0ms;
@@ -0,0 +1,158 @@
import type { CSSProperties } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { expect, waitFor } from "storybook/test";
import { MobileBottomNav } from "@/components/MobileBottomNav";
import { TaskChatComposer } from "@/components/task-chat/TaskChatComposer";
import { TaskChatComposerDock } from "@/components/task-chat/TaskChatComposerDock";
import { TaskChatThreadView } from "@/components/task-chat/TaskChatThreadView";
import { useMobileNavVisibility } from "@/hooks/useMobileNavVisibility";
import { useMobileVisualViewport } from "@/hooks/useMobileVisualViewport";
const paragraphs = (count: number, topic: string) =>
Array.from({ length: count }, (_, index) =>
`${topic} ${index + 1}: I checked this section against the spec, noted the differences, and recorded what still needs a decision.`,
).join("\n\n");
const items = [
{ id: "ask-1", kind: "message" as const, author: "human" as const, text: "Audit the onboarding flow and tell me what is slowing people down." },
{ id: "reply-1", kind: "message" as const, author: "agent" as const, authorName: "Researcher", text: paragraphs(10, "Finding") },
{ id: "ask-2", kind: "message" as const, author: "human" as const, text: "Which of these should we fix first?" },
{ id: "reply-2", kind: "message" as const, author: "agent" as const, authorName: "Researcher", text: paragraphs(8, "Priority") },
{ id: "ask-3", kind: "message" as const, author: "human" as const, text: "Great — draft the plan for the top three." },
{ id: "reply-3", kind: "message" as const, author: "agent" as const, authorName: "Researcher", text: paragraphs(6, "Step") },
];
/**
* The production mobile task page frame: the Layout's main column publishes
* the auto-hiding chrome state exactly as `Layout.tsx` does, and the real
* thread scroller, composer dock, and bottom navigation respond to it.
*/
function MobileChromeAutoHide() {
const viewportRef = useMobileVisualViewport(true);
const navVisible = useMobileNavVisibility(true, "/ONB/issues/ONB-12");
return <div ref={viewportRef} data-mobile="true" className="paperclip-app-shell min-h-dvh overflow-x-clip bg-background text-foreground">
<div className="app-main-row min-h-0 flex-1 w-full">
<div className="app-content-column flex w-full min-w-0 flex-col">
<header className="app-breadcrumb sticky top-0 z-20 flex h-12 shrink-0 items-center bg-background/95 px-4 text-sm font-medium backdrop-blur">
ONB-12 · Onboarding audit
</header>
<div className="app-content-row block">
<main
id="main-content"
data-mobile-nav={navVisible ? "visible" : "hidden"}
style={{
"--tc-composer-bottom": navVisible ? "var(--tc-composer-visible-nav-offset)" : "var(--tc-composer-hidden-nav-offset)",
"--mobile-nav-motion-duration": navVisible ? "var(--motion-mobile-nav-enter)" : "var(--motion-mobile-nav-exit)",
"--mobile-nav-motion-ease": navVisible ? "var(--motion-ease-out-expo)" : "var(--motion-ease-standard)",
} as CSSProperties}
className="flex-1 overflow-visible p-4 pb-(--tc-composer-visible-nav-offset) outline-none"
>
<div data-task-chat-shell="" className="-mx-4 flex h-full min-h-0 w-full flex-1 flex-col">
<div data-testid="task-chat-thread" className="relative flex min-h-0 flex-1 flex-col">
<TaskChatThreadView items={items} />
<TaskChatComposerDock mobile streamlined={false}>
<TaskChatComposer mobile workMode="standard" onAdd={async () => {}} />
</TaskChatComposerDock>
</div>
</div>
</main>
</div>
</div>
</div>
<MobileBottomNav visible={navVisible} />
</div>;
}
function scroller(canvasElement: HTMLElement) {
const element = canvasElement.ownerDocument.querySelector<HTMLElement>('[data-testid="task-chat-scroller"]');
if (!element) throw new Error("Task thread scroller is missing");
return element;
}
/** Scroll in small steps, like a finger drag, so the tracker sees deliberate movement. */
async function dragThread(element: HTMLElement, by: number) {
const step = Math.sign(by) * 8;
for (let moved = 0; Math.abs(moved) < Math.abs(by); moved += step) {
element.scrollTop += step;
await new Promise((resolve) => requestAnimationFrame(resolve));
}
}
const chromeState = (canvasElement: HTMLElement) => {
const doc = canvasElement.ownerDocument;
return {
nav: doc.querySelector(".mobile-bottom-nav")?.getAttribute("data-visible"),
main: doc.getElementById("main-content")?.getAttribute("data-mobile-nav"),
dockVisibility: getComputedStyle(doc.querySelector('[data-testid="task-chat-composer-dock"]')!).visibility,
};
};
async function settleAtLatest(canvasElement: HTMLElement) {
const element = scroller(canvasElement);
await waitFor(() => expect(element.scrollHeight).toBeGreaterThan(element.clientHeight * 2));
element.scrollTop = element.scrollHeight;
await new Promise((resolve) => requestAnimationFrame(resolve));
return element;
}
const meta = {
id: "task-chat-mobile-chrome-autohide",
title: "Tasks and conversations/Task creation and lifecycle/Task chat/Mobile chrome auto-hide",
component: MobileChromeAutoHide,
parameters: {
layout: "fullscreen",
docs: { description: { component: "On a phone, the task page rests at the latest message with the composer and bottom navigation on screen. Drag back through the conversation and both slide away so the thread uses the full height. Drag back toward the latest message, or reach it, and both return. Typing with the keyboard open never hides the composer. Reduced motion switches instantly." } },
paperclip: {
"capabilities": [
"tasks/discussion",
],
"implementation": "production",
"boundary": "fixtures",
"notes": "Production thread scroller, composer dock, bottom navigation, and useMobileNavVisibility in the Layout's mobile task-page frame. Static fixture messages; no agent or provider calls. Physical iPhone touch acceptance is still required.",
},
},
globals: { theme: "light", viewport: { value: "mobile", isRotated: false } },
} satisfies Meta<typeof MobileChromeAutoHide>;
export default meta;
type Story = StoryObj<typeof meta>;
/** Interactive: start at the latest message and drag the thread yourself. */
export const Interactive: Story = {
name: "01 · Drag the thread",
play: async ({ canvasElement }) => {
await settleAtLatest(canvasElement);
await waitFor(() => expect(chromeState(canvasElement).main).toBe("visible"));
},
};
/** Reading back through the thread tucks the composer and navigation away. */
export const ReadingBack: Story = {
name: "02 · Reading back hides composer and nav",
play: async ({ canvasElement }) => {
const element = await settleAtLatest(canvasElement);
await dragThread(element, -240);
await waitFor(() => {
const state = chromeState(canvasElement);
expect(state.main).toBe("hidden");
expect(state.nav).toBe("false");
expect(state.dockVisibility).toBe("hidden");
});
},
};
/** Heading back toward the latest message brings both back. */
export const HeadingBack: Story = {
name: "03 · Heading back restores them",
play: async ({ canvasElement }) => {
const element = await settleAtLatest(canvasElement);
await dragThread(element, -240);
await waitFor(() => expect(chromeState(canvasElement).main).toBe("hidden"));
await dragThread(element, 40);
await waitFor(() => {
const state = chromeState(canvasElement);
expect(state.main).toBe("visible");
expect(state.nav).toBe("true");
expect(state.dockVisibility).toBe("visible");
});
},
};