Skip to content

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

53.0 KB
Raw Blame
"use client";

import dynamic from "next/dynamic";
import { browserStorage } from "@/shared/storage";
import Tooltip from "@/shared/ui/Tooltip";

import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
import { createPortal } from "react-dom";
import {
  ArrowLeft,
  ArrowRight,
  Bookmark,
  BookmarkCheck,
  Crosshair,
  Download,
  FileText,
  MoreHorizontal,
  Loader2,
  History,
  PanelRightClose,
  PanelRightOpen,
  X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { useReading } from "@/context/ReadingContext";
import {
  READER_ACTION_EVENT,
  READER_TURN_END_EVENT,
  type ReaderActionPayload,
} from "@/lib/reading-reader-action";
import { scopedUrl } from "@/lib/workspace-scope";
import { citationTargetFromHref, readingPassageHref } from "@/lib/reading-citations";
import {
  fetchExport,
  getMaterial,
  getReadingPosition,
  saveReadingPosition,
  type AnnotationColor,
  type AnnotationItem,
  type MaterialDetail,
  type ReadingBookmark,
} from "@/lib/reading-api";
import { AnnotationList } from "./AnnotationList";
import { AnnotationPopover, type PopoverAiAction } from "./AnnotationPopover";
import { passagePrompts } from "@/lib/reading-passage-prompts";
import {
  PdfDocumentView,
  type JumpRequest,
  type SelectionPayload,
} from "./PdfDocumentView";
import { ReadingExtensionBar } from "./ReadingExtensionBar";
import {
  useReadingActions,
  type ReadingActionEntry,
} from "./reading-actions-context";
import {
  useWorkspaceMenuSection,
  type WorkspaceMenuItem,
} from "./workspace-menu-context";
import { TextUnitView, unitLabel } from "./TextUnitView";
import type { ReaderHeading } from "@/lib/reading-outline";
import {
  EMPTY_READING_HISTORY,
  loadReadingHistory,
  moveReadingHistory,
  pushReadingLocation,
  replaceCurrentReadingLocation,
  saveReadingHistory,
  selectReadingHistoryIndex,
  type ReadingLocationEntry,
  type ReadingLocationHistory,
} from "@/lib/reading-location-history";

function EpubLoading() {
  const { t } = useTranslation();
  return (
    <div role="status" aria-label={t("Loading")} className="flex h-full items-center justify-center">
      <Loader2 aria-hidden="true" className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
    </div>
  );
}

const EpubDocumentView = dynamic(
  () => import("./EpubDocumentView").then(module => module.EpubDocumentView),
  { ssr: false, loading: EpubLoading },
);

/** Event the reader dispatches to prefill the composer from a selection. */
export const READER_ASK_EVENT = "dt:reader-ask";
const AUTO_JUMP_KEY = "dt.reader.autoJump";

function locationEntry(
  material: MaterialDetail,
  locator: number,
): ReadingLocationEntry {
  return {
    materialId: material.material_id,
    locator,
    title: material.title || material.filename,
    source: {
      filename: material.filename,
      unit: material.unit,
      mime: material.mime,
      renderMode: material.render_mode,
    },
  };
}

export interface ReaderPaneProps {
  onClose: () => void;
  sessionId?: string | null;
  /** User-owned navigation from the workspace's source outline. */
  externalJump?: JumpRequest | null;
  /**
   * Headings the text view discovers in the open unit. Only the rendered
   * document knows them, but the workspace navigator is where the reader
   * looks for structure — so they are reported up rather than shown here.
   */
  onHeadingsChange?: (headings: ReaderHeading[]) => void;
  onActiveHeadingChange?: (headingId: string | null) => void;
  /** Heading the navigator asked to scroll to. */
  headingJump?: {
    id: string;
    nonce: number;
    locator?: number;
    sourceHref?: string;
  } | null;
  /**
   * Kept places in this material. Owned by the workspace because the outline
   * panel lists them and this toolbar only needs to answer "is the page I am
   * on one of them?" — see `useReadingWorkspace`.
   */
  bookmarks?: ReadingBookmark[];
  onToggleBookmark?: (locator: number, label?: string) => void;
  /**
   * Where in the material the reader now is.
   *
   * Only the rendered document knows this, and the workspace is where it is
   * needed: the outline panel highlights the row the reader is inside. The
   * media stage has always reported it; the document surface did not, so on
   * an EPUB, PDF or Markdown the outline stayed on whichever row was last
   * clicked while the header counted up (#1447).
   */
  onLocatorChange?: (locator: number) => void;
  /**
   * Whether the pane shows its own annotation column beside the document.
   * The workspace turns it off and lists notes in its navigator instead: a
   * fourth column between the page and the companion left the page itself
   * the narrowest thing on screen.
   */
  ownAnnotationList?: boolean;
  /**
   * Where the document's title row goes when the host has a bar for it. The
   * workspace gives its own top bar, so the title, place and bookmark read on
   * one line with the collection rather than as a second strip under it.
   * Without one the row renders here, at the top of the pane.
   */
  headSlot?: HTMLElement | null;
}

/**
 * The document surface of the Reading workspace, with its own annotations.
 * Source navigation, tabs and the outline are owned by the workspace shell —
 * this component renders one open document and everything anchored to it.
 *
 * Two behaviours are worth calling out because they were explicit product
 * decisions rather than defaults:
 *
 * * **Auto-jump is a user-owned toggle, not a rate limit.** The assistant may
 *   call `reader_goto` as often as it likes — once per passage it discusses is
 *   the intended usage. When the toggle is on, the view follows every call, so
 *   the reader watches the model read. When it is off, jumps are ignored and the
 *   citations in the answer remain clickable, so the user stays in control of
 *   their own scroll position. The preference persists across sessions.
 * * **Annotations are optimistic.** A highlight appears the moment it is drawn
 *   and is reconciled with the server's row when the write returns; a failed
 *   write removes it again and surfaces the error. Waiting for a round trip
 *   before showing ink makes highlighting feel broken.
 */
export function ReaderPane({
  onClose,
  sessionId,
  externalJump = null,
  onHeadingsChange,
  onActiveHeadingChange,
  headingJump = null,
  bookmarks = [],
  onToggleBookmark,
  onLocatorChange,
  ownAnnotationList = true,
  headSlot = null,
}: ReaderPaneProps) {
  const { t, i18n } = useTranslation();
  // Document + annotations live in the provider (workspace layout), so they
  // survive the remount that sending the first message causes.
  const {
    material,
    annotations,
    loading: loadingMaterial,
    error: notice,
    openMaterial,
    closeMaterial,
    saveMark,
    removeMark,
    mergeMark,
    dismissError,
    setError,
    reportViewport,
  } = useReading();

  const [activeAnnotationId, setActiveAnnotationId] = useState<string | null>(
    null,
  );
  const [selection, setSelection] = useState<SelectionPayload | null>(null);
  // Whether the annotation popover is showing, kept apart from whether there
  // IS a selection. They used to be the same flag, and the popover dismisses
  // itself on a document-level, capture-phase `pointerdown` — so pressing a
  // toolbar button cleared `selection` before the click could land, React
  // re-rendered the button as `disabled` (all four selection-gated actions
  // declare `requires: ["selection"]`), and the browser then refused to
  // dispatch the rest of the activation sequence to a disabled control. No
  // fetch, no spinner, no error: 引导我 / 翻译成英文 / 翻译成中文 / 解释词汇
  // have been unreachable by pointer since the toolbar shipped.
  const [popoverOpen, setPopoverOpen] = useState(false);

  /** One place to open a selection, so the popover cannot drift out of step. */
  const openSelection = useCallback((payload: SelectionPayload | null) => {
    setSelection(payload);
    setPopoverOpen(payload !== null);
  }, []);

  /** Drop the selection entirely — it is stale, not merely unfocused. */
  const clearSelection = useCallback(() => {
    setSelection(null);
    setPopoverOpen(false);
  }, []);
  const [jump, setJump] = useState<JumpRequest | null>(null);
  // `null` = follow the document: show the panel once there is something in it.
  // An empty panel is a whole column of nothing next to the page, which reads as
  // a layout bug rather than an affordance. An explicit true/false means the
  // user decided, and that wins from then on.
  const [annotationPanel, setAnnotationPanel] = useState<boolean | null>(null);
  const [autoJump, setAutoJump] = useState(true);
  const [exporting, setExporting] = useState(false);
  const [currentLocator, setCurrentLocator] = useState(1);
  const [epubPosition, setEpubPosition] = useState<{
    materialId: string; percentage: number | null;
  } | null>(null);
  const handleEpubProgress = useCallback((percentage: number | null) => {
    if (material) setEpubPosition({ materialId: material.material_id, percentage });
  }, [material]);
  const nonceRef = useRef(0);
  const headingLocatorRef = useRef(1);
  const jumpMaterialIdRef = useRef<string | null>(null);
  const [locationHistory, setLocationHistory] =
    useState<ReadingLocationHistory>(EMPTY_READING_HISTORY);
  const [historySessionId, setHistorySessionId] = useState<
    string | null | undefined
  >(undefined);
  const [showHistory, setShowHistory] = useState(false);
  const [showMoreTools, setShowMoreTools] = useState(false);
  const moreToolsButtonRef = useRef<HTMLButtonElement>(null);
  const moreToolsMenuRef = useRef<HTMLDivElement>(null);
  const [unavailableMaterials, setUnavailableMaterials] = useState<Set<string>>(
    new Set(),
  );

  useEffect(() => {
    if (!showMoreTools) return;
    moreToolsMenuRef.current?.querySelector<HTMLElement>("[role^='menuitem']")?.focus();
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key !== "Escape") return;
      event.preventDefault();
      event.stopPropagation();
      setShowMoreTools(false);
      moreToolsButtonRef.current?.focus();
    };
    const onPointerDown = (event: PointerEvent) => {
      const target = event.target as Node;
      if (
        !moreToolsMenuRef.current?.contains(target) &&
        !moreToolsButtonRef.current?.contains(target)
      ) {
        setShowMoreTools(false);
      }
    };
    document.addEventListener("keydown", onKeyDown);
    document.addEventListener("pointerdown", onPointerDown);
    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.removeEventListener("pointerdown", onPointerDown);
    };
  }, [showMoreTools]);
  // The history list used to close only by picking an entry or by the ⋯ that
  // opened it. Opened from the workspace's menu there is no ⋯ here to click
  // again, so it closes the way the menu does: click away, or Escape.
  const historyPanelRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (!showHistory) return;
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key !== "Escape") return;
      event.preventDefault();
      setShowHistory(false);
    };
    const onPointerDown = (event: PointerEvent) => {
      const target = event.target as Node;
      if (
        !historyPanelRef.current?.contains(target) &&
        !moreToolsMenuRef.current?.contains(target)
      ) {
        setShowHistory(false);
      }
    };
    document.addEventListener("keydown", onKeyDown);
    document.addEventListener("pointerdown", onPointerDown);
    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.removeEventListener("pointerdown", onPointerDown);
    };
  }, [showHistory]);
  const navigationNonceRef = useRef(0);
  const pendingNavigationRef = useRef<{
    mode: "push" | "replay";
    materialId: string;
    locator: number;
  } | null>(null);
  const historyRestoreAttemptRef = useRef<{
    sessionId: string | null;
  } | null>(null);
  const externalJumpNonceRef = useRef(0);
  const positionSaveTimerRef = useRef<number | null>(null);
  /** Materials whose stored position has already been honoured. */
  const resumedMaterialRef = useRef("");
  const headingJumpNonceRef = useRef(0);
  const historyReady = historySessionId === (sessionId ?? null);

  // -- persisted auto-jump preference --------------------------------------

  useEffect(() => {
    try {
      const stored = browserStorage.readRaw("local", AUTO_JUMP_KEY);
      if (stored !== null) setAutoJump(stored === "1");
    } catch {
      // Private mode / storage disabled — keep the default.
    }
  }, []);

  const toggleAutoJump = useCallback(() => {
    setAutoJump((current) => {
      const next = !current;
      try {
        browserStorage.writeRaw("local", AUTO_JUMP_KEY, next ? "1" : "0");
      } catch {
        // Non-fatal: the toggle still works for this session.
      }
      return next;
    });
  }, []);

  // -- viewport reporting --------------------------------------------------

  const handleVisibleLocator = useCallback(
    (locator: number) => {
      setCurrentLocator(locator);
      onLocatorChange?.(locator);
      reportViewport({ locator });
      // Remember where the reader got to, so opening this material again
      // starts here instead of at page 1. EPUB writes its own position — a
      // CFI it needs to land inside a reflowed page — so leaving that alone
      // is the difference between resuming a paragraph and resuming a
      // chapter; the media stage does the same with a timestamp.
      if (material && material.render_mode !== "epub") {
        const materialId = material.material_id;
        const total = material.unit_count;
        if (positionSaveTimerRef.current) {
          clearTimeout(positionSaveTimerRef.current);
        }
        positionSaveTimerRef.current = window.setTimeout(() => {
          void saveReadingPosition(materialId, {
            locator,
            source_anchor: "",
            percentage: total > 0 ? locator / total : 0,
          }).catch(() => {
            // Reading continues when a background progress write fails.
          });
        }, 400);
      }
      if (material && historyReady) {
        const pending = pendingNavigationRef.current;
        if (
          pending?.materialId === material.material_id &&
          pending.locator !== locator
        ) {
          return;
        }
        setLocationHistory((current) => {
          const entry = locationEntry(material, locator);
          return current.entries[current.index]?.materialId ===
            material.material_id
            ? replaceCurrentReadingLocation(current, entry)
            : pushReadingLocation(current, entry);
        });
      }
    },
    [historyReady, material, onLocatorChange, reportViewport],
  );

  useEffect(() => {
    reportViewport({ selection: selection?.quote ?? "" });
  }, [selection, reportViewport]);

  // -- reader actions from the assistant -----------------------------------

  const requestJump = useCallback(
    (locator: number, quote?: string, targetMaterialId?: string) => {
      nonceRef.current += 1;
      setJump({ locator, quote, nonce: nonceRef.current });
      jumpMaterialIdRef.current =
        targetMaterialId ?? material?.material_id ?? null;
    },
    [material?.material_id],
  );

  const rememberExplicitLocation = useCallback(
    (locator: number) => {
      if (!material || !historyReady) return;
      setLocationHistory((current) =>
        pushReadingLocation(current, locationEntry(material, locator)),
      );
    },
    [historyReady, material],
  );

  const openHistoryEntry = useCallback(
    async (
      entry: ReadingLocationEntry,
      mode: "push" | "replay",
      forceOpen = false,
      candidate?: MaterialDetail,
    ) => {
      const navigationNonce = ++navigationNonceRef.current;
      if (forceOpen || entry.materialId !== material?.material_id) {
        setJump(null);
        pendingNavigationRef.current = {
          mode,
          materialId: entry.materialId,
          locator: entry.locator,
        };
        const opened = await openMaterial(candidate ?? entry.materialId);
        if (navigationNonce !== navigationNonceRef.current) return false;
        if (!opened) {
          setUnavailableMaterials((current) =>
            new Set(current).add(entry.materialId),
          );
          pendingNavigationRef.current = null;
          return false;
        }
      } else {
        pendingNavigationRef.current = null;
      }
      setUnavailableMaterials((current) => {
        if (!current.has(entry.materialId)) return current;
        const next = new Set(current);
        next.delete(entry.materialId);
        return next;
      });
      requestJump(entry.locator, undefined, entry.materialId);
      return true;
    },
    [material?.material_id, openMaterial, requestJump],
  );

  const selectHistoryEntry = useCallback(
    (index: number) => {
      const next = selectReadingHistoryIndex(locationHistory, index);
      const entry = next.entries[next.index];
      if (!entry) return;
      setLocationHistory(next);
      setShowHistory(false);
      void openHistoryEntry(entry, "replay");
    },
    [locationHistory, openHistoryEntry],
  );

  const stepHistory = useCallback(
    (delta: -1 | 1) => {
      const next = moveReadingHistory(locationHistory, delta);
      if (next.index === locationHistory.index) return;
      const entry = next.entries[next.index];
      if (!entry) return;
      setLocationHistory(next);
      void openHistoryEntry(entry, "replay");
    },
    [locationHistory, openHistoryEntry],
  );

  useEffect(() => {
    const scopedSessionId = sessionId ?? null;
    if (loadingMaterial) return;
    if (!material) return;
    if (historyRestoreAttemptRef.current?.sessionId === scopedSessionId) {
      return;
    }
    historyRestoreAttemptRef.current = { sessionId: scopedSessionId };
    const hadPendingNavigation = pendingNavigationRef.current !== null;
    navigationNonceRef.current += 1;
    pendingNavigationRef.current = null;
    const restored = scopedSessionId
      ? loadReadingHistory(scopedSessionId)
      : EMPTY_READING_HISTORY;
    setLocationHistory(restored);
    setUnavailableMaterials(new Set());
    setHistorySessionId(sessionId ?? null);
    const entry = restored.entries[restored.index];
    if (entry) void openHistoryEntry(entry, "replay", hadPendingNavigation);
    else if (hadPendingNavigation) closeMaterial();
    // Restore once per chat id. Material changes caused by the restore must not
    // restart it with a newly-created callback closure.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sessionId, loadingMaterial]);

  useEffect(() => {
    if (!historyReady || !sessionId || historySessionId !== sessionId) return;
    saveReadingHistory(sessionId, locationHistory);
  }, [historyReady, historySessionId, locationHistory, sessionId]);

  useEffect(() => {
    if (!historyReady || !material) return;
    const pending = pendingNavigationRef.current;
    if (pending?.materialId === material.material_id) {
      pendingNavigationRef.current = null;
      setCurrentLocator(pending.locator);
      if (pending.mode === "push") {
        setLocationHistory((current) =>
          pushReadingLocation(
            current,
            locationEntry(material, pending.locator),
          ),
        );
      }
      return;
    }
    if (pending) return;
    setJump(null);
    setCurrentLocator(1);
    setLocationHistory((current) =>
      pushReadingLocation(current, locationEntry(material, 1)),
    );
  }, [historyReady, material]);

  // -- resume where the reader left off ------------------------------------
  //
  // The effect above lands every newly-opened material on page 1. For a
  // 74-page document that a learner is halfway through, page 1 is the one
  // place they are certainly not trying to be — so the stored position, if
  // there is one, decides instead. Only once per material: after that the
  // reader is in charge, and re-running this would drag them back.
  //
  // EPUB and the media stage resume themselves (a CFI, a timestamp), and a
  // navigation already in flight — a citation, a history entry — is a
  // destination the learner asked for and outranks where they last stopped.
  useEffect(() => {
    const materialId = material?.material_id;
    if (!materialId || material?.render_mode === "epub") return;
    if (resumedMaterialRef.current === materialId) return;
    if (pendingNavigationRef.current) return;
    // Claimed before awaiting: this render is not the last one before the
    // request comes back.
    resumedMaterialRef.current = materialId;
    let cancelled = false;
    void getReadingPosition(materialId)
      .then((position) => {
        if (cancelled || position.locator <= 1) return;
        requestJump(position.locator);
      })
      .catch(() => {
        // Never opened before, or the read failed: page 1 is a fine start.
      });
    return () => {
      cancelled = true;
    };
  }, [material?.material_id, material?.render_mode, requestJump]);

  useEffect(
    () => () => {
      if (positionSaveTimerRef.current) {
        clearTimeout(positionSaveTimerRef.current);
      }
    },
    [],
  );

  const navigateCitation = useCallback(
    async (href: string | null | undefined) => {
      const target = citationTargetFromHref(href);
      if (!target) return false;
      if (target.materialId && target.materialId !== material?.material_id) {
        try {
          const candidate = await getMaterial(target.materialId);
          if (
            target.materialRevision &&
            candidate.revision !== target.materialRevision
          ) {
            setError(
              "This citation points to an older material revision that is not available in the reader.",
            );
            return true;
          }
          const entry = locationEntry(candidate, target.locator);
          await openHistoryEntry(entry, "push", false, candidate);
        } catch (caught) {
          setError(
            caught instanceof Error
              ? caught.message
              : "This citation's material could not be opened.",
          );
          return true;
        }
      } else if (
        target.materialRevision &&
        material?.revision !== target.materialRevision
      ) {
        setError(
          "This citation points to an older material revision that is not available in the reader.",
        );
        return true;
      }
      rememberExplicitLocation(target.locator);
      requestJump(target.locator);
      return true;
    },
    [
      material?.material_id,
      material?.revision,
      openHistoryEntry,
      rememberExplicitLocation,
      requestJump,
      setError,
    ],
  );

  const followedSource = useRef('');
  useEffect(() => {
    const follow = () => {
      const href = window.location.hash;
      if (!material || !citationTargetFromHref(href) || followedSource.current === href) return;
      followedSource.current = href;
      void navigateCitation(href);
    };
    follow();
    window.addEventListener('hashchange', follow);
    return () => window.removeEventListener('hashchange', follow);
  }, [material, navigateCitation]);

  useEffect(() => {
    if (!externalJump) return;
    if (externalJumpNonceRef.current === externalJump.nonce) return;
    externalJumpNonceRef.current = externalJump.nonce;
    rememberExplicitLocation(externalJump.locator);
    requestJump(externalJump.locator, externalJump.quote);
  }, [externalJump, rememberExplicitLocation, requestJump]);

  useEffect(() => {
    headingLocatorRef.current = currentLocator;
  }, [currentLocator]);

  useEffect(() => {
    if (!headingJump) return;
    if (headingJumpNonceRef.current === headingJump.nonce) return;
    headingJumpNonceRef.current = headingJump.nonce;
    rememberExplicitLocation(headingJump.locator ?? headingLocatorRef.current);
  }, [headingJump, rememberExplicitLocation]);

  useEffect(() => {
    const onReaderAction = (event: Event) => {
      const detail = (event as CustomEvent<ReaderActionPayload>).detail;
      if (!detail || !material) return;
      // Ignore actions aimed at a document that is no longer open — a stale
      // event replayed from an earlier turn must not move the current view.
      if (detail.material_id && detail.material_id !== material.material_id)
        return;

      if (detail.reader_action === "annotate" && detail.annotation) {
        const incoming = detail.annotation as unknown as AnnotationItem;
        if (incoming.annotation_id) {
          mergeMark(incoming);
        }
      }
      if (!autoJump) return;
      const locator = Number(detail.locator ?? 0);
      if (locator >= 1) {
        rememberExplicitLocation(locator);
        requestJump(locator, detail.quote || undefined);
      }
    };
    window.addEventListener(READER_ACTION_EVENT, onReaderAction);
    return () =>
      window.removeEventListener(READER_ACTION_EVENT, onReaderAction);
  }, [material, autoJump, requestJump, mergeMark, rememberExplicitLocation]);

  /**
   * Follow the answer when the model did not move the reader itself.
   *
   * `reader_goto` is the intended path and gives a highlighted quote; this is
   * the safety net for the turns where the model cites `[p.5]` in prose and
   * simply never calls it. Without it the reader sits on page 1 next to an
   * answer about page 5, which reads as broken no matter whose fault it is.
   *
   * Deliberately the FIRST citation of the LAST answer, and only when auto-jump
   * is on: it is the same promise the toggle makes — the view follows what the
   * assistant is talking about.
   */
  useEffect(() => {
    const onTurnEnd = (event: Event) => {
      const moved = (event as CustomEvent<{ moved?: boolean }>).detail?.moved;
      if (moved || !autoJump || !material) return;
      // One frame later: the final answer is still being committed to the DOM
      // as the turn closes.
      const timer = window.setTimeout(() => {
        const answers = document.querySelectorAll('[role="article"]');
        const last = answers[answers.length - 1];
        const anchor = last?.querySelector<HTMLAnchorElement>(
          'a[href^="#dt-locator-"], a[href^="#dt-material-"]',
        );
        void navigateCitation(anchor?.getAttribute("href"));
      }, 120);
      return () => window.clearTimeout(timer);
    };
    window.addEventListener(READER_TURN_END_EVENT, onTurnEnd);
    return () => window.removeEventListener(READER_TURN_END_EVENT, onTurnEnd);
  }, [autoJump, material, navigateCitation]);

  /**
   * Citation clicks in assistant prose, intercepted in the CAPTURE phase.
   *
   * It has to be capture, and it has to be here. The shared Markdown renderer
   * calls `preventDefault()` on *every* `#`-prefixed link before looking for an
   * element with that id (RichMarkdownRenderer's hash-link branch), and the chat
   * page's own delegated handler bails on `event.defaultPrevented`. A citation
   * would therefore be swallowed in the bubble phase and do nothing at all.
   * Capture runs before React dispatches any of that, and `stopPropagation`
   * keeps the renderer's hash handling from firing afterwards.
   */
  useEffect(() => {
    const onClick = (event: MouseEvent) => {
      // Leave modified clicks to the browser — a user opening a citation in a
      // new tab is asking for the link, not for the reader to move.
      if (event.button !== 0) return;
      if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
        return;
      const element = event.target as HTMLElement | null;
      const anchor = element?.closest?.("a[href]") as HTMLAnchorElement | null;
      const citation = citationTargetFromHref(anchor?.getAttribute("href"));
      if (!citation) return;
      event.preventDefault();
      event.stopPropagation();
      void navigateCitation(anchor?.getAttribute("href"));
    };
    document.addEventListener("click", onClick, true);
    return () => document.removeEventListener("click", onClick, true);
  }, [navigateCitation]);

  // -- annotations ---------------------------------------------------------

  const commitSelection = useCallback(
    (
      kind: "highlight" | "underline" | "note" | "citation",
      color: AnnotationColor,
      note = "",
    ) => {
      if (!selection || !material) return;
      const temporaryId = `pending-${Date.now()}-${Math.round(Math.random() * 1e6)}`;
      const now = Date.now() / 1000;
      void saveMark(
        {
          locator: selection.locator,
          kind: kind === "note" ? "highlight" : kind,
          color,
          quote: selection.quote,
          note,
          rects: selection.rects,
          source_anchor: selection.sourceAnchor ?? "",
          selectors: selection.selectors ?? [],
        },
        {
          annotation_id: temporaryId,
          locator: selection.locator,
          material_revision: material.revision ?? 1,
          kind: kind === "note" ? "highlight" : kind,
          color,
          quote: selection.quote,
          note,
          rects: selection.rects,
          source_anchor: selection.sourceAnchor ?? "",
          selectors: selection.selectors ?? [],
          author: "user",
          created_at: now,
          updated_at: now,
        },
      );
      clearSelection();
      window.getSelection()?.removeAllRanges();
    },
    [selection, material, saveMark, clearSelection],
  );

  // The text a question about the selection carries: the reading text where
  // the view could tell it apart from the page furniture (margin line
  // numbers), the raw selection otherwise. Marks keep the raw text, which is
  // what re-anchors them on the page.
  const selectionText = selection ? selection.text || selection.quote : "";

  const askAboutSelection = useCallback(
    (prompt?: string) => {
      if (!selection || !material) return;
      window.dispatchEvent(
        new CustomEvent(READER_ASK_EVENT, {
          detail: {
            quote: selectionText,
            locator: selection.locator,
            unit: material.unit,
            ...(prompt ? { prompt } : {}),
          },
        }),
      );
      clearSelection();
      window.getSelection()?.removeAllRanges();
    },
    [selection, selectionText, material, clearSelection],
  );

  // Inside a workspace the selection's AI actions sit on the popover, next to
  // the text they act on. Explain, translate and guide are messages in the
  // reading conversation (see reading-passage-prompts); an installed
  // extension's own selection actions follow them and answer as cards.
  const readingActions = useReadingActions();
  const aiActions = useMemo<PopoverAiAction[] | undefined>(() => {
    if (!readingActions || readingActions.ageMode !== "default") return undefined;
    if (!selection || !material) return undefined;
    const target = { locator: selection.locator, selection: selectionText };
    const prompts = passagePrompts(selectionText, i18n.language, t).map(
      (prompt): PopoverAiAction => ({
        key: prompt.key,
        label: prompt.label,
        title: prompt.message,
        onClick: () => askAboutSelection(prompt.message),
      }),
    );
    const extensions = readingActions.actions
      .filter((entry) => entry.needsSelection)
      .map(
        (entry: ReadingActionEntry): PopoverAiAction => ({
          key: entry.key,
          label: entry.label,
          title: entry.label,
          onClick: () => {
            void readingActions.run(entry, target);
            clearSelection();
            window.getSelection()?.removeAllRanges();
          },
        }),
      );
    return [...prompts, ...extensions];
  }, [
    readingActions,
    selection,
    selectionText,
    material,
    askAboutSelection,
    clearSelection,
    i18n.language,
    t,
  ]);

  // -- export --------------------------------------------------------------

  const runExport = useCallback(async () => {
    if (!material || exporting) return;
    setExporting(true);
    dismissError();
    try {
      const { blob, filename } = await fetchExport(material.material_id);
      const url = URL.createObjectURL(blob);
      const anchor = document.createElement("a");
      anchor.href = url;
      anchor.download = filename;
      document.body.appendChild(anchor);
      anchor.click();
      anchor.remove();
      // Revoke on the next frame: revoking synchronously can cancel the download
      // in some browsers before it has read the blob.
      window.setTimeout(() => URL.revokeObjectURL(url), 1000);
    } catch (error) {
      setError(error instanceof Error ? error.message : t("Export failed."));
    } finally {
      setExporting(false);
    }
  }, [material, exporting, t, dismissError, setError]);

  // -- render --------------------------------------------------------------

  const showAnnotations = annotationPanel ?? annotations.length > 0;
  const unitWord = material ? t(unitLabel(material.unit)) : "";
  const isEpub = material?.render_mode === "epub";
  const currentUnitTitle = isEpub
    ? material?.unit_refs.find((row) => row.locator === currentLocator)?.title
    : undefined;
  const epubProgress = epubPosition?.materialId === material?.material_id
    && epubPosition?.percentage != null
    ? Math.round(epubPosition.percentage * 100) : null;
  const bookmarkedHere = bookmarks.some(
    (row) => row.locator === currentLocator,
  );
  const materialJump =
    material && jumpMaterialIdRef.current === material.material_id
      ? jump
      : null;

  // Inside a workspace these go to the top bar's ⋯, next to the collection's
  // and the conversation's actions; standing alone, the pane keeps its own.
  const hasHistory = locationHistory.entries.length > 0;
  const menuItems = useMemo<WorkspaceMenuItem[] | null>(() => {
    if (!material) return null;
    const items: WorkspaceMenuItem[] = [];
    if (hasHistory) {
      items.push({
        key: "history",
        icon: History,
        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",
      icon: Crosshair,
      label: t("Follow the assistant"),
      hint: autoJump
        ? t("Auto-jump on — the view follows what the assistant reads")
        : t("Auto-jump off — the assistant will not move your view"),
      active: autoJump,
      onSelect: toggleAutoJump,
    });
    if (ownAnnotationList) {
      items.push({
        key: "annotations",
        icon: showAnnotations ? PanelRightClose : PanelRightOpen,
        label: t("Annotations"),
        active: showAnnotations,
        onSelect: () => setAnnotationPanel(!showAnnotations),
      });
    }
    items.push({
      key: "export",
      icon: exporting ? Loader2 : Download,
      label: t("Export annotated file"),
      spinning: exporting,
      disabled: exporting,
      onSelect: () => void runExport(),
    });
    return items;
  }, [
    autoJump,
    exporting,
    hasHistory,
    locationHistory,
    material,
    ownAnnotationList,
    runExport,
    showAnnotations,
    stepHistory,
    t,
    toggleAutoJump,
  ]);
  const menuHosted = useWorkspaceMenuSection("material", menuItems);

  return (
    <div className="dt-reader-pane relative flex h-full min-w-0 flex-col bg-[var(--background)]">
      <ReaderHead slot={headSlot}>
        {/* Under the workspace's bar the document is a crumb of that bar
            (it switches between the collection's files), so the head only
            brings its place, history and bookmark. */}
        {!headSlot && (
          <>
            <FileText
              size={14}
              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
                "65228f9f372d6e9b.md" for every page the learner opened — the one
                place in the reader that names what they are reading, spelling it
                as a checksum. The filename is worth keeping for uploads, where it
                is what the learner recognises, so it stays as the tooltip. */}
            <span
              className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-[var(--foreground)]"
              title={material?.filename || material?.title}
            >
              {material?.title || material?.filename || t("Immersive reading")}
            </span>
          </>
        )}

        {/* Back and Forward stay in the bar because they are how a learner
            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 ⋯.
            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
              icon={ArrowLeft}
              label={t("Back")}
              disabled={locationHistory.index <= 0}
              onClick={() => stepHistory(-1)}
            />
            <HeaderButton
              icon={ArrowRight}
              label={t("Forward")}
              disabled={
                locationHistory.index < 0 ||
                locationHistory.index >= locationHistory.entries.length - 1
              }
              className="hidden md:inline-flex"
              onClick={() => stepHistory(1)}
            />
          </>
        )}

        {material && (
          <>
            {/* 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. 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">
                    {currentUnitTitle || material.title}
                  </span>
                  {epubProgress !== null && <span>{` · ${epubProgress}%`}</span>}
                </>
              ) : (
                t("{{unit}} {{n}} / {{total}}", {
                  unit: unitWord,
                  n: currentLocator,
                  total: material.unit_count,
                })
              )}
            </span>
            {onToggleBookmark && (
              <HeaderButton
                icon={bookmarkedHere ? BookmarkCheck : Bookmark}
                label={
                  bookmarkedHere
                    ? t("Remove the bookmark on this {{unit}}", {
                        unit: unitWord.toLocaleLowerCase(),
                      })
                    : t("Bookmark this {{unit}}", {
                        unit: unitWord.toLocaleLowerCase(),
                      })
                }
                active={bookmarkedHere}
                onClick={() => onToggleBookmark(currentLocator)}
              />
            )}
            {!menuHosted && (
              <HeaderButton
                icon={MoreHorizontal}
                label={t("More")}
                active={showMoreTools}
                menu
                buttonRef={moreToolsButtonRef}
                onClick={() => {
                  setShowMoreTools(!showMoreTools);
                  if (!showMoreTools) setShowHistory(false);
                }}
              />
            )}
          </>
        )}
      </ReaderHead>

      {showMoreTools && material && !menuHosted && (
        <div
          ref={moreToolsMenuRef}
          role="menu"
          aria-label={t("More")}
          className={`absolute ${headSlot ? "top-2" : "top-11"} right-2 z-40 w-64 rounded-xl border border-[var(--border)] bg-[var(--background)] p-1.5 shadow-xl`}
        >
          {locationHistory.entries.length > 0 && (
            <MenuToolButton
              icon={History}
              label={t("History")}
              onClick={() => {
                setShowHistory(true);
                setShowMoreTools(false);
              }}
            />
          )}
          {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")}
            hint={
              autoJump
                ? t("Auto-jump on — the view follows what the assistant reads")
                : t("Auto-jump off — the assistant will not move your view")
            }
            active={autoJump}
            onClick={toggleAutoJump}
          />
          {ownAnnotationList && (
            <MenuToolButton
              icon={showAnnotations ? PanelRightClose : PanelRightOpen}
              label={t("Annotations")}
              active={showAnnotations}
              onClick={() => {
                setAnnotationPanel(!showAnnotations);
                setShowMoreTools(false);
              }}
            />
          )}
          <div className="my-1 h-px bg-[var(--border)]" aria-hidden />
          <MenuToolButton
            icon={exporting ? Loader2 : Download}
            label={t("Export annotated file")}
            spinning={exporting}
            onClick={() => {
              void runExport();
              setShowMoreTools(false);
            }}
          />
        </div>
      )}

      {showHistory && locationHistory.entries.length > 0 && (
        <div
          ref={historyPanelRef}
          className={`absolute ${headSlot ? "top-2" : "top-11"} right-2 z-30 max-h-72 w-72 overflow-y-auto rounded-xl border border-[var(--border)] bg-[var(--background)] p-1.5 shadow-xl`}>
          {[...locationHistory.entries]
            .map((entry, index) => ({ entry, index }))
            .reverse()
            .map(({ entry, index }) => {
              const unavailable = unavailableMaterials.has(entry.materialId);
              return (
                <button
                  key={`${entry.materialId}:${entry.locator}:${index}`}
                  type="button"
                  aria-current={
                    index === locationHistory.index ? "location" : undefined
                  }
                  onClick={() => selectHistoryEntry(index)}
                  className={`flex w-full items-start gap-2 rounded-lg px-2.5 py-2 text-left transition hover:bg-[var(--muted)] ${
                    index === locationHistory.index
                      ? "bg-[color-mix(in_srgb,var(--primary)_10%,transparent)] text-[var(--primary)]"
                      : "text-[var(--foreground)]"
                  }`}
                >
                  <span className="min-w-0 flex-1">
                    <span className="block truncate text-[11.5px] font-medium">
                      {entry.title}
                    </span>
                    <span className="block truncate font-mono text-[10px] text-[var(--muted-foreground)]">
                      {t(unitLabel(entry.source?.unit || "section"))}{" "}
                      {entry.locator}
                      {unavailable ? ` · ${t("Unavailable")}` : ""}
                    </span>
                  </span>
                </button>
              );
            })}
        </div>
      )}

      {notice && (
        <div
          role="alert"
          className="flex items-start gap-2 border-b border-[color-mix(in_srgb,var(--destructive)_25%,transparent)] bg-[var(--destructive)]/[0.06] px-3 py-2"
        >
          <p className="flex-1 text-[11.5px] leading-relaxed text-[var(--destructive)]">
            {notice}
          </p>
          <button
            type="button"
            onClick={dismissError}
            className="text-[color-mix(in_srgb,var(--destructive)_70%,transparent)] transition hover:text-[var(--destructive)]"
            aria-label={t("Dismiss")}
          >
            <X size={12} />
          </button>
        </div>
      )}

      {material && (
        <ReadingExtensionBar
          materialId={material.material_id}
          locator={currentLocator}
          selectionLocator={selection?.locator}
          selection={selection?.quote}
          sessionId={sessionId}
          onError={setError}
        />
      )}

      <div className="relative flex min-h-0 flex-1">
        <div className="min-w-0 flex-1">
          {loadingMaterial ? (
            <div className="flex h-full items-center justify-center gap-2 text-[12px] text-[var(--muted-foreground)]">
              <Loader2 size={14} className="animate-spin" />
              {t("Opening document…")}
            </div>
          ) : !material ? (
            <div className="flex h-full flex-col items-center justify-center gap-1 px-6 text-center">
              <p className="text-[12.5px] text-[var(--muted-foreground)]">
                {t("This document could not be opened.")}
              </p>
              <button
                type="button"
                onClick={onClose}
                className="text-[11.5px] font-medium text-[var(--primary)] underline-offset-2 hover:underline"
              >
                {t("Back to the library")}
              </button>
            </div>
          ) : material.render_mode === "epub" ? (
            <EpubDocumentView
              key={material.material_id}
              materialId={material.material_id}
              unitCount={material.unit_count}
              unitRefs={material.unit_refs}
              annotations={annotations}
              jump={materialJump}
              highlightedAnnotationId={activeAnnotationId}
              onSelection={openSelection}
              onAnnotationClick={(annotation) =>
                setActiveAnnotationId(annotation.annotation_id)
              }
              onVisibleLocatorChange={handleVisibleLocator}
              onProgressChange={handleEpubProgress}
              onHeadingsChange={onHeadingsChange}
              headingJump={headingJump}
              onError={setError}
            />
          ) : material.has_raw_view ? (
            <PdfDocumentView
              key={material.material_id}
              materialId={material.material_id}
              unitCount={material.unit_count}
              annotations={annotations}
              jump={materialJump}
              highlightedAnnotationId={activeAnnotationId}
              onSelection={openSelection}
              onAnnotationClick={(annotation) =>
                setActiveAnnotationId(annotation.annotation_id)
              }
              onVisibleLocatorChange={handleVisibleLocator}
            />
          ) : (
            <TextUnitView
              key={material.material_id}
              materialId={material.material_id}
              unit={material.unit}
              unitCount={material.unit_count}
              contentFormat={material.content_format}
              annotations={annotations}
              jump={materialJump}
              highlightedAnnotationId={activeAnnotationId}
              onSelection={openSelection}
              onAnnotationClick={(annotation) =>
                setActiveAnnotationId(annotation.annotation_id)
              }
              onVisibleLocatorChange={handleVisibleLocator}
              onHeadingsChange={onHeadingsChange}
              onActiveHeadingChange={onActiveHeadingChange}
              headingJump={headingJump}
            />
          )}
        </div>

        {material && ownAnnotationList && showAnnotations && (
          <aside className="hidden w-[248px] shrink-0 bg-[var(--background)] lg:block">
            <AnnotationList
              annotations={annotations}
              unit={material.unit}
              activeId={activeAnnotationId}
              onSelect={(annotation) => {
                setActiveAnnotationId(annotation.annotation_id);
                requestJump(annotation.locator, annotation.quote || undefined);
              }}
              onDelete={(annotation) => void removeMark(annotation)}
            />
          </aside>
        )}
      </div>

      {/* `popoverOpen` and not just `selection`: dismissal now leaves the
          selection in place for the toolbar, so gating the mount on the
          selection alone would make Escape and outside-click stop working. */}
      {popoverOpen && selection && material && (
        <AnnotationPopover
          anchor={selection.anchor}
          quote={selection.quote}
          noteSource={{title: `${material.title} · ${unitLabel(material.unit)} ${selection.locator}`, url: scopedUrl(window.location.pathname + window.location.search) + readingPassageHref(material.material_id, selection.locator, material.revision), id: `${material.material_id}:${selection.locator}`}}
          onHighlight={(color) => commitSelection("highlight", color)}
          onUnderline={(color) => commitSelection("underline", color)}
          onNote={(note, color) => commitSelection("note", color, note)}
          onCitation={(color) => commitSelection("citation", color)}
          onAsk={() => askAboutSelection()}
          aiActions={aiActions}
          // Closes the popover WITHOUT dropping the selection, so the
          // toolbar's selection-gated actions stay reachable.
          onDismiss={() => setPopoverOpen(false)}
        />
      )}
    </div>
  );
}

function HeaderButton({
  icon: Icon,
  label,
  onClick,
  active,
  spinning,
  disabled,
  menu = false,
  buttonRef,
  className = "",
}: {
  icon: typeof FileText;
  label: string;
  onClick: () => void;
  active?: boolean;
  spinning?: boolean;
  disabled?: boolean;
  menu?: boolean;
  buttonRef?: RefObject<HTMLButtonElement | null>;
  className?: string;
}) {
  return (
    <Tooltip label={label} suppressed={Boolean(menu && active)}>
      <button
        ref={buttonRef}
        type="button"
        aria-label={label}
        aria-pressed={menu ? undefined : active}
        aria-haspopup={menu ? "menu" : undefined}
        aria-expanded={menu ? active : undefined}
        disabled={spinning || disabled}
        onClick={onClick}
        className={`h-7 w-7 shrink-0 items-center justify-center rounded-lg transition disabled:cursor-default ${
          className || "inline-flex"
        } ${
          active
            ? "bg-[color-mix(in_srgb,var(--primary)_12%,transparent)] text-[var(--primary)]"
            : "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-35 disabled:hover:bg-transparent"
        }`}
      >
        <Icon size={14} className={spinning ? "animate-spin" : undefined} />
      </button>
    </Tooltip>
  );
}

function MenuToolButton({
  icon: Icon,
  label,
  onClick,
  active,
  spinning,
  disabled,
  hint,
  className = "",
}: {
  icon: typeof FileText;
  label: string;
  onClick: () => void;
  active?: boolean;
  spinning?: boolean;
  disabled?: boolean;
  /** A second line saying what the setting currently does. */
  hint?: string;
  className?: string;
}) {
  return (
    <button
      type="button"
      role={active === undefined ? "menuitem" : "menuitemcheckbox"}
      aria-label={hint ? `${label}. ${hint}` : label}
      aria-checked={active}
      disabled={spinning || disabled}
      onClick={onClick}
      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"
      }`}
    >
      <Icon
        size={14}
        className={
          spinning
            ? "animate-spin text-[var(--muted-foreground)]"
            : "text-[var(--muted-foreground)]"
        }
      />
      <span className="min-w-0 flex-1">
        <span className="block truncate">{label}</span>
        {hint ? (
          <span className="block text-[10.5px] leading-snug opacity-75">
            {hint}
          </span>
        ) : null}
      </span>
    </button>
  );
}

/** The title row: in the host's bar when it offers one, else atop the pane. */
function ReaderHead({ slot, children }: { slot: HTMLElement | null; children: ReactNode }) {
  if (slot) return createPortal(children, slot);
  return (
    <header className="dt-reader-head flex h-11 shrink-0 items-center gap-1 px-3">
      {children}
    </header>
  );
}