Skip to content

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

fix(web): keep deep book routes in loading state

Gao-Chenkaie9a9e6677573
diff --git a/web/app/(workspace)/books/BooksRoute.tsx b/web/app/(workspace)/books/BooksRoute.tsx
index 816c6d028..a33ffd812 100644
--- a/web/app/(workspace)/books/BooksRoute.tsx
+++ b/web/app/(workspace)/books/BooksRoute.tsx
@@ -35,7 +35,7 @@ import LearningCapturePanel from './components/LearningCapturePanel'
import SpineEditor from './components/SpineEditor'
import type { QuizAttemptArgs } from './components/blocks/QuizBlock'
-type View = 'list' | 'creator' | 'spine' | 'reader'
+type View = 'list' | 'loading' | 'creator' | 'spine' | 'reader'
// Blocks land one at a time during compilation. Coalescing a burst into a
// single fetch keeps a page that is actively generating from issuing one
@@ -73,17 +73,26 @@ export default function BookPage() {
// Keep one loading boundary for the library and its resource routes.
return (
<Suspense
- fallback={
- <div className="flex h-full w-full items-center justify-center text-[var(--muted-foreground)]">
- <Loader2 className="mr-2 h-4 w-4 animate-spin" /> <BookLoadingText />
- </div>
- }
+ fallback={<BookLoadingView />}
>
<BookPageInner />
</Suspense>
)
}
+function BookLoadingView() {
+ return (
+ <div
+ className="flex h-full w-full items-center justify-center text-[var(--muted-foreground)]"
+ role="status"
+ aria-live="polite"
+ aria-busy="true"
+ >
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" /> <BookLoadingText />
+ </div>
+ )
+}
+
function BookLoadingText() {
const { t } = useTranslation()
return <>{t('Loading…')}</>
@@ -98,7 +107,10 @@ function BookPageInner() {
const [books, setBooks] = useState<Book[]>([])
const [canCreateBook, setCanCreateBook] = useState(true)
const [loadingBooks, setLoadingBooks] = useState(false)
- const [view, setView] = useState<View>('list')
+ // A deep resource route already identifies the target book before its
+ // details arrive. Start in a route-level loading shell so the library's
+ // empty state cannot briefly claim that the book collection is the target.
+ const [view, setView] = useState<View>(requestedBookId ? 'loading' : 'list')
const [selectedBookId, setSelectedBookId] = useState<string | null>(null)
const [detail, setDetail] = useState<BookDetail | null>(null)
@@ -386,50 +398,69 @@ function BookPageInner() {
if (!id) {
setSelectedBookId(null)
setDetail(null)
+ setSelectedPageId(null)
setView('list')
if (requestedBookId) router.push(bookRoute())
return
}
+ setView('loading')
const targetPath = bookRoute(id, openPageId)
if (requestedBookId !== id || (openPageId && requestedPageId !== openPageId)) {
router.push(targetPath)
}
setSelectedBookId(id)
- const data = await loadBookDetail(id)
- const hasReadableContent = data.pages.some(
- p => p.status !== 'pending' || (p.block_count ?? p.blocks.length) > 0
- )
- const canEdit = data.book.can_edit !== false
- if (canEdit && data.book.status === 'draft' && data.book.proposal) {
- setPendingBook(data.book)
- setPendingProposal(data.book.proposal)
- setView('creator')
- } else if (
- canEdit &&
- data.book.status === 'spine_ready' &&
- data.spine &&
- !hasReadableContent
- ) {
- // Spine confirmed but nothing built yet — the editor is still the right
- // place. Once any chapter exists, the reader is.
- setView('spine')
- } else {
- // Resume where the reader left off — that's what `current_page_id` is
- // for, and until now nothing ever read it.
- const requested = (openPageId && data.pages.find(p => p.id === openPageId)) || null
- const resumed = data.pages.find(p => p.id === data.progress.current_page_id) || null
- const firstReady = data.pages.find(p => p.status === 'ready') || null
- const target = requested || resumed || firstReady || data.pages[0] || null
- setSelectedPageId(target?.id || null)
- setView('reader')
+ try {
+ const data = await loadBookDetail(id)
+ const hasReadableContent = data.pages.some(
+ p => p.status !== 'pending' || (p.block_count ?? p.blocks.length) > 0
+ )
+ const canEdit = data.book.can_edit !== false
+ if (canEdit && data.book.status === 'draft' && data.book.proposal) {
+ setPendingBook(data.book)
+ setPendingProposal(data.book.proposal)
+ setView('creator')
+ } else if (
+ canEdit &&
+ data.book.status === 'spine_ready' &&
+ data.spine &&
+ !hasReadableContent
+ ) {
+ // Spine confirmed but nothing built yet — the editor is still the right
+ // place. Once any chapter exists, the reader is.
+ setView('spine')
+ } else {
+ // Resume where the reader left off — that's what `current_page_id` is
+ // for, and until now nothing ever read it.
+ const requested = (openPageId && data.pages.find(p => p.id === openPageId)) || null
+ const resumed = data.pages.find(p => p.id === data.progress.current_page_id) || null
+ const firstReady = data.pages.find(p => p.status === 'ready') || null
+ const target = requested || resumed || firstReady || data.pages[0] || null
+ setSelectedPageId(target?.id || null)
+ setView('reader')
+ }
+ } catch (err) {
+ const reason = bookErrorMessage(err, t)
+ notify(reason, {
+ tone: 'error',
+ durationMs: 8000,
+ })
+ console.error('loadBookDetail failed:', err)
+ setSelectedBookId(null)
+ setDetail(null)
+ setSelectedPageId(null)
+ setPendingBook(null)
+ setPendingProposal(null)
+ setView('list')
+ router.replace(bookRoute())
}
},
- [loadBookDetail, requestedBookId, requestedPageId, router]
+ [loadBookDetail, requestedBookId, requestedPageId, router, t]
)
// Resource identity belongs in the path: /books/<book>[/pages/<page>].
useEffect(() => {
if (!requestedBookId) {
+ lastDeepLinkedBookId.current = null
if (selectedBookId) void handleSelectBook(null)
return
}
@@ -953,6 +984,13 @@ function BookPageInner() {
// ── Render ─────────────────────────────────────────────────────────
+ // Route params update before the deep-link effect runs. Treat a mismatched
+ // requested ID as loading immediately, preventing one frame of the previous
+ // book (or the parent library) during client-side navigation as well.
+ if (view === 'loading' || (!!requestedBookId && requestedBookId !== selectedBookId)) {
+ return <BookLoadingView />
+ }
+
return (
<div className="flex h-full w-full">
{view !== 'list' && (
diff --git a/web/tests/book-deep-link-loading.spec.tsx b/web/tests/book-deep-link-loading.spec.tsx
new file mode 100644
index 000000000..8abf9e771
--- /dev/null
+++ b/web/tests/book-deep-link-loading.spec.tsx
@@ -0,0 +1,220 @@
+import { act, render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const fixture = vi.hoisted(() => ({
+ params: {} as { bookId?: string; pageId?: string },
+ get: vi.fn(),
+ list: vi.fn(),
+ getPage: vi.fn(),
+ listLearningCaptures: vi.fn(),
+ markVisited: vi.fn(),
+ push: vi.fn(),
+ replace: vi.fn(),
+ notify: vi.fn(),
+ t: (key: string) => key,
+}));
+
+vi.mock("next/navigation", () => ({
+ useParams: () => fixture.params,
+ useRouter: () => ({
+ push: fixture.push,
+ replace: fixture.replace,
+ }),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: fixture.t,
+ }),
+}));
+
+vi.mock("@/lib/notifications", () => ({
+ notify: fixture.notify,
+}));
+
+vi.mock("@/lib/book-api", () => ({
+ BookApiError: class BookApiError extends Error {
+ status = 500;
+ code?: string;
+ },
+ bookApi: {
+ get: fixture.get,
+ list: fixture.list,
+ getPage: fixture.getPage,
+ listLearningCaptures: fixture.listLearningCaptures,
+ markVisited: fixture.markVisited,
+ },
+}));
+
+vi.mock("@/lib/use-book-stream", () => ({
+ useBookStream: vi.fn(),
+ bookEventKind: () => "",
+ bookEventPageId: () => null,
+}));
+
+vi.mock("@/app/(workspace)/books/components/BookLibrary", () => ({
+ default: () => <div data-testid="book-library" />,
+}));
+vi.mock("@/app/(workspace)/books/components/BookCreator", () => ({
+ default: () => <div data-testid="book-creator" />,
+}));
+vi.mock("@/app/(workspace)/books/components/SpineEditor", () => ({
+ default: () => <div data-testid="spine-editor" />,
+}));
+vi.mock("@/app/(workspace)/books/components/BookSidebar", () => ({
+ default: () => <div data-testid="book-sidebar" />,
+}));
+vi.mock("@/app/(workspace)/books/components/BookGenerationActivity", () => ({
+ default: () => <div data-testid="book-generation" />,
+}));
+vi.mock("@/app/(workspace)/books/components/BookPausedBanner", () => ({
+ default: () => null,
+}));
+vi.mock("@/app/(workspace)/books/components/BookHealthBanner", () => ({
+ default: () => null,
+}));
+vi.mock("@/app/(workspace)/books/components/BookChatPanel", () => ({
+ default: () => null,
+}));
+vi.mock("@/app/(workspace)/books/components/LearningCapturePanel", () => ({
+ default: () => null,
+}));
+vi.mock("@/app/(workspace)/books/components/PageReader", () => ({
+ default: ({ page }: { page?: { id: string } | null }) => (
+ <div data-testid="page-reader">{page?.id || "no-page"}</div>
+ ),
+}));
+
+import BookPage from "@/app/(workspace)/books/BooksRoute";
+
+function readyDetail() {
+ const progress = {
+ current_page_id: null,
+ visited_page_ids: [],
+ bookmarked_page_ids: [],
+ quiz_attempts: {},
+ };
+ return {
+ book: {
+ id: "book-1",
+ title: "A book",
+ status: "ready",
+ can_edit: true,
+ revision: 1,
+ metadata: {},
+ },
+ pages: [
+ {
+ id: "page-1",
+ book_id: "book-1",
+ title: "Chapter one",
+ status: "ready",
+ blocks: [],
+ block_count: 0,
+ },
+ ],
+ spine: null,
+ progress,
+ generation: null,
+ };
+}
+
+beforeEach(() => {
+ fixture.params = {};
+ fixture.get.mockReset();
+ fixture.list.mockReset().mockResolvedValue({ books: [], can_create: true });
+ fixture.getPage.mockReset();
+ fixture.listLearningCaptures
+ .mockReset()
+ .mockResolvedValue({ captures: [] });
+ fixture.markVisited
+ .mockReset()
+ .mockResolvedValue({ progress: readyDetail().progress });
+ fixture.push.mockReset();
+ fixture.replace.mockReset().mockImplementation(() => {
+ fixture.params = {};
+ });
+ fixture.notify.mockReset();
+});
+
+describe("book deep-link loading", () => {
+ it("keeps a direct book URL in a book loading shell until details arrive", async () => {
+ fixture.params = { bookId: "book-1" };
+ let resolveDetails!: (value: ReturnType<typeof readyDetail>) => void;
+ fixture.get.mockReturnValue(
+ new Promise((resolve) => {
+ resolveDetails = resolve;
+ }),
+ );
+
+ render(<BookPage />);
+
+ expect(screen.getByRole("status")).toHaveAttribute("aria-busy", "true");
+ expect(screen.queryByTestId("book-library")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("book-sidebar")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("book-generation")).not.toBeInTheDocument();
+
+ await act(async () => {
+ resolveDetails(readyDetail());
+ });
+
+ expect(await screen.findByTestId("page-reader")).toHaveTextContent("page-1");
+ expect(screen.queryByRole("status")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("book-library")).not.toBeInTheDocument();
+ });
+
+ it("opens the requested page directly after a page deep link loads", async () => {
+ fixture.params = { bookId: "book-1", pageId: "page-1" };
+ fixture.get.mockResolvedValue(readyDetail());
+
+ render(<BookPage />);
+
+ expect(screen.getByRole("status")).toBeInTheDocument();
+ expect(await screen.findByTestId("page-reader")).toHaveTextContent("page-1");
+ expect(screen.queryByTestId("book-library")).not.toBeInTheDocument();
+ });
+
+ it("still renders the library at the books root route", async () => {
+ let resolveBooks!: (value: { books: never[]; can_create: boolean }) => void;
+ fixture.list.mockReturnValue(
+ new Promise((resolve) => {
+ resolveBooks = resolve;
+ }),
+ );
+
+ render(<BookPage />);
+
+ expect(screen.getByTestId("book-library")).toBeInTheDocument();
+ expect(screen.queryByRole("status")).not.toBeInTheDocument();
+
+ await act(async () => {
+ resolveBooks({ books: [], can_create: true });
+ });
+ });
+
+ it("leaves loading and returns to the library when the book cannot be loaded", async () => {
+ fixture.params = { bookId: "missing-book" };
+ fixture.get.mockRejectedValue(new Error("Book not found"));
+ let resolveBooks!: (value: { books: never[]; can_create: boolean }) => void;
+ fixture.list.mockReturnValue(
+ new Promise((resolve) => {
+ resolveBooks = resolve;
+ }),
+ );
+
+ render(<BookPage />);
+
+ await waitFor(() => {
+ expect(fixture.replace).toHaveBeenCalledWith("/books");
+ expect(screen.getByTestId("book-library")).toBeInTheDocument();
+ });
+ await act(async () => {
+ resolveBooks({ books: [], can_create: true });
+ });
+ expect(screen.queryByRole("status")).not.toBeInTheDocument();
+ expect(fixture.notify).toHaveBeenCalledWith("Book not found", {
+ tone: "error",
+ durationMs: 8000,
+ });
+ });
+});