Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ jobs:
# ad-hoc defaults (13.11). Diverges from ci.yml's test matrix by design.
- os: macos
arch: universal
runner: macos-14
runner: macos-15
rust-target: aarch64-apple-darwin
rust-extra: x86_64-apple-darwin
napi-script: build:darwin-arm64
Expand Down
17 changes: 17 additions & 0 deletions apps/books/src/app.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,23 @@ describe("BooksApp shelf", () => {
expect(el.querySelector(".books__page")?.textContent).toContain("Anchor");
});

// The inspector read the stored fraction as a bare number ("45") while the
// footer showed the live one ("23% read"); both now come from the reader.
it("shows the reader's live progress in the inspector, as a percentage", async () => {
const el = await renderApp();
const footer = /(\d+)%/.exec(el.querySelector(".books__progress")?.textContent ?? "")?.[1];
expect(footer).toBeDefined();
expect(Number(footer)).toBeGreaterThan(0);
expect(el.querySelector(".bs-cell-progress-text")?.textContent).toBe(`${footer}%`);
});

it("carries no Pages row for a reflowable book — the footer owns the page count", async () => {
const el = await renderApp();
const labels = [...el.querySelectorAll(".bs-props__row-label")].map((n) => n.textContent);
expect(labels).toContain("Progress");
expect(labels).not.toContain("Pages");
});

