@kibitzo/chess-book-reader 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ import type { Box, Recognition } from "./protocol";
2
+ import type { Diagram } from "./store";
3
+ /**
4
+ * The page's side of the search worker: hand over a picture of a book's page, get its diagrams back. The worker
5
+ * does one job at a time, in the order asked.
6
+ */
7
+ export interface Search {
8
+ /** Every diagram of a page, each told through `onFound` as soon as it is found. */
9
+ page(bitmap: ImageBitmap, onFound: (d: Diagram) => void): Promise<Diagram[]>;
10
+ /** The diagram at a point of a page (fractions), or null. */
11
+ at(bitmap: ImageBitmap, fx: number, fy: number): Promise<Diagram | null>;
12
+ /** The diagram in a box the reader drew (fractions), or null. */
13
+ box(bitmap: ImageBitmap, box: Box): Promise<Diagram | null>;
14
+ /** The worker stopped (it could not be loaded, or this browser cannot run it): nothing more will be answered. */
15
+ readonly stopped: boolean;
16
+ close(): void;
17
+ }
18
+ export declare function openSearch(worker: Worker, recognition: Recognition): Search;
package/dist/search.js ADDED
@@ -0,0 +1,45 @@
1
+ const absolute = (url) => new URL(url, location.href).href;
2
+ export function openSearch(worker, recognition) {
3
+ const waiting = new Map();
4
+ let next = 1, stopped = false;
5
+ const send = (ask, transfer = []) => worker.postMessage(ask, transfer);
6
+ worker.onmessage = (e) => {
7
+ const tell = e.data, w = waiting.get(tell.id);
8
+ if (!w)
9
+ return;
10
+ if (tell.type === "found") {
11
+ w.found?.(tell.diagram);
12
+ return;
13
+ }
14
+ waiting.delete(tell.id);
15
+ if (tell.type === "error")
16
+ w.fail(new Error(tell.message));
17
+ else
18
+ w.done((tell.type === "page" ? tell.diagrams : tell.diagram));
19
+ };
20
+ worker.onerror = () => {
21
+ stopped = true;
22
+ for (const w of waiting.values())
23
+ w.fail(new Error("the search worker stopped"));
24
+ waiting.clear();
25
+ };
26
+ const { wasmPaths } = recognition;
27
+ send({ type: "init", recognition: { modelUrl: absolute(recognition.modelUrl), wasmPaths: typeof wasmPaths === "string" ? absolute(wasmPaths) : { mjs: absolute(wasmPaths.mjs), wasm: absolute(wasmPaths.wasm) } } });
28
+ const ask = (make, bitmap, found) => new Promise((done, fail) => {
29
+ if (stopped) {
30
+ bitmap.close();
31
+ fail(new Error("the search worker stopped"));
32
+ return;
33
+ }
34
+ const id = next++;
35
+ waiting.set(id, { found, done: done, fail });
36
+ send(make(id), [bitmap]);
37
+ });
38
+ return {
39
+ page: (bitmap, onFound) => ask((id) => ({ type: "page", id, bitmap }), bitmap, onFound),
40
+ at: (bitmap, fx, fy) => ask((id) => ({ type: "at", id, bitmap, fx, fy }), bitmap),
41
+ box: (bitmap, box) => ask((id) => ({ type: "box", id, bitmap, box }), bitmap),
42
+ get stopped() { return stopped; },
43
+ close: () => { worker.terminate(); waiting.clear(); },
44
+ };
45
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The reader's library: the visitor's books, kept on this device and nowhere else (IndexedDB). A book's file, its
3
+ * name (the visitor may change it), the page he stopped on, and the diagrams found on each page so far, so a page
4
+ * is read once and opens at once the next time.
5
+ */
6
+ export interface Book {
7
+ id: string;
8
+ /** The file's name without ".pdf", until the reader gives the book another (`renamed`). */
9
+ name: string;
10
+ renamed?: boolean;
11
+ size: number;
12
+ pages: number;
13
+ /** The page last read, 1-based. */
14
+ page: number;
15
+ added: number;
16
+ opened: number;
17
+ /** The first page as a small picture (a data URL). */
18
+ cover?: string;
19
+ }
20
+ /** A diagram on a page: where it is (fractions of the page) and what was read. */
21
+ export interface Diagram {
22
+ x0: number;
23
+ y0: number;
24
+ x1: number;
25
+ y1: number;
26
+ placement: string;
27
+ flipped: boolean;
28
+ /** The least and the mean confidence over the 64 squares, 0..1. */
29
+ min: number;
30
+ mean: number;
31
+ /** Who is to move, when the book says so beside the diagram. */
32
+ turn?: "w" | "b";
33
+ }
34
+ /** The name of the file a book came from: its id is "<time>:<file name>". */
35
+ export declare const fileNameOf: (book: Book) => string;
36
+ export declare function listBooks(): Promise<Book[]>;
37
+ /** A file's name without ".pdf", as the book's first name. */
38
+ export declare const titleOf: (fileName: string) => string;
39
+ /** Keep a file in the library. The same file (name and size) dropped again is the book already there. */
40
+ export declare function addBook(file: File, pages: number, about?: {
41
+ cover?: string;
42
+ }): Promise<Book>;
43
+ export declare function fileOf(id: string): Promise<Blob | undefined>;
44
+ export declare function saveBook(book: Book): Promise<void>;
45
+ export declare function removeBook(id: string): Promise<void>;
46
+ export declare function handOver(file: File): Promise<void>;
47
+ export declare function takeIncoming(): Promise<File | undefined>;
48
+ /** What is known of a page's diagrams. `full`: the whole page was searched; without it only the diagrams the
49
+ * reader double-clicked are there, and the page is still to be searched. */
50
+ export interface PageDiagrams {
51
+ full: boolean;
52
+ list: Diagram[];
53
+ /** Which finder searched the page (find.ts): a page searched by an older one is searched again. */
54
+ finder?: number;
55
+ }
56
+ export declare function diagramsOf(id: string, page: number): Promise<PageDiagrams | undefined>;
57
+ /** Everything known of a book's diagrams, by page. */
58
+ export declare function allDiagrams(id: string): Promise<Map<number, PageDiagrams>>;
59
+ /** How many diagrams are known in each book, by book. */
60
+ export declare function diagramCounts(): Promise<Map<string, number>>;
61
+ export declare function saveDiagrams(id: string, page: number, known: PageDiagrams): Promise<void>;
62
+ /** "4.9 MB", "812 KB". */
63
+ export declare function sizeText(bytes: number): string;
package/dist/store.js ADDED
@@ -0,0 +1,103 @@
1
+ const DB = "fenshot-read", VERSION = 1;
2
+ let opening = null;
3
+ function db() {
4
+ opening ??= new Promise((resolve, reject) => {
5
+ const req = indexedDB.open(DB, VERSION);
6
+ req.onupgradeneeded = () => {
7
+ const d = req.result;
8
+ if (!d.objectStoreNames.contains("books"))
9
+ d.createObjectStore("books", { keyPath: "id" });
10
+ if (!d.objectStoreNames.contains("files"))
11
+ d.createObjectStore("files");
12
+ if (!d.objectStoreNames.contains("diagrams"))
13
+ d.createObjectStore("diagrams");
14
+ };
15
+ req.onsuccess = () => resolve(req.result);
16
+ req.onerror = () => reject(req.error);
17
+ });
18
+ return opening;
19
+ }
20
+ const done = (req) => new Promise((resolve, reject) => { req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); });
21
+ const ended = (tx) => new Promise((resolve, reject) => { tx.oncomplete = () => resolve(); tx.onerror = tx.onabort = () => reject(tx.error); });
22
+ /** The name of the file a book came from: its id is "<time>:<file name>". */
23
+ export const fileNameOf = (book) => book.id.slice(book.id.indexOf(":") + 1);
24
+ export async function listBooks() {
25
+ const books = await done((await db()).transaction("books").objectStore("books").getAll());
26
+ // A book the reader has not renamed is called by its file's name, also one first named by the title inside the PDF
27
+ // (founder 2026-12-05: a PDF's own title is often a tool's word, "Print Diagram", not the book's name).
28
+ return books.map((b) => (b.renamed ? b : { ...b, name: titleOf(fileNameOf(b)) })).sort((a, b) => b.opened - a.opened);
29
+ }
30
+ /** A file's name without ".pdf", as the book's first name. */
31
+ export const titleOf = (fileName) => fileName.replace(/\.pdf$/i, "").replace(/[_]+/g, " ").trim() || "Book";
32
+ /** Keep a file in the library. The same file (name and size) dropped again is the book already there. */
33
+ export async function addBook(file, pages, about = {}) {
34
+ const known = (await listBooks()).find((b) => b.size === file.size && b.id.endsWith(`:${file.name}`));
35
+ if (known)
36
+ return known;
37
+ const now = Date.now();
38
+ const book = { id: `${now.toString(36)}:${file.name}`, name: titleOf(file.name), size: file.size, pages, page: 1, added: now, opened: now, cover: about.cover };
39
+ const tx = (await db()).transaction(["books", "files"], "readwrite");
40
+ tx.objectStore("books").put(book);
41
+ tx.objectStore("files").put(file, book.id);
42
+ await ended(tx);
43
+ return book;
44
+ }
45
+ export async function fileOf(id) {
46
+ return done((await db()).transaction("files").objectStore("files").get(id));
47
+ }
48
+ export async function saveBook(book) {
49
+ const tx = (await db()).transaction("books", "readwrite");
50
+ tx.objectStore("books").put(book);
51
+ await ended(tx);
52
+ }
53
+ export async function removeBook(id) {
54
+ const tx = (await db()).transaction(["books", "files", "diagrams"], "readwrite");
55
+ tx.objectStore("books").delete(id);
56
+ tx.objectStore("files").delete(id);
57
+ tx.objectStore("diagrams").delete(IDBKeyRange.bound(`${id}#`, `${id}#\uffff`));
58
+ await ended(tx);
59
+ }
60
+ /** A PDF dropped on the scanner's page goes to the reader through here: kept under one name, taken once. */
61
+ const INCOMING = "incoming";
62
+ export async function handOver(file) {
63
+ const tx = (await db()).transaction("files", "readwrite");
64
+ tx.objectStore("files").put(file, INCOMING);
65
+ await ended(tx);
66
+ }
67
+ export async function takeIncoming() {
68
+ const tx = (await db()).transaction("files", "readwrite");
69
+ const file = await done(tx.objectStore("files").get(INCOMING));
70
+ tx.objectStore("files").delete(INCOMING);
71
+ await ended(tx);
72
+ return file;
73
+ }
74
+ export async function diagramsOf(id, page) {
75
+ return done((await db()).transaction("diagrams").objectStore("diagrams").get(`${id}#${page}`));
76
+ }
77
+ /** Everything known of a book's diagrams, by page. */
78
+ export async function allDiagrams(id) {
79
+ const store = (await db()).transaction("diagrams").objectStore("diagrams");
80
+ const range = IDBKeyRange.bound(`${id}#`, `${id}#\uffff`);
81
+ const [keys, values] = await Promise.all([done(store.getAllKeys(range)), done(store.getAll(range))]);
82
+ return new Map(keys.map((key, i) => [Number(String(key).slice(id.length + 1)), values[i]]));
83
+ }
84
+ /** How many diagrams are known in each book, by book. */
85
+ export async function diagramCounts() {
86
+ const store = (await db()).transaction("diagrams").objectStore("diagrams");
87
+ const [keys, values] = await Promise.all([done(store.getAllKeys()), done(store.getAll())]);
88
+ const counts = new Map();
89
+ keys.forEach((key, i) => {
90
+ const id = String(key).slice(0, String(key).lastIndexOf("#"));
91
+ counts.set(id, (counts.get(id) ?? 0) + values[i].list.length);
92
+ });
93
+ return counts;
94
+ }
95
+ export async function saveDiagrams(id, page, known) {
96
+ const tx = (await db()).transaction("diagrams", "readwrite");
97
+ tx.objectStore("diagrams").put(known, `${id}#${page}`);
98
+ await ended(tx);
99
+ }
100
+ /** "4.9 MB", "812 KB". */
101
+ export function sizeText(bytes) {
102
+ return bytes >= 1048576 ? `${(bytes / 1048576).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`;
103
+ }
@@ -0,0 +1,25 @@
1
+ import { type RefObject } from "react";
2
+ import type { Point } from "./PageView";
3
+ import { type Doc } from "./pdf";
4
+ import { type Box } from "./protocol";
5
+ import { type Diagram } from "./store";
6
+ /** A diagram and the page it is on. */
7
+ export interface Spot {
8
+ page: number;
9
+ diagram: Diagram;
10
+ }
11
+ /** The same diagram, found twice. */
12
+ export declare const same: (a: Diagram, b: Diagram) => boolean;
13
+ /**
14
+ * The page to search next: the one being read, the one after it, then on to the end of the book (or of the
15
+ * window), then back from the one before. Null when all of them are done.
16
+ */
17
+ export declare function nextPage(now: number, pages: number, seen: ReadonlySet<number>, ahead?: number, behind?: number): number | null;
18
+ export declare function useDiagrams(doc: Doc, bookId: string, page: number, pane: RefObject<HTMLDivElement | null>): {
19
+ found: Map<number, Diagram[]>;
20
+ all: Spot[];
21
+ searched: number;
22
+ busy: boolean;
23
+ readPoint: (p: Point) => Promise<Diagram | null>;
24
+ readIn: (n: number, box: Box) => Promise<Diagram | null>;
25
+ };
@@ -0,0 +1,208 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { flipPlacement } from "@scoriiu/fenshot";
3
+ import { useReaderHost, useTrack } from "./host";
4
+ import { drawPage, sideBelow, turnNear, wordsOf } from "./pdf";
5
+ import { FINDER } from "./protocol";
6
+ import { openSearch } from "./search";
7
+ import { allDiagrams, diagramsOf, saveDiagrams } from "./store";
8
+ /**
9
+ * The diagrams of a book. Every page is searched once and what is found is kept (store.ts), so a book opened
10
+ * again has its diagrams at once. The search itself runs in a worker (worker.ts): this thread only draws a page
11
+ * into a picture and hands it over, so the reader's scrolling is never held up.
12
+ *
13
+ * The order (founder 2026-12-05: "where we are on the page is priority"): what the reader asks for himself (a
14
+ * double-click, a box) goes first; then the page he is on and its neighbours, at once, also while he scrolls;
15
+ * then the rest of the book from there on, only while the pages are still. The order is decided again after
16
+ * every page, so a jump to another chapter is served next. On a phone the rest is the next 20 pages, not the
17
+ * whole book (a search of 190 pages keeps one core busy for a minute and a half).
18
+ */
19
+ /** How wide a page is drawn for reading its diagrams: a board of a quarter page then has squares of about 50 px. */
20
+ const READ_WIDTH = 1700, FIND_WIDTH = 1300;
21
+ /** The reader has stopped scrolling when the pages have been still this long. */
22
+ const STILL_MS = 400;
23
+ const PHONE_AHEAD = 20, PHONE_BEHIND = 2;
24
+ /** This many pages in a row that could not be searched: the search is not working (the worker, the model), and stops. */
25
+ const GIVE_UP = 5;
26
+ /** The same diagram, found twice. */
27
+ export const same = (a, b) => Math.abs(a.x0 - b.x0) < 0.03 && Math.abs(a.y0 - b.y0) < 0.03;
28
+ /** The order they are read in: row by row, each row from the left. */
29
+ const inReadingOrder = (a, b) => (Math.abs(a.y0 - b.y0) > (a.y1 - a.y0) / 2 ? a.y0 - b.y0 : a.x0 - b.x0);
30
+ async function pictureOf(doc, n, width, canvas) {
31
+ await (await drawPage(doc, n, width, canvas)).promise;
32
+ return createImageBitmap(canvas);
33
+ }
34
+ /**
35
+ * A diagram with what the page's words say of it: who is to move (a caption counts for more than a mark beside
36
+ * the board), and which side it is printed from. A book prints from White's side unless its coordinates say
37
+ * otherwise: the scanner's guess from where the pawns stand is wrong for an endgame with pawns far up the board
38
+ * (3 of 44 diagrams in a book of exercises, measured 2026-12-05), so it is not asked here.
39
+ */
40
+ function withWords(words, d) {
41
+ const turn = turnNear(words, d);
42
+ const told = turn ? { ...d, turn } : d;
43
+ return sideBelow(words, d) === "black" && !told.flipped ? { ...told, placement: flipPlacement(told.placement), flipped: true } : told;
44
+ }
45
+ /**
46
+ * The page to search next: the one being read, the one after it, then on to the end of the book (or of the
47
+ * window), then back from the one before. Null when all of them are done.
48
+ */
49
+ export function nextPage(now, pages, seen, ahead = Infinity, behind = Infinity) {
50
+ const last = Math.min(pages, now + ahead), first = Math.max(1, now - behind);
51
+ for (let n = now; n <= last; n++)
52
+ if (!seen.has(n))
53
+ return n;
54
+ for (let n = now - 1; n >= first; n--)
55
+ if (!seen.has(n))
56
+ return n;
57
+ return null;
58
+ }
59
+ export function useDiagrams(doc, bookId, page, pane) {
60
+ const pages = doc.numPages;
61
+ const { searchWorker, recognition } = useReaderHost();
62
+ const count = useTrack();
63
+ const [found, setFound] = useState(new Map());
64
+ /** How many pages have been searched, and whether a search is going on or waiting. */
65
+ const [searched, setSearched] = useState(0);
66
+ const [busy, setBusy] = useState(true);
67
+ const search = useRef(null);
68
+ const seen = useRef(new Set());
69
+ const full = useRef(new Set());
70
+ /** What the reader asked for himself, ahead of everything else. */
71
+ const asks = useRef([]);
72
+ const wake = useRef(() => { });
73
+ /** The one sheet pages are drawn on for the search: one at a time, each handed over as a picture. */
74
+ const sheet = useRef(null);
75
+ sheet.current ??= document.createElement("canvas");
76
+ const now = useRef(page);
77
+ useEffect(() => { now.current = page; wake.current(); }, [page]);
78
+ /** Add diagrams to a page's, each once. */
79
+ const show = useCallback((n, list) => {
80
+ setFound((old) => {
81
+ const known = old.get(n) ?? [], fresh = list.filter((d) => !known.some((k) => same(k, d)));
82
+ return fresh.length ? new Map(old).set(n, [...known, ...fresh]) : old;
83
+ });
84
+ }, []);
85
+ useEffect(() => {
86
+ const s = openSearch(searchWorker(), recognition);
87
+ search.current = s;
88
+ let gone = false, moved = 0, worked = false, total = 0, failed = 0;
89
+ const el = pane.current;
90
+ const onScroll = () => { moved = performance.now(); };
91
+ el?.addEventListener("scroll", onScroll, { passive: true });
92
+ const phone = window.matchMedia("(pointer: coarse) and (max-width: 900px)").matches;
93
+ const [ahead, behind] = phone ? [PHONE_AHEAD, PHONE_BEHIND] : [Infinity, Infinity];
94
+ /** Wait, at most `ms`: a new page under the reader, or something he asks for, ends the wait. */
95
+ const rest = (ms) => new Promise((done) => {
96
+ const id = setTimeout(done, ms);
97
+ wake.current = () => { clearTimeout(id); done(); };
98
+ });
99
+ const finished = (n, list) => {
100
+ full.current.add(n);
101
+ total += list.length;
102
+ setSearched(full.current.size);
103
+ if (worked && full.current.size === pages)
104
+ count("read-searched", { pages, diagrams: total });
105
+ };
106
+ /** Search a page, unless it was searched before by this finder. */
107
+ const searchPage = async (n) => {
108
+ let list = [];
109
+ try {
110
+ const kept = await diagramsOf(bookId, n);
111
+ list = kept?.list ?? [];
112
+ if (!kept?.full || kept.finder !== FINDER) {
113
+ worked = true;
114
+ const [picture, words] = await Promise.all([pictureOf(doc, n, FIND_WIDTH, sheet.current), wordsOf(doc, n).catch(() => [])]);
115
+ // Each diagram shows as soon as it is found: a page of six is not kept waiting for the sixth.
116
+ const searchedNow = (await s.page(picture, (d) => { if (!gone)
117
+ show(n, [withWords(words, d)]); })).map((d) => withWords(words, d));
118
+ list = [...searchedNow, ...list.filter((d) => !searchedNow.some((k) => same(k, d)))];
119
+ void saveDiagrams(bookId, n, { full: true, finder: FINDER, list });
120
+ }
121
+ if (!gone)
122
+ show(n, list);
123
+ failed = 0;
124
+ }
125
+ catch {
126
+ failed++; /* a page that cannot be read has no diagrams */
127
+ }
128
+ if (!gone)
129
+ finished(n, list);
130
+ };
131
+ void (async () => {
132
+ // What was kept from before, at once.
133
+ const kept = await allDiagrams(bookId).catch(() => new Map());
134
+ if (gone)
135
+ return;
136
+ for (const [n, known] of kept) {
137
+ if (!known.full || known.finder !== FINDER || n > pages)
138
+ continue;
139
+ seen.current.add(n);
140
+ show(n, known.list);
141
+ finished(n, known.list);
142
+ }
143
+ while (!gone) {
144
+ const ask = asks.current.shift();
145
+ if (ask) {
146
+ await ask();
147
+ continue;
148
+ }
149
+ if (s.stopped || failed >= GIVE_UP) {
150
+ count("read-fail", { why: "search" });
151
+ setBusy(false);
152
+ return;
153
+ }
154
+ const n = nextPage(now.current, pages, seen.current, ahead, behind);
155
+ if (n === null) {
156
+ setBusy(false);
157
+ await rest(60_000);
158
+ continue;
159
+ }
160
+ setBusy(true);
161
+ const here = Math.abs(n - now.current) <= 1;
162
+ if (!here && (document.hidden || performance.now() - moved < STILL_MS)) {
163
+ await rest(200);
164
+ continue;
165
+ }
166
+ seen.current.add(n);
167
+ await searchPage(n);
168
+ }
169
+ })();
170
+ return () => { gone = true; wake.current(); el?.removeEventListener("scroll", onScroll); s.close(); search.current = null; };
171
+ }, [doc, bookId, pages, pane, searchWorker, recognition, show, count]);
172
+ /** Something the reader asks for himself: done before the next page of the background search. */
173
+ const asked = useCallback((n, read) => new Promise((done, fail) => {
174
+ asks.current.push(async () => {
175
+ const s = search.current;
176
+ if (!s) {
177
+ done(null);
178
+ return;
179
+ }
180
+ try {
181
+ const [picture, words] = await Promise.all([pictureOf(doc, n, READ_WIDTH, sheet.current), wordsOf(doc, n).catch(() => [])]);
182
+ const got = await read(s, picture);
183
+ const diagram = got && withWords(words, got);
184
+ if (diagram) {
185
+ // It joins its page's diagrams, in place of one found there before.
186
+ setFound((old) => {
187
+ const list = [...(old.get(n) ?? []).filter((d) => !same(d, diagram)), diagram];
188
+ void saveDiagrams(bookId, n, { full: full.current.has(n), finder: FINDER, list });
189
+ return new Map(old).set(n, list);
190
+ });
191
+ }
192
+ done(diagram);
193
+ }
194
+ catch (err) {
195
+ fail(err instanceof Error ? err : new Error(String(err)));
196
+ }
197
+ });
198
+ wake.current();
199
+ }), [doc, bookId]);
200
+ /** The diagram at a point of a page, read now; null when none can be read there. */
201
+ const readPoint = useCallback((p) => asked(p.page, (s, picture) => s.at(picture, p.fx, p.fy)), [asked]);
202
+ /** The diagram in a box the reader drew on a page; null when it cannot be read. */
203
+ const readIn = useCallback((n, box) => asked(n, (s, picture) => s.box(picture, box)), [asked]);
204
+ /** Every diagram found so far, in the order of the book. */
205
+ const all = useMemo(() => [...found.keys()].sort((a, b) => a - b)
206
+ .flatMap((n) => [...(found.get(n) ?? [])].sort(inReadingOrder).map((diagram) => ({ page: n, diagram }))), [found]);
207
+ return { found, all, searched, busy, readPoint, readIn };
208
+ }
@@ -0,0 +1,18 @@
1
+ import { type Doc } from "./pdf";
2
+ import type { Diagram } from "./store";
3
+ export declare function usePages(doc: Doc, startPage: number): {
4
+ pane: import("react").RefObject<HTMLDivElement | null>;
5
+ holder: (n: number, el: HTMLDivElement | null) => void;
6
+ pages: number;
7
+ page: number;
8
+ width: number;
9
+ ratio0: number;
10
+ laidOut: boolean;
11
+ near: Set<number>;
12
+ goTo: (n: number) => void;
13
+ goToDiagram: (n: number, d: Diagram) => void;
14
+ zoomBy: (step: number) => void;
15
+ zoom: number;
16
+ canZoomOut: boolean;
17
+ canZoomIn: boolean;
18
+ };
@@ -0,0 +1,148 @@
1
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
2
+ import { ratioOf } from "./pdf";
3
+ /**
4
+ * The column of pages: how wide a page is drawn (the room there is, times the zoom), which pages are near the
5
+ * screen and so are drawn, which page is being read, and the ways to move: to a page, to a diagram, larger and
6
+ * smaller. When the pages change size (zoom, the board's edge dragged) the reader stays where he was.
7
+ */
8
+ /** Sizes of a page, in percent of the size that fits the room. */
9
+ const ZOOMS = [50, 67, 80, 90, 100, 110, 125, 150, 175, 200];
10
+ const FIT = ZOOMS.indexOf(100);
11
+ const PAGE_MAX = 920;
12
+ export function usePages(doc, startPage) {
13
+ const pages = doc.numPages;
14
+ const pane = useRef(null);
15
+ const holders = useRef(new Map());
16
+ const [paneW, setPaneW] = useState(0);
17
+ const [zoom, setZoom] = useState(FIT);
18
+ const [ratio0, setRatio0] = useState(0);
19
+ const [near, setNear] = useState(new Set([startPage]));
20
+ const [page, setPage] = useState(startPage);
21
+ const width = Math.max(0, Math.round(Math.min(paneW - 24, PAGE_MAX) * ZOOMS[zoom] / 100));
22
+ const laidOut = ratio0 > 0 && width > 50;
23
+ useEffect(() => { void ratioOf(doc, 1).then(setRatio0); }, [doc]);
24
+ /** Where the reader is (a page and how far down it), kept while the pages change size. */
25
+ const place = useRef(null);
26
+ const keepPlace = useCallback(() => {
27
+ const el = pane.current;
28
+ if (!el)
29
+ return;
30
+ const top = el.getBoundingClientRect().top;
31
+ for (const [n, h] of holders.current) {
32
+ const r = h.getBoundingClientRect();
33
+ if (r.bottom > top && r.height > 0) {
34
+ place.current = { page: n, part: (top - r.top) / r.height };
35
+ return;
36
+ }
37
+ }
38
+ }, []);
39
+ useLayoutEffect(() => {
40
+ const el = pane.current;
41
+ if (!el)
42
+ return;
43
+ // The pages are drawn again at a new width: once the edge of the board has come to rest, not at every step.
44
+ let wait = 0;
45
+ const ro = new ResizeObserver(() => { clearTimeout(wait); wait = window.setTimeout(() => { keepPlace(); setPaneW(el.clientWidth); }, 140); });
46
+ ro.observe(el);
47
+ setPaneW(el.clientWidth);
48
+ return () => { ro.disconnect(); clearTimeout(wait); };
49
+ }, [keepPlace]);
50
+ useLayoutEffect(() => {
51
+ const el = pane.current, at = place.current;
52
+ place.current = null;
53
+ const h = at && holders.current.get(at.page);
54
+ if (el && h)
55
+ el.scrollTop += h.getBoundingClientRect().top + at.part * h.offsetHeight - el.getBoundingClientRect().top;
56
+ }, [width]);
57
+ // Pages near the screen are drawn; the rest keep their place, empty.
58
+ const watcher = useRef(null);
59
+ const holder = useCallback((n, el) => {
60
+ const was = holders.current.get(n);
61
+ if (was === el)
62
+ return;
63
+ if (was)
64
+ watcher.current?.unobserve(was);
65
+ if (el) {
66
+ holders.current.set(n, el);
67
+ watcher.current?.observe(el);
68
+ }
69
+ else
70
+ holders.current.delete(n);
71
+ }, []);
72
+ useLayoutEffect(() => {
73
+ if (!laidOut || !pane.current)
74
+ return;
75
+ const io = new IntersectionObserver((entries) => {
76
+ setNear((old) => {
77
+ const next = new Set(old);
78
+ for (const e of entries) {
79
+ const n = Number(e.target.dataset.page);
80
+ if (e.isIntersecting)
81
+ next.add(n);
82
+ else
83
+ next.delete(n);
84
+ }
85
+ return next;
86
+ });
87
+ }, { root: pane.current, rootMargin: "900px 0px" });
88
+ watcher.current = io;
89
+ for (const el of holders.current.values())
90
+ io.observe(el);
91
+ return () => { io.disconnect(); watcher.current = null; };
92
+ }, [laidOut]);
93
+ // Open on the page the reader stopped on, once the pages have their size.
94
+ const placed = useRef(false);
95
+ useLayoutEffect(() => {
96
+ if (placed.current || !laidOut)
97
+ return;
98
+ placed.current = true;
99
+ if (startPage > 1)
100
+ holders.current.get(startPage)?.scrollIntoView({ block: "start" });
101
+ }, [laidOut, startPage]);
102
+ // The page that holds the upper third of the screen is the one being read.
103
+ useEffect(() => {
104
+ const el = pane.current;
105
+ if (!el)
106
+ return;
107
+ let frame = 0;
108
+ const read = () => {
109
+ frame = 0;
110
+ const line = el.getBoundingClientRect().top + el.clientHeight * 0.3;
111
+ for (const [n, h] of holders.current) {
112
+ const r = h.getBoundingClientRect();
113
+ if (r.top <= line && r.bottom > line) {
114
+ setPage(n);
115
+ break;
116
+ }
117
+ }
118
+ };
119
+ const onScroll = () => { if (!frame)
120
+ frame = requestAnimationFrame(read); };
121
+ el.addEventListener("scroll", onScroll, { passive: true });
122
+ return () => { el.removeEventListener("scroll", onScroll); cancelAnimationFrame(frame); };
123
+ }, []);
124
+ const goTo = useCallback((n) => {
125
+ const target = Math.min(pages, Math.max(1, Math.round(n)));
126
+ holders.current.get(target)?.scrollIntoView({ block: "start" });
127
+ setPage(target);
128
+ }, [pages]);
129
+ /** Bring a diagram to the middle of what the reader sees of the page (its top, where a sheet covers the rest). */
130
+ const goToDiagram = useCallback((n, d) => {
131
+ const el = pane.current, h = holders.current.get(n);
132
+ if (!el || !h)
133
+ return;
134
+ const r = h.getBoundingClientRect(), view = el.getBoundingClientRect();
135
+ const sheet = window.matchMedia("(max-width: 900px)").matches;
136
+ const want = sheet ? view.top + 12 + ((d.y1 - d.y0) * r.height) / 2 : view.top + el.clientHeight / 2;
137
+ el.scrollTop += r.top + ((d.y0 + d.y1) / 2) * r.height - want;
138
+ // Zoomed in, the page is wider than its room: bring the diagram to the middle sideways too.
139
+ if (el.scrollWidth > el.clientWidth)
140
+ el.scrollLeft += r.left + ((d.x0 + d.x1) / 2) * r.width - (view.left + el.clientWidth / 2);
141
+ }, []);
142
+ /** A step larger or smaller; no step is back to 100%. */
143
+ const zoomBy = useCallback((step) => {
144
+ keepPlace();
145
+ setZoom((z) => (step === 0 ? FIT : Math.min(ZOOMS.length - 1, Math.max(0, z + step))));
146
+ }, [keepPlace]);
147
+ return { pane, holder, pages, page, width, ratio0, laidOut, near, goTo, goToDiagram, zoomBy, zoom: ZOOMS[zoom], canZoomOut: zoom > 0, canZoomIn: zoom < ZOOMS.length - 1 };
148
+ }
@@ -0,0 +1 @@
1
+ export {};