),
},
);
interface ReaderAskDetail {
quote?: string;
locator?: number;
unit?: string;
/** Send this about the passage now, instead of waiting for a question. */
prompt?: string;
}
export function ReadingWorkspacePage() {
const params = useParams<{ workspaceId: string }>();
const workspaceId = params.workspaceId;
// From the path, not from route params: the first turn binds its session id
// with the native history API so the workspace is not torn down mid-answer,
// and `useParams` does not follow that — `usePathname` does.
const sessionIdParam = readingSessionIdFromPath(usePathname());
const router = useRouter();
const { t } = useTranslation();
// The shell only needs to *send* (guided one-click prompts). Rendering the
// transcript, editing, branching and cancelling all belong to the companion,
// which reads them off the same context.
const { state, sendMessage } = useChatStateAdapter();
const {
workspace,
setWorkspace,
conversations,
setConversations,
loading,
error,
notice,
refreshConversations,
setNotice,
material,
annotations,
activeTab,
activeConversation,
linkedSessionIds,
activeLocator,
setActiveLocator,
bookmarks,
toggleBookmark,
removeBookmark,
transcript,
organizedNotes,
setOrganizedNotes,
refresh,
switchMaterial,
removeMaterial,
newConversation,
organizeNotes,
buildMasteryPath,
renameWorkspace,
reportViewport,
} = useReadingWorkspace(workspaceId, sessionIdParam);
// View-only state: what the reader is pointing at and which panels are open.
const [transcriptSearch, setTranscriptSearch] = useState("");
const [selection, setSelection] = useState<{
quote: string;
locator: number;
} | null>(null);
const prefillInputRef = useRef<((text: string) => void) | null>(null);
const [isDesktopWide, setIsDesktopWide] = useState(false);
// Where each panel stops being a sheet over the document and takes its own
// column. Two thresholds, because the two panels dock at different widths:
// the navigator at `lg`, the companion at `xl` — the same two screens the
// grid's `lg:`/`xl:` classes use. The layout hook needs them as state rather
// than as CSS, since it reserves columns in pixels and must not do that while
// the panel it would size is still an overlay.
const [isDocked, setIsDocked] = useState(false);
// The bar's place for the open document's title row (see ReaderPane).
const [docSlot, setDocSlot] = useState(null);
useEffect(() => {
const docked = window.matchMedia("(min-width: 1024px)");
const wide = window.matchMedia("(min-width: 1280px)");
const update = () => {
setIsDocked(docked.matches);
setIsDesktopWide(wide.matches);
};
update();
docked.addEventListener("change", update);
wide.addEventListener("change", update);
return () => {
docked.removeEventListener("change", update);
wide.removeEventListener("change", update);
};
}, []);
const [showSessions, setShowSessions] = useState(false);
const [showLinker, setShowLinker] = useState(false);
// Stable: the companion hands it to the workspace ⋯ inside memoised items,
// and a fresh arrow every render re-registered them forever.
const openLinker = useCallback(() => setShowLinker(true), []);
const [showNotebook, setShowNotebook] = useState(false);
const [showAddSource, setShowAddSource] = useState(false);
const { host: menuHost, sections: menuSections } = useWorkspaceMenuHost();
const [showRename, setShowRename] = useState(false);
const [showMastery, setShowMastery] = useState(false);
const collectionMenu = useMemo(
() => [
{
key: "organize",
icon: StickyNote,
label: t("Organize notes"),
onSelect: () => void organizeNotes(),
},
{
key: "notebook",
icon: NotebookPen,
label: t("Send to Notebook"),
onSelect: () => setShowNotebook(true),
},
{
key: "mastery",
icon: GraduationCap,
label: t("Build Mastery Path"),
onSelect: () => setShowMastery(true),
},
],
[organizeNotes, t],
);
const [removeTarget, setRemoveTarget] =
useState(null);
const {
closeLearning,
companionOpen,
learning,
mainRef,
navigatorOpen: preferredNavigatorOpen,
openLearning,
setCompanionOpen: setPreferredCompanionOpen,
setNavigatorOpen,
} = useReadingLearningMode(workspaceId);
const { gridRef, ...panels } = useReadingPanelLayout({
// The navigator owns a column from `lg`; the companion only from `xl`.
enabled: isDocked,
navigatorOpen: preferredNavigatorOpen,
companionOpen,
companionDocked: isDesktopWide,
});
const { navigatorOpen, exitFocus } = panels;
const companionDocked = isDesktopWide && companionOpen;
const setCompanionOpen = useCallback(
(open: boolean) => {
if (!open) exitFocus();
setPreferredCompanionOpen(open);
},
[exitFocus, setPreferredCompanionOpen],
);
const [documentJump, setDocumentJump] = useState(null);
const [pageHeadings, setPageHeadings] = useState([]);
const [activeHeadingId, setActiveHeadingId] = useState(null);
const [headingJump, setHeadingJump] = useState<{
id: string;
nonce: number;
locator?: number;
sourceHref?: string;
} | null>(null);
useEffect(() => {
// On narrower screens the source remains the base layer. The outline and
// companion open as intentional sheets instead of squeezing the reader
// into an unusable three-column layout.
const frame = window.requestAnimationFrame(() => {
if (!window.matchMedia("(min-width: 1280px)").matches) {
setCompanionOpen(false);
}
});
return () => window.cancelAnimationFrame(frame);
}, [setCompanionOpen]);
// The two panels are independent wherever at least one of them docks:
// opening one used to close the other at every width, so a learner could
// never see the outline and the conversation together. Below `lg` both are
// sheets over the document, and two sheets at once is just a mess.
const toggleNavigator = useCallback(
(open: boolean) => {
exitFocus();
if (open && !window.matchMedia("(min-width: 1024px)").matches) {
setCompanionOpen(false);
}
setNavigatorOpen(open);
},
[exitFocus, setCompanionOpen, setNavigatorOpen],
);
const toggleCompanion = useCallback(
(open: boolean) => {
if (open && !window.matchMedia("(min-width: 1024px)").matches) {
setNavigatorOpen(false);
}
setCompanionOpen(open);
},
[setCompanionOpen, setNavigatorOpen],
);
useEffect(() => {
const onAsk = (event: Event) => {
const detail = (event as CustomEvent).detail;
const quote = String(detail?.quote ?? "").trim();
if (!quote) return;
const locator = Number(detail.locator || activeLocator);
const prompt = String(detail?.prompt ?? "").trim();
toggleCompanion(true);
// Explain / translate / guide: a message in this conversation, sent
// now, with the passage attached the same way a typed question gets it.
// A turn still streaming, or a mode that wants its settings confirmed
// first, gets the passage and the words in the box instead of a send
// that would be refused or would run the wrong mode.
if (
prompt &&
!state.isStreaming &&
!workspaceActionNeedsConfiguration(state.activeCapability)
) {
setReadingViewport({ locator, selection: quote });
sendMessage(prompt, undefined, undefined, undefined, linkedSessionIds);
setSelection(null);
window.setTimeout(() => setReadingViewport({ selection: "" }), 0);
return;
}
setSelection({ quote, locator });
setReadingViewport({ locator, selection: quote });
if (prompt) {
window.requestAnimationFrame(() => prefillInputRef.current?.(prompt));
return;
}
// Focus, not `prefillInputRef("")`: that one *sets* the text, and
// "Ask about this" used to wipe whatever the learner had half-typed.
// A frame later, because a closed companion is not mounted yet.
window.requestAnimationFrame(focusReadingComposer);
};
window.addEventListener(READER_ASK_EVENT, onAsk);
return () => window.removeEventListener(READER_ASK_EVENT, onAsk);
}, [
activeLocator,
linkedSessionIds,
sendMessage,
state.activeCapability,
state.isStreaming,
toggleCompanion,
]);
// "Quiz me": a quiz turn in this conversation, run by the same engine as
// the composer's Quiz mode, with its settings chosen here instead of asked
// for. The conversation's own mode is left as it was.
const quizThisPage = useCallback(() => {
if (state.isStreaming) return;
toggleCompanion(true);
setReadingViewport({ locator: activeLocator, selection: "" });
sendMessage(
t("Quiz me on this page"),
undefined,
{ ...PAGE_QUIZ_CONFIG },
undefined,
linkedSessionIds,
{ capability: PAGE_QUIZ_CAPABILITY },
);
}, [
activeLocator,
linkedSessionIds,
sendMessage,
state.isStreaming,
t,
toggleCompanion,
]);
if (loading) {
return (
{t("Opening collection…")}
);
}
if (error && !workspace) {
return (
{error}
{t("Back to library")}
);
}
if (!workspace) return null;
const activeExtractor = material?.extractor || "";
const transcriptUnavailable = [
"youtube-no-captions",
"bilibili-no-subtitles",
"bilibili-chapters-only",
].includes(activeExtractor);
const chaptersOnly = activeExtractor === "bilibili-chapters-only";
const isMedia =
activeTab?.material.source_kind === "youtube" ||
activeTab?.material.render_mode === "video" ||
activeTab?.material.render_mode === "audio";
// Panels below their docking width are sheets over the document, and a
// sheet needs a scrim to close it by. The navigator docks at `lg`, the
// companion at `xl`; the scrim used to key on either one being open with a
// single `xl:hidden`, so at `lg` it dimmed a document the docked navigator
// was sitting beside and swallowed every click on the page.
const scrimClass =
companionOpen ? "xl:hidden" : navigatorOpen ? "lg:hidden" : "";
const materialReady =
activeTab?.material.status === "ready" && !isMedia && Boolean(material);
return (
toggleCompanion(true)}
>
{/* One desk: the bar sits over the document columns only, and a docked
companion runs the full height beside them as a sheet of its own. */}