// F-487 — the shared `.bs-props` inspector is `position: fixed`, so it
// takes no layout space. Books centres a full-bleed reading measure under
// it, so with the panel open every line ran on underneath: paragraphs read
Expand Down
22 changes: 17 additions & 5 deletions apps/books/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ import {
} from "./logic/book-open";
import { makePositionPersister, removeBookEntity, writeBookPatch } from "./logic/book-writes";
import { parseEpub } from "./logic/epub-parser";
import { booksFromEntities } from "./logic/library";
import { type LiveProgress, booksFromEntities, withLiveProgress } from "./logic/library";
import { type PdfInfo, pdfEnrichmentPatch } from "./logic/pdf-metadata";
import { SAMPLE_BOOK_CONTENT, sampleBook } from "./logic/sample-book";
import { type TocEntry, tocFromContent, tocFromPdfOutline } from "./logic/toc";
Expand Down Expand Up @@ -283,6 +283,7 @@ export function BooksApp(): ReactElement {
const [openNonce, setOpenNonce] = useState(0);
const [status, setStatus] = useState<ReaderStatus>(ReaderStatus.Idle);
const [toc, setToc] = useState<readonly TocEntry[]>([]);
const [liveProgress, setLiveProgress] = useState<LiveProgress | null>(null);
const [showLibrary, setShowLibrary] = useState(true);
const libraryAutoHide = useAutoHidePanel({ side: PanelSide.Left, collapsed: !showLibrary });
const [showInspector, setShowInspector] = useState(readInspectorPref);
Expand Down Expand Up @@ -380,10 +381,13 @@ export function BooksApp(): ReactElement {
);

const isSample = selectedId === SAMPLE_BOOK_ID;
const shelf = useMemo(() => withLiveProgress(books, liveProgress), [books, liveProgress]);
const selectedBook = useMemo(() => {
if (isSample) return sample.current;
return selectedId ? (books.find((b) => b.id === selectedId) ?? null) : null;
}, [isSample, selectedId, books]);
if (isSample) {
return sample.current ? (withLiveProgress([sample.current], liveProgress)[0] ?? null) : null;
}
return selectedId ? (shelf.find((b) => b.id === selectedId) ?? null) : null;
}, [isSample, selectedId, shelf, liveProgress]);
// PRES-3 — who's-here on the open book (vault rows only; not the sample).
const bookPeers = usePresence(
isSample ? null : (selectedBook?.id ?? null),
Expand Down Expand Up @@ -461,16 +465,22 @@ export function BooksApp(): ReactElement {
if (!stage || !controls) return undefined;

setToc([]);
setLiveProgress(null);

if (selectedId === null) {
stage.replaceChildren();
setStatus(ReaderStatus.Idle);
return undefined;
}

const reportProgress = (progress: number): void => {
if (seq === openSeqRef.current) setLiveProgress({ bookId: selectedId, progress });
};

if (selectedId === SAMPLE_BOOK_ID) {
const handle = mountReader(stage, controls, SAMPLE_BOOK_CONTENT, {
bookId: SAMPLE_BOOK_ID,
onProgressChange: reportProgress,
});
readerRef.current = { dispose: handle.dispose, goTo: handle.goTo };
setToc(tocFromContent(SAMPLE_BOOK_CONTENT));
Expand Down Expand Up @@ -522,6 +532,7 @@ export function BooksApp(): ReactElement {
bookId: book.id,
initialPosition: book.reading.position,
onPositionChange: persist,
onProgressChange: reportProgress,
});
readerRef.current = { dispose: handle.dispose, goTo: handle.goTo };
setToc(tocFromContent(content));
Expand All @@ -543,6 +554,7 @@ export function BooksApp(): ReactElement {
const handle = mountPdfReader(stage, controls, title, port, {
initialPosition: book.reading.position,
onPositionChange: persist,
onProgressChange: reportProgress,
onOpenLink: (url) => {
// Route page links through the `open` intent so web URLs land
// in the browser app (the registered `https` opener) — Books
Expand Down Expand Up @@ -880,7 +892,7 @@ export function BooksApp(): ReactElement {
data-inspector-open={selectedBook && subject && showInspector ? "true" : "false"}
>
<LibraryPanel
books={books}
books={shelf}
selectedId={selectedId}
open={libraryAutoHide.visible}
autoHide={libraryAutoHide.panelProps}
Expand Down
22 changes: 19 additions & 3 deletions apps/books/src/logic/book-properties.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { PropertyFormat } from "@brainstorm-os/sdk-types";
import { describe, expect, it } from "vitest";
import { BookFormat } from "../types/book";
import { makeLocator } from "../types/locator";
Expand Down Expand Up @@ -27,12 +28,12 @@ function fixtureBook() {
}

describe("bookToValues", () => {
it("maps author / format label / pages / 0-100 progress", () => {
it("maps author / format label / pages / whole-percent progress fraction", () => {
const values = bookToValues(fixtureBook());
expect(values[BOOK_PROP_KEY.author]).toBe("Cal Newport");
expect(values[BOOK_PROP_KEY.format]).toBe("PDF");
expect(values[BOOK_PROP_KEY.pages]).toBe(12);
expect(values[BOOK_PROP_KEY.progress]).toBe(42);
expect(values[BOOK_PROP_KEY.progress]).toBe(0.42);
});

it("hides the page count for a book without a measured spine", () => {
Expand All @@ -56,8 +57,23 @@ describe("applyBookPropertyValue", () => {
});

describe("bookPropertyDefs", () => {
// The bare-number cell rendered "45" beside a footer reading "45% read".
it("formats progress as a percentage over a 0..1 range", () => {
const def = bookPropertyDefs(BookFormat.Pdf).find((d) => d.key === BOOK_PROP_KEY.progress);
expect(def?.format).toBe(PropertyFormat.Percent);
expect(def?.range).toEqual({ min: 0, max: 1 });
});

// An EPUB's spine length is its chapter-file count; the reflow reader
// paginates to the viewport, so "Pages 1" sat beside "Page 2 of 8".
it("omits the page count for a reflowable EPUB", () => {
const keys = bookPropertyDefs(BookFormat.Epub).map((d) => d.key);
expect(keys).not.toContain(BOOK_PROP_KEY.pages);
expect(keys).toContain(BOOK_PROP_KEY.progress);
});

it("declares every value-map key exactly once", () => {
const keys = bookPropertyDefs().map((d) => d.key);
const keys = bookPropertyDefs(BookFormat.Pdf).map((d) => d.key);
expect([...keys].sort()).toEqual(Object.values(BOOK_PROP_KEY).sort());
const values = bookToValues(fixtureBook());
for (const key of keys) expect(key in values).toBe(true);
Expand Down
44 changes: 31 additions & 13 deletions apps/books/src/logic/book-properties.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@
* position-persistence path, never edited by hand).
*/

import { type PropertyDef, PropertyView, ValueType } from "@brainstorm-os/sdk-types";
import {
type PropertyDef,
PropertyFormat,
PropertyView,
ValueType,
} from "@brainstorm-os/sdk-types";
import { t } from "../i18n";
import { type Book, BookFormat } from "../types/book";

Expand All @@ -18,19 +23,32 @@ export const BOOK_PROP_KEY = {
progress: "progress",
} as const;

export function bookPropertyDefs(): readonly PropertyDef[] {
return [
/** The rows for a book of `format`. A reflowable EPUB has no page count of
* its own — its `spineLength` counts chapter files and the reader paginates
* to the viewport — so only a fixed-layout PDF carries the Pages row. */
export function bookPropertyDefs(format: BookFormat): readonly PropertyDef[] {
const defs: PropertyDef[] = [
{ key: BOOK_PROP_KEY.author, name: t("prop.author"), icon: null, valueType: ValueType.Text },
{ key: BOOK_PROP_KEY.format, name: t("prop.format"), icon: null, valueType: ValueType.Text },
{ key: BOOK_PROP_KEY.pages, name: t("prop.pages"), icon: null, valueType: ValueType.Number },
{
key: BOOK_PROP_KEY.progress,
name: t("prop.progress"),
];
if (format === BookFormat.Pdf) {
defs.push({
key: BOOK_PROP_KEY.pages,
name: t("prop.pages"),
icon: null,
valueType: ValueType.Number,
display: { view: PropertyView.ProgressBar },
},
];
});
}
defs.push({
key: BOOK_PROP_KEY.progress,
name: t("prop.progress"),
icon: null,
valueType: ValueType.Number,
format: PropertyFormat.Percent,
range: { min: 0, max: 1 },
display: { view: PropertyView.ProgressBar },
});
return defs;
}

export const READONLY_BOOK_PROP_KEYS: ReadonlySet<string> = new Set([
Expand All @@ -44,14 +62,14 @@ const FORMAT_LABEL_KEYS = {
[BookFormat.Epub]: "prop.format.epub",
} as const;

/** Cell values for a book. Progress is 0..100 (the ProgressBar cell's
* default range). */
/** Cell values for a book. Progress is the 0..1 fraction snapped to a whole
* percent, so the cell reads the same number as the shelf row and footer. */
export function bookToValues(book: Book): Record<string, unknown> {
return {
[BOOK_PROP_KEY.author]: book.author,
[BOOK_PROP_KEY.format]: t(FORMAT_LABEL_KEYS[book.format]),
[BOOK_PROP_KEY.pages]: book.spineLength > 0 ? book.spineLength : null,
[BOOK_PROP_KEY.progress]: Math.round(book.reading.progress * 100),
[BOOK_PROP_KEY.progress]: Math.round(book.reading.progress * 100) / 100,
};
}

Expand Down
20 changes: 20 additions & 0 deletions apps/books/src/logic/library.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
filterLibrary,
isInProgress,
sortLibrary,
withLiveProgress,
} from "./library";

const SECTION_LABELS: LibrarySectionLabels = {
Expand Down Expand Up @@ -185,3 +186,22 @@ describe("booksFromEntities", () => {
expect(books[0]?.format).toBe(BookFormat.Pdf);
});
});

// The footer measures progress against the LIVE pagination; the stored
// fraction was measured against whatever viewport last turned a page. Shown
// side by side they disagreed ("45%" in the row, "23% read" in the footer).
describe("withLiveProgress", () => {
const shelf = [reading("a", "A", 0.45, 10), reading("b", "B", 0.8, 20)];

it("shows the open book at the reader's live progress", () => {
const out = withLiveProgress(shelf, { bookId: "a", progress: 0.23 });
expect(out.map((b) => b.reading.progress)).toEqual([0.23, 0.8]);
expect(out[0]?.reading.lastReadAt).toBe(10);
});

it("returns the same list when nothing is live or nothing differs", () => {
expect(withLiveProgress(shelf, null)).toBe(shelf);
expect(withLiveProgress(shelf, { bookId: "a", progress: 0.45 })).toBe(shelf);
expect(withLiveProgress(shelf, { bookId: "zzz", progress: 0.1 })).toBe(shelf);
});
});
21 changes: 21 additions & 0 deletions apps/books/src/logic/library.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,27 @@ export function continueReading(books: readonly Book[]): Book[] {
return sortLibrary(books.filter(isInProgress), LibrarySort.Recent);
}

/** The open book's progress as its mounted reader currently measures it. */
export type LiveProgress = { bookId: string; progress: number };

/** Overlay the open reader's live progress onto the shelf. Progress is
* measured to the END of the visible page, so it depends on the pagination
* (viewport × typography) — the stored fraction is only true for the layout
* that last turned a page. Every surface that shows the open book's progress
* reads through this, so they cannot disagree with the reader footer. */
export function withLiveProgress(
books: readonly Book[],
live: LiveProgress | null,
): readonly Book[] {
if (live === null) return books;
const index = books.findIndex((b) => b.id === live.bookId);
const book = books[index];
if (!book || book.reading.progress === live.progress) return books;
const next = [...books];
next[index] = { ...book, reading: { ...book.reading, progress: live.progress } };
return next;
}

/** The persistence seam for per-book reading state. The reader calls
* `saveReadingPosition` whenever the parked locator changes; the preview
* drop leaves it unset (in-memory only), and 9.21.2 wires it to a
Expand Down
12 changes: 11 additions & 1 deletion apps/books/src/render/pdf-reader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ export type PdfReaderOptions = {
* with the stable locator + progress (0..1), mirroring the reflow
* reader's contract so the host persists both modes identically. */
onPositionChange?: (locator: Locator, progress: number) => void;
/** Fired with the progress the footer shows whenever it changes,
* including on mount — mirrors the reflow reader. Display-only. */
onProgressChange?: (progress: number) => void;
/** Fired when a link in the page is clicked — the host opens it (web links
* go to the browser via the `open` intent). Absent = links render but do
* nothing on click. */
Expand Down Expand Up @@ -215,6 +218,8 @@ export function mountPdfReader(
return isSpread() ? 2 : 1;
}

let reportedProgress: number | null = null;

function paint(): void {
if (disposed) return;
applyView();
Expand All @@ -231,9 +236,14 @@ export function mountPdfReader(
: t("reader.pageStatus", { page: String(state.pageIndex + 1), total });
status.textContent = pageStatus;
leftCanvas.setAttribute("aria-label", `${title} — ${pageStatus}`);
const fraction = pdfProgress(state);
progress.textContent = t("reader.progress", {
percent: String(Math.round(pdfProgress(state) * 100)),
percent: String(Math.round(fraction * 100)),
});
if (fraction !== reportedProgress) {
reportedProgress = fraction;
options.onProgressChange?.(fraction);
}
prev.disabled = !canGoPrevPdf(state);
next.disabled = !canGoNextPdf(state);
if (state.pageCount <= 0) return;
Expand Down
29 changes: 29 additions & 0 deletions apps/books/src/render/reader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,35 @@ describe("reader render with a measured page box", () => {
});
});

describe("reader live progress", () => {
const footerPercent = (root: HTMLElement): number =>
Number(/(\d+)%/.exec(root.querySelector(".books__progress")?.textContent ?? "")?.[1]);

// The footer was the only surface that knew the live number; the shelf row
// and the inspector showed the stored one until the next page turn.
it("reports the footer's progress on mount, before any page turn", () => {
const { root, right } = scaffold();
const seen: number[] = [];
handle = mountReader(root, right, SAMPLE_BOOK_CONTENT, {
onProgressChange: (p) => seen.push(p),
});
expect(seen).toHaveLength(1);
expect(Math.round((seen[0] ?? -1) * 100)).toBe(footerPercent(root));
});

it("reports again when a page turn moves it, and stays in step with the footer", () => {
const { root, right } = scaffold();
const seen: number[] = [];
handle = mountReader(root, right, SAMPLE_BOOK_CONTENT, {
onProgressChange: (p) => seen.push(p),
});
root.querySelector<HTMLButtonElement>(".books__nav-btn:last-of-type")?.click();
expect(seen).toHaveLength(2);
expect(seen[1]).toBeGreaterThan(seen[0] ?? 1);
expect(Math.round((seen[1] ?? -1) * 100)).toBe(footerPercent(root));
});
});

describe("reader render", () => {
it("paints the typography controls + the first page content + page status", () => {
const { root, right } = scaffold();
Expand Down
Loading
Loading