Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(reading): converge the mobile header and dock the selection panel (#1734)

evan188199-techa5979981349c
diff --git a/web/components/reading/AnnotationPopover.tsx b/web/components/reading/AnnotationPopover.tsx
index 54a1b4bd1..cfc71ef2a 100644
--- a/web/components/reading/AnnotationPopover.tsx
+++ b/web/components/reading/AnnotationPopover.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import type { PointerEvent as ReactPointerEvent } from "react";
import {
BookmarkPlus,
Highlighter,
@@ -11,6 +12,7 @@ import {
} from "lucide-react";
import { useTranslation } from "react-i18next";
import Tooltip from "@/shared/ui/Tooltip";
+import { useDevice } from "@/hooks/useDevice";
import {
ANNOTATION_COLORS,
ANNOTATION_SWATCH,
@@ -46,13 +48,24 @@ export interface PopoverAiAction {
/** Chips that fit on the row before the rest go behind ⋯. */
const INLINE_AI_ACTIONS = 3;
+/** How far the sheet must be pulled down before the drag counts as "close". */
+const DRAG_CLOSE_THRESHOLD = 48;
+
/**
* Toolbar that appears over a selection.
*
- * Positioned in fixed coordinates and then clamped to the window after mount, so
- * a selection near the top or right edge still shows the whole toolbar instead of
- * being cut off — the failure people actually hit, since the interesting text is
- * often at the top of a page.
+ * On a desktop it is positioned in fixed coordinates and clamped to the
+ * window after mount, so a selection near the top or right edge still shows
+ * the whole toolbar instead of being cut off — the failure people actually
+ * hit, since the interesting text is often at the top of a page.
+ *
+ * Below 768px it is a bottom card instead (#916): the anchored popover that
+ * a long-press summons competes with the system selection menu for the same
+ * few pixels around the finger, so on a phone the panel drops to the bottom
+ * of the screen. The collapsed rows fit without scrolling; the expanded
+ * states — the note editor, the extra AI actions — get a capped, scrollable
+ * body; and a drag handle offers pull-down-to-dismiss next to Escape and
+ * tapping the page.
*
* Dismissal is on Escape and on pointerdown outside. Deliberately not on blur:
* clicking a colour swatch blurs the toolbar, and a blur-based dismissal would
@@ -70,6 +83,7 @@ export function AnnotationPopover({
aiActions,
}: AnnotationPopoverProps) {
const { t } = useTranslation();
+ const { isMobile } = useDevice();
const ref = useRef<HTMLDivElement | null>(null);
const [color, setColor] = useState<AnnotationColor>("yellow");
const [noteOpen, setNoteOpen] = useState(false);
@@ -79,7 +93,37 @@ export function AnnotationPopover({
const overflowAi = aiActions?.slice(INLINE_AI_ACTIONS) ?? [];
const [position, setPosition] = useState({ left: anchor.x, top: anchor.y });
+ // -- pull-down-to-dismiss ------------------------------------------------
+ //
+ // Only the handle drags; the body stays live so a scroll or a tap inside
+ // the card never reads as "close". The threshold is generous: an accidental
+ // nudge moves the sheet visually without closing it.
+ const dragRef = useRef<{ id: number; startY: number } | null>(null);
+ const [dragOffset, setDragOffset] = useState(0);
+ const onHandlePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
+ dragRef.current = { id: event.pointerId, startY: event.clientY };
+ try {
+ event.currentTarget.setPointerCapture(event.pointerId);
+ } catch {
+ // jsdom / rare engines without capture: element handlers still fire.
+ }
+ };
+ const onHandlePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
+ const drag = dragRef.current;
+ if (!drag || drag.id !== event.pointerId) return;
+ setDragOffset(Math.max(0, event.clientY - drag.startY));
+ };
+ const onHandlePointerEnd = (event: ReactPointerEvent<HTMLDivElement>) => {
+ const drag = dragRef.current;
+ if (!drag || drag.id !== event.pointerId) return;
+ dragRef.current = null;
+ const travelled = Math.max(0, event.clientY - drag.startY);
+ setDragOffset(0);
+ if (travelled >= DRAG_CLOSE_THRESHOLD) onDismiss();
+ };
+
useLayoutEffect(() => {
+ if (isMobile) return;
const element = ref.current;
if (!element) return;
const box = element.getBoundingClientRect();
@@ -95,7 +139,7 @@ export function AnnotationPopover({
left,
top: Math.min(top, window.innerHeight - box.height - margin),
});
- }, [anchor.x, anchor.y, noteOpen, overflowOpen]);
+ }, [anchor.x, anchor.y, isMobile, noteOpen, overflowOpen]);
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
@@ -117,14 +161,14 @@ export function AnnotationPopover({
};
}, [onDismiss]);
- return (
- <div
- ref={ref}
- role="dialog"
- aria-label={t("Annotate selection")}
- style={{ left: position.left, top: position.top }}
- className="dt-reader-popover fixed z-[70] w-max max-w-[min(360px,92vw)] rounded-xl border border-[var(--border)] bg-[var(--popover)] p-1.5 shadow-[0_10px_30px_-12px_rgba(0,0,0,0.35)]"
- >
+ // The rows are shared by both presentations; only the frame they sit in
+ // differs. `expanded` is what makes the body long: the note editor and the
+ // overflow action list are the states whose content can outgrow a thumb's
+ // reach, so they are the ones that switch the body to capped-and-scrollable.
+ const expanded = noteOpen || overflowOpen;
+
+ const body = (
+ <>
<div className="flex items-center gap-1">
<div className="flex items-center gap-0.5 pr-1">
{ANNOTATION_COLORS.map((swatch) => (
@@ -254,6 +298,52 @@ export function AnnotationPopover({
</div>
</div>
)}
+ </>
+ );
+
+ if (isMobile) {
+ return (
+ <div
+ ref={ref}
+ role="dialog"
+ aria-label={t("Annotate selection")}
+ style={{ transform: dragOffset ? `translateY(${dragOffset}px)` : undefined }}
+ className="dt-reader-sheet fixed inset-x-0 bottom-0 z-[70] rounded-t-2xl border-t border-[var(--border)] bg-[var(--popover)] pb-[calc(env(safe-area-inset-bottom)+10px)] shadow-[0_-12px_40px_-16px_rgba(0,0,0,0.45)]"
+ >
+ <div
+ data-testid="sheet-handle"
+ aria-hidden
+ onPointerDown={onHandlePointerDown}
+ onPointerMove={onHandlePointerMove}
+ onPointerUp={onHandlePointerEnd}
+ onPointerCancel={onHandlePointerEnd}
+ className="flex cursor-grab touch-none justify-center pb-0.5 pt-2"
+ >
+ <span className="h-1.5 w-10 rounded-full bg-[var(--muted-foreground)]/40" />
+ </div>
+ <div
+ data-scroll={expanded ? "long" : "short"}
+ className={`px-2 ${
+ expanded
+ ? "max-h-[60dvh] overflow-y-auto overscroll-contain"
+ : ""
+ }`}
+ >
+ {body}
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div
+ ref={ref}
+ role="dialog"
+ aria-label={t("Annotate selection")}
+ style={{ left: position.left, top: position.top }}
+ className="dt-reader-popover fixed z-[70] w-max max-w-[min(360px,92vw)] rounded-xl border border-[var(--border)] bg-[var(--popover)] p-1.5 shadow-[0_10px_30px_-12px_rgba(0,0,0,0.35)]"
+ >
+ {body}
</div>
);
}
diff --git a/web/components/reading/ReaderPane.tsx b/web/components/reading/ReaderPane.tsx
index c57110751..6c6e34023 100644
--- a/web/components/reading/ReaderPane.tsx
+++ b/web/components/reading/ReaderPane.tsx
@@ -906,6 +906,18 @@ export function ReaderPane({
label: t("History"),
onSelect: () => setShowHistory(true),
});
+ // The header's Forward button is desktop-only; on a phone the menu is
+ // where a learner comes back to it after following a citation.
+ items.push({
+ key: "forward",
+ icon: ArrowRight,
+ label: t("Forward"),
+ disabled:
+ locationHistory.index < 0 ||
+ locationHistory.index >= locationHistory.entries.length - 1,
+ onSelect: () => stepHistory(1),
+ mobileOnly: true,
+ });
}
items.push({
key: "follow",
@@ -939,10 +951,12 @@ export function ReaderPane({
autoJump,
exporting,
hasHistory,
+ locationHistory,
material,
ownAnnotationList,
runExport,
showAnnotations,
+ stepHistory,
t,
toggleAutoJump,
]);
@@ -953,7 +967,7 @@ export function ReaderPane({
<header className="flex h-11 shrink-0 items-center gap-1 border-b border-[var(--border)] px-2.5">
<FileText
size={14}
- className="shrink-0 text-[var(--muted-foreground)]"
+ className="hidden shrink-0 text-[var(--muted-foreground)] md:block"
/>
{/* The title, not the filename. A material saved from the web is
stored under its content hash, so this line read
@@ -972,7 +986,11 @@ export function ReaderPane({
returns from a citation the assistant jumped to. Everything else
that used to sit here — history, auto-jump, export, the notes
panel — is a setting or a once-a-session action, and seven small
- grey icons beside the title read as noise. They live under ⋯. */}
+ grey icons beside the title read as noise. They live under ⋯.
+ Below 768px the bar converges further (#916): back, title +
+ chapter, bookmark, ⋯. Forward is a secondary command there and
+ moves into the menu, and the file icon gives its width to the
+ chapter indicator. */}
{locationHistory.entries.length > 0 && (
<>
<HeaderButton
@@ -988,6 +1006,7 @@ export function ReaderPane({
locationHistory.index < 0 ||
locationHistory.index >= locationHistory.entries.length - 1
}
+ className="hidden md:inline-flex"
onClick={() => stepHistory(1)}
/>
</>
@@ -997,8 +1016,11 @@ export function ReaderPane({
<>
{/* The one place the reader's position is stated. Monospace is for
code, not for a line of UI copy; tabular figures alone stop the
- number from jittering as the learner scrolls. */}
- <span className="hidden shrink-0 whitespace-nowrap px-1 text-[11.5px] tabular-nums text-[var(--muted-foreground)] md:inline">
+ number from jittering as the learner scrolls. Below md it is the
+ "chapter" half of the converged title — title and indicator each
+ truncate inside their own share of the row, so together they
+ can never push the buttons past the edge. */}
+ <span className="min-w-0 max-w-[45%] shrink truncate whitespace-nowrap px-1 text-[11.5px] tabular-nums text-[var(--muted-foreground)] md:max-w-none md:shrink-0">
{isEpub ? (
<>
<span className="max-w-[180px] truncate">
@@ -1064,6 +1086,21 @@ export function ReaderPane({
}}
/>
)}
+ {locationHistory.entries.length > 0 && (
+ <MenuToolButton
+ icon={ArrowRight}
+ label={t("Forward")}
+ disabled={
+ locationHistory.index < 0 ||
+ locationHistory.index >= locationHistory.entries.length - 1
+ }
+ className="md:hidden"
+ onClick={() => {
+ stepHistory(1);
+ setShowMoreTools(false);
+ }}
+ />
+ )}
<MenuToolButton
icon={Crosshair}
label={t("Follow the assistant")}
@@ -1335,6 +1372,7 @@ function MenuToolButton({
spinning,
disabled,
hint,
+ className = "",
}: {
icon: typeof FileText;
label: string;
@@ -1344,6 +1382,7 @@ function MenuToolButton({
disabled?: boolean;
/** A second line saying what the setting currently does. */
hint?: string;
+ className?: string;
}) {
return (
<button
@@ -1353,7 +1392,7 @@ function MenuToolButton({
aria-checked={active}
disabled={spinning || disabled}
onClick={onClick}
- className={`flex w-full items-center gap-2 rounded-lg px-2.5 text-left text-[12px] transition disabled:cursor-default ${hint ? "py-1.5" : "h-9"} ${
+ className={`${className} flex w-full items-center gap-2 rounded-lg px-2.5 text-left text-[12px] transition disabled:cursor-default ${hint ? "py-1.5" : "h-9"} ${
active
? "bg-[color-mix(in_srgb,var(--primary)_12%,transparent)] text-[var(--primary)]"
: "text-[var(--foreground)] hover:bg-[var(--muted)] disabled:opacity-35 disabled:hover:bg-transparent"
diff --git a/web/components/reading/workspace-menu-context.ts b/web/components/reading/workspace-menu-context.ts
index 4f4f0acd3..39d55f70f 100644
--- a/web/components/reading/workspace-menu-context.ts
+++ b/web/components/reading/workspace-menu-context.ts
@@ -20,6 +20,12 @@ export interface WorkspaceMenuItem {
active?: boolean;
disabled?: boolean;
spinning?: boolean;
+ /**
+ * Shown below the `md` breakpoint only — a control the converged mobile
+ * header moved into this menu (#916). Desktop keeps it where it was, so
+ * the menu does not offer it twice.
+ */
+ mobileOnly?: boolean;
onSelect: () => void;
}
diff --git a/web/components/reading/workspace/WorkspaceChrome.tsx b/web/components/reading/workspace/WorkspaceChrome.tsx
index 0e822b0a8..0952ac90a 100644
--- a/web/components/reading/workspace/WorkspaceChrome.tsx
+++ b/web/components/reading/workspace/WorkspaceChrome.tsx
@@ -32,6 +32,7 @@ export function MenuItem({
hint,
active,
spinning,
+ mobileOnly = false,
}: {
icon: typeof StickyNote;
label: string;
@@ -42,6 +43,8 @@ export function MenuItem({
/** A setting that is on. Toggles report it; plain actions leave it unset. */
active?: boolean;
spinning?: boolean;
+ /** Below `md` only: a desktop control the converged mobile header moved here. */
+ mobileOnly?: boolean;
}) {
return (
<button
@@ -50,7 +53,7 @@ export function MenuItem({
disabled={disabled}
role={active === undefined ? undefined : "menuitemcheckbox"}
aria-checked={active}
- className="flex w-full items-start gap-2 rounded-md px-2.5 py-2 text-left text-[var(--foreground)] transition hover:bg-[var(--muted)] disabled:cursor-not-allowed disabled:opacity-45 disabled:hover:bg-transparent"
+ className={`${mobileOnly ? "md:hidden " : ""}flex w-full items-start gap-2 rounded-md px-2.5 py-2 text-left text-[var(--foreground)] transition hover:bg-[var(--muted)] disabled:cursor-not-allowed disabled:opacity-45 disabled:hover:bg-transparent`}
>
<Icon
size={13}
diff --git a/web/components/reading/workspace/WorkspaceMenu.tsx b/web/components/reading/workspace/WorkspaceMenu.tsx
index ee7ced5ea..0d3c0b746 100644
--- a/web/components/reading/workspace/WorkspaceMenu.tsx
+++ b/web/components/reading/workspace/WorkspaceMenu.tsx
@@ -112,6 +112,7 @@ export function WorkspaceMenu({
active={item.active}
spinning={item.spinning}
disabled={item.disabled}
+ mobileOnly={item.mobileOnly}
onClick={() => {
// A toggle stays open so the learner sees it flip.
if (item.active === undefined) setOpen(false);
diff --git a/web/tests/reading-mobile-header.spec.tsx b/web/tests/reading-mobile-header.spec.tsx
new file mode 100644
index 000000000..e9e4a74da
--- /dev/null
+++ b/web/tests/reading-mobile-header.spec.tsx
@@ -0,0 +1,203 @@
+import { render, screen, waitFor, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { ArrowRight } from "lucide-react";
+import { describe, expect, it, vi } from "vitest";
+
+import { initI18n } from "@/i18n/init";
+
+initI18n("en");
+
+const api = vi.hoisted(() => ({
+ fetchExport: vi.fn(),
+ getMaterial: vi.fn(async () => null),
+ getReadingPosition: vi.fn(async () => ({ locator: 1, source_anchor: "" })),
+ saveReadingPosition: vi.fn(),
+}));
+
+/** The document view is stubbed down to "report selections upward". */
+const view = vi.hoisted(() => ({
+ select: null as null | ((payload: unknown) => void),
+}));
+
+vi.mock("@/lib/reading-api", async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ ...api,
+}));
+
+vi.mock("@/components/reading/PdfDocumentView", () => ({
+ PdfDocumentView: ({
+ onSelection,
+ }: {
+ onSelection: (payload: unknown) => void;
+ }) => {
+ view.select = onSelection;
+ return <div data-testid="doc" />;
+ },
+}));
+
+vi.mock("@/lib/auth", () => ({
+ fetchAuthStatus: vi.fn(async () => null),
+}));
+
+vi.mock("@/components/reading/EpubDocumentView", () => ({
+ EpubDocumentView: () => null,
+}));
+
+vi.mock("@/components/reading/TextUnitView", () => ({
+ TextUnitView: () => null,
+ unitLabel: () => "page",
+}));
+
+vi.mock("@/components/reading/AnnotationList", () => ({
+ AnnotationList: () => null,
+}));
+
+const material = {
+ // The history store only accepts hash-shaped material ids; a made-up "m1"
+ // would be dropped and every history assertion below would vacuously pass.
+ material_id: "0123456789abcdef",
+ title: "Understanding Deep Learning",
+ filename: "udl.pdf",
+ unit: "page",
+ mime: "application/pdf",
+ render_mode: "raw",
+ has_raw_view: true,
+ unit_count: 10,
+};
+
+vi.mock("@/context/ReadingContext", () => ({
+ useReading: () => ({
+ material,
+ annotations: [],
+ loading: false,
+ error: "",
+ openMaterial: vi.fn(),
+ closeMaterial: vi.fn(),
+ saveMark: vi.fn(),
+ removeMark: vi.fn(),
+ mergeMark: vi.fn(),
+ dismissError: vi.fn(),
+ setError: vi.fn(),
+ reportViewport: vi.fn(),
+ }),
+}));
+
+const { ReaderPane } = await import("@/components/reading/ReaderPane");
+const { WorkspaceMenu } = await import(
+ "@/components/reading/workspace/WorkspaceMenu"
+);
+
+/**
+ * #916, header half: below 768px the reader's top bar converges to back,
+ * title + chapter, bookmark and ⋯. jsdom lays nothing out, so "cannot
+ * overflow horizontally" is asserted the only honest way available — every
+ * child of the row either truncates inside its own box or is `shrink-0`,
+ * and the controls that would crowd the row are display:none below `md`.
+ */
+describe("reader header below 768px", () => {
+ it("converges to back, title + chapter, bookmark and more without an overflow path", async () => {
+ const { container } = render(
+ <ReaderPane
+ onClose={() => undefined}
+ onToggleBookmark={() => undefined}
+ />,
+ );
+
+ // The flexible middle: title and chapter indicator each truncate inside
+ // their own share of the row.
+ const title = await screen.findByText("Understanding Deep Learning");
+ expect(title.className).toContain("min-w-0");
+ expect(title.className).toContain("flex-1");
+ expect(title.className).toContain("truncate");
+
+ const position = screen.getByText(/1\s*\/\s*10/);
+ expect(position.className).toContain("min-w-0");
+ expect(position.className).toContain("truncate");
+ expect(position.className).toContain("max-w-[45%]");
+ // Desktop keeps the indicator unconstrained — the bound is mobile-only.
+ expect(position.className).toContain("md:max-w-none");
+ expect(position.className).toContain("md:shrink-0");
+
+ // The four controls that stay: back, bookmark, more — all fixed-width.
+ for (const name of ["Back", /Bookmark this page/, "More"]) {
+ const button = screen.getByRole("button", { name });
+ expect(button.className).toContain("shrink-0");
+ expect(button.className).not.toContain("hidden");
+ }
+
+ // What left the mobile bar: forward (into the ⋯ menu) and the file icon.
+ const forward = screen.getByRole("button", { name: "Forward" });
+ expect(forward.className).toContain("hidden");
+ expect(forward.className).toContain("md:inline-flex");
+ // SVG className is not a string; read the attribute instead.
+ const fileIconClass =
+ container.querySelector(".lucide-file-text")?.getAttribute("class") ??
+ "";
+ expect(fileIconClass).toContain("hidden");
+ expect(fileIconClass).toContain("md:block");
+ });
+
+ it("keeps forward reachable from the more menu on a phone", async () => {
+ const user = userEvent.setup();
+ const { rerender } = render(
+ <ReaderPane onClose={() => undefined} externalJump={null} />,
+ );
+
+ // Two explicit jumps give the history three entries; the pane sits on the
+ // last one, so forward is disabled until the reader steps back.
+ const jump = (locator: number, nonce: number) =>
+ rerender(
+ <ReaderPane
+ onClose={() => undefined}
+ externalJump={{ locator, nonce }}
+ />,
+ );
+ jump(5, 1);
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: "Back" })).toBeEnabled(),
+ );
+ jump(6, 2);
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: "Forward" })).toBeDisabled(),
+ );
+
+ await user.click(screen.getByRole("button", { name: "Back" }));
+ expect(screen.getByRole("button", { name: "Forward" })).toBeEnabled();
+
+ await user.click(screen.getByRole("button", { name: "More" }));
+ const menu = screen.getByRole("menu", { name: "More" });
+ const menuForward = within(menu).getByRole("menuitem", {
+ name: "Forward",
+ });
+ // Mobile-only: the menu does not offer forward twice on desktop.
+ expect(menuForward.className).toContain("md:hidden");
+ await user.click(menuForward);
+
+ expect(screen.getByRole("button", { name: "Forward" })).toBeDisabled();
+ });
+
+ it("marks workspace-hosted mobile-only items below md only", async () => {
+ const user = userEvent.setup();
+ render(
+ <WorkspaceMenu
+ collection={[]}
+ sections={{
+ material: [
+ {
+ key: "forward",
+ icon: ArrowRight,
+ label: "Forward",
+ onSelect: () => undefined,
+ mobileOnly: true,
+ },
+ ],
+ }}
+ />,
+ );
+ await user.click(screen.getByRole("button", { name: "More" }));
+ // Plain workspace menu actions carry no ARIA role of their own (only
+ // the checkbox toggles do) — the button is the queryable surface.
+ const item = screen.getByRole("button", { name: "Forward" });
+ expect(item.className).toContain("md:hidden");
+ });
+});
diff --git a/web/tests/reading-selection-sheet.spec.tsx b/web/tests/reading-selection-sheet.spec.tsx
new file mode 100644
index 000000000..bd4159e9f
--- /dev/null
+++ b/web/tests/reading-selection-sheet.spec.tsx
@@ -0,0 +1,149 @@
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { initI18n } from "@/i18n/init";
+
+initI18n("en");
+
+const device = vi.hoisted(() => ({ isMobile: false }));
+
+vi.mock("@/hooks/useDevice", () => ({
+ useDevice: () => ({
+ device: device.isMobile ? "mobile" : "tablet",
+ isMobile: device.isMobile,
+ isTablet: !device.isMobile,
+ isDesktop: false,
+ isCompact: true,
+ }),
+}));
+
+const { AnnotationPopover } = await import(
+ "@/components/reading/AnnotationPopover"
+);
+
+const noop = () => undefined;
+
+function renderPopover(overrides: Partial<Parameters<typeof AnnotationPopover>[0]> = {}) {
+ const onDismiss = vi.fn();
+ const props = {
+ anchor: { x: 120, y: 200 },
+ quote: "the slope of the line",
+ onHighlight: noop,
+ onUnderline: noop,
+ onNote: noop,
+ onCitation: noop,
+ onAsk: noop,
+ onDismiss,
+ ...overrides,
+ };
+ const view = render(<AnnotationPopover {...props} />);
+ return { onDismiss, ...view };
+}
+
+/** Five AI actions: three chips inline, two behind the ⋯ overflow. */
+const aiActions = [1, 2, 3, 4, 5].map((n) => ({
+ key: `a${n}`,
+ label: `Action ${n}`,
+ title: `Action ${n} in full`,
+ onClick: noop,
+}));
+
+/**
+ * #916, dictionary half: on a phone the selection panel — the panel a
+ * long-press on a word summons, carrying explain and translate — is a
+ * bottom card rather than an anchored popover. Short content sits at its
+ * collapsed height; the expanded states cap and scroll; the handle closes
+ * on a pull-down. Desktop keeps the anchored popover unchanged.
+ */
+describe("selection panel as a bottom card below 768px", () => {
+ beforeEach(() => {
+ device.isMobile = true;
+ });
+
+ it("docks to the bottom edge with safe-area padding and a collapsed body", () => {
+ const { container } = renderPopover({ aiActions });
+
+ const sheet = screen.getByRole("dialog", { name: "Annotate selection" });
+ expect(sheet.className).toContain("dt-reader-sheet");
+ expect(sheet.className).toContain("bottom-0");
+ expect(sheet.className).toContain("inset-x-0");
+ // The home-indicator strip stays clear of the card's buttons.
+ expect(sheet.className).toContain("pb-[calc(env(safe-area-inset-bottom)+10px)]");
+ expect(container.querySelector('[data-scroll="short"]')).not.toBeNull();
+ const body = container.querySelector('[data-scroll="short"]') as HTMLElement;
+ // Short content collapses: nothing to scroll, no forced height.
+ expect(body.className).not.toContain("overflow-y-auto");
+ expect(body.className).not.toContain("max-h-");
+ expect(screen.getByTestId("sheet-handle")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Ask about this" }),
+ ).toBeVisible();
+ });
+
+ it("switches the body to capped and scrollable for long content", async () => {
+ const user = userEvent.setup();
+ const { container } = renderPopover({ aiActions });
+
+ // Long content #1: the overflow list of extra AI actions.
+ await user.click(screen.getByRole("button", { name: "More actions" }));
+ let body = container.querySelector('[data-scroll]') as HTMLElement;
+ expect(body.getAttribute("data-scroll")).toBe("long");
+ expect(body.className).toContain("max-h-[60dvh]");
+ expect(body.className).toContain("overflow-y-auto");
+ expect(body.className).toContain("overscroll-contain");
+ expect(within(body).getByRole("button", { name: "Action 4 in full" })).toBeVisible();
+
+ // Long content #2: the note editor.
+ await user.click(screen.getByRole("button", { name: "Add note" }));
+ body = container.querySelector('[data-scroll]') as HTMLElement;
+ expect(body.getAttribute("data-scroll")).toBe("long");
+ expect(screen.getByPlaceholderText("Your note…")).toBeVisible();
+ });
+
+ it("closes on a pull-down of the handle, not on a nudge", () => {
+ const { onDismiss } = renderPopover({ aiActions });
+ const handle = screen.getByTestId("sheet-handle");
+
+ // A nudge moves the card but keeps it open.
+ fireEvent.pointerDown(handle, { pointerId: 3, clientY: 300 });
+ fireEvent.pointerMove(handle, { pointerId: 3, clientY: 316 });
+ fireEvent.pointerUp(handle, { pointerId: 3, clientY: 318 });
+ expect(onDismiss).not.toHaveBeenCalled();
+
+ // A pull past the threshold dismisses.
+ fireEvent.pointerDown(handle, { pointerId: 4, clientY: 300 });
+ fireEvent.pointerMove(handle, { pointerId: 4, clientY: 331 });
+ fireEvent.pointerUp(handle, { pointerId: 4, clientY: 355 });
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ });
+
+ it("still closes on Escape and on a tap outside", () => {
+ const { onDismiss } = renderPopover({ aiActions });
+
+ fireEvent.keyDown(document, { key: "Escape" });
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+
+ fireEvent.pointerDown(document.body);
+ expect(onDismiss).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe("selection panel above 768px (desktop regression)", () => {
+ beforeEach(() => {
+ device.isMobile = false;
+ });
+
+ it("stays the anchored popover, not a bottom card", () => {
+ const { container } = renderPopover({ aiActions });
+
+ const popover = screen.getByRole("dialog", { name: "Annotate selection" });
+ expect(popover.className).toContain("dt-reader-popover");
+ expect(popover.className).not.toContain("dt-reader-sheet");
+ expect(popover.className).not.toContain("bottom-0");
+ // No sheet furniture on the desktop frame: no handle, no scroll region.
+ expect(container.querySelector('[data-scroll]')).toBeNull();
+ expect(container.querySelector('[data-testid="sheet-handle"]')).toBeNull();
+ expect(screen.getByRole("button", { name: "Ask about this" })).toBeVisible();
+ });
+});