@kibitzo/chess-book-reader 0.1.0 → 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.
package/README.md CHANGED
@@ -7,12 +7,19 @@ beside the page. The book is read in the browser and kept on the device (Indexed
7
7
  It runs [fenshot.com/read](https://fenshot.com/read/) and [kibitzo.com/read](https://kibitzo.com/read): the
8
8
  reader is this package, the board beside the page is each site's own.
9
9
 
10
+ ```tsx
11
+ // search.worker.ts, a file of one line in your app, so that your bundler builds the worker:
12
+ import "@kibitzo/chess-book-reader/worker";
13
+ ```
14
+
10
15
  ```tsx
11
16
  import { BookReader, englishWords, type ReaderHost } from "@kibitzo/chess-book-reader";
12
17
  import "@kibitzo/chess-book-reader/reader.css";
13
18
 
14
19
  const host: ReaderHost = {
15
- recognizer: createRecognizer({ modelUrl, wasmPaths }), // from @scoriiu/fenshot
20
+ // the tile model from @scoriiu/fenshot and onnxruntime-web's wasm files, as you serve them
21
+ recognition: { modelUrl: "/models/chess-tiles-v2.onnx", wasmPaths: "/ort/" },
22
+ searchWorker: () => new Worker(new URL("./search.worker.ts", import.meta.url), { type: "module" }),
16
23
  pdf: { workerSrc: "/pdfjs/pdf.worker.min.mjs", assets: "/pdfjs/" }, // pdfjs-dist's worker, wasm/, cmaps/, standard_fonts/, iccs/
17
24
  t: englishWords,
18
25
  BoardPanel: MyBoard, // ({ picked: { page, diagram }, onClose }) => your board
@@ -21,6 +28,9 @@ const host: ReaderHost = {
21
28
  <BookReader host={host} />;
22
29
  ```
23
30
 
31
+ The diagrams are searched in the worker, off the page's thread: the page being read first, then the rest of
32
+ the book.
33
+
24
34
  The look follows the `--fsr-*` CSS variables (colours), `--fsr-inset` and `--fsr-z` (where an open book sits),
25
35
  and `--fsr-sheet-left` (the board's sheet on narrow screens).
26
36
 
@@ -1,4 +1,5 @@
1
1
  import { type Doc } from "./pdf";
2
+ import type { Box } from "./protocol";
2
3
  import type { Diagram } from "./store";
3
4
  /** A point of a page, in fractions of its width and height. */
4
5
  export type Point = {
@@ -6,13 +7,6 @@ export type Point = {
6
7
  fx: number;
7
8
  fy: number;
8
9
  };
9
- /** A box on a page, in the same fractions. */
10
- export type Box = {
11
- x0: number;
12
- y0: number;
13
- x1: number;
14
- y1: number;
15
- };
16
10
  /**
17
11
  * One page of the book: its picture when it is near the screen (`live`), the diagrams found on it as buttons, the
18
12
  * reader's double-click (or two quick taps) told as a point of the page, and the box he draws around a diagram
package/dist/ReadApp.js CHANGED
@@ -38,17 +38,20 @@ function ReadApp() {
38
38
  const now = { ...book, pages: doc.numPages, page: Math.min(book.page, doc.numPages), opened: Date.now() };
39
39
  await saveBook(now);
40
40
  history.replaceState(null, "", `#${encodeURIComponent(book.id)}`);
41
+ count("read-reopen", { pages: doc.numPages, page: now.page });
41
42
  setOpen({ book: now, doc });
42
43
  }
43
44
  catch {
45
+ count("read-fail", { why: "cant-reopen" });
44
46
  setError(t("readCantOpen"));
45
47
  }
46
48
  finally {
47
49
  setBusy(false);
48
50
  }
49
- }, [t]);
51
+ }, [t, count]);
50
52
  const openFile = useCallback(async (file) => {
51
53
  if (file.type !== "application/pdf" && !/\.pdf$/i.test(file.name)) {
54
+ count("read-fail", { why: "not-pdf" });
52
55
  setError(t("readNotPdf"));
53
56
  return;
54
57
  }
@@ -62,12 +65,13 @@ function ReadApp() {
62
65
  setOpen({ book: { ...book, opened: Date.now() }, doc });
63
66
  }
64
67
  catch {
68
+ count("read-fail", { why: "cant-open" });
65
69
  setError(t("readCantOpen"));
66
70
  }
67
71
  finally {
68
72
  setBusy(false);
69
73
  }
70
- }, [t]);
74
+ }, [t, count]);
71
75
  // Once, on arrival: the library, and the book the address names.
72
76
  const arrived = useRef(false);
73
77
  useEffect(() => {
package/dist/Reader.js CHANGED
@@ -28,7 +28,7 @@ export function Reader({ book, doc, onLibrary, onProgress }) {
28
28
  const { BoardPanel } = useReaderHost();
29
29
  const view = usePages(doc, book.page);
30
30
  const { page, goToDiagram } = view;
31
- const { found, all, searched, readPoint, readIn } = useDiagrams(doc, book.id, page, view.pane);
31
+ const { found, all, searched, busy: searching, readPoint, readIn } = useDiagrams(doc, book.id, page, view.pane);
32
32
  /** The reader is drawing a box around a diagram that was not found. */
33
33
  const [selecting, setSelecting] = useState(false);
34
34
  const [sideW, setSideW] = useState(storedSide);
@@ -113,5 +113,5 @@ export function Reader({ book, doc, onLibrary, onProgress }) {
113
113
  window.addEventListener("keydown", key);
114
114
  return () => window.removeEventListener("keydown", key);
115
115
  }, [zoomBy, step, selecting]);
116
- return (_jsxs("div", { className: `rd ${picked ? "rd-has-board" : ""}`, style: { "--rd-side": `${sideW}px` }, "data-testid": "reader", children: [_jsx(ReaderBar, { doc: doc, name: book.name, page: page, onLibrary: onLibrary, onPage: view.goTo, nav: { total: all.length, index, searched, pages: view.pages, onStep: step }, select: { on: selecting, toggle: () => setSelecting(!selecting) }, zoom: { percent: view.zoom, by: zoomBy, canOut: view.canZoomOut, canIn: view.canZoomIn } }), _jsxs("div", { className: "rd-body", children: [_jsx("div", { className: `rd-pages ${selecting ? "rd-selecting" : ""}`, ref: view.pane, tabIndex: 0, "data-testid": "read-pages", children: view.laidOut && Array.from({ length: view.pages }, (_, i) => i + 1).map((n) => (_jsx(PageView, { doc: doc, n: n, width: view.width, ratio0: view.ratio0, live: view.near.has(n), found: found.get(n), picked: picked?.page === n && !picked.byHand ? picked.diagram : null, busy: busy?.page === n ? busy : null, selecting: selecting, onPoint: onPoint, onDiagram: open, onBox: onBox, holder: view.holder }, n))) }), _jsx(SideGrip, { width: sideW, label: t("readResize"), onWidth: setSideW }), picked ? (_jsx("aside", { className: "rd-side", "data-testid": "read-board-panel", children: _jsx(BoardPanel, { picked: picked, onClose: () => setPicked(null) }) })) : (_jsxs("aside", { className: "rd-side rd-side-empty", children: [_jsxs("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true, children: [_jsx("rect", { x: "3.5", y: "3.5", width: "17", height: "17", rx: "2" }), _jsx("path", { d: "M3.5 12h17M12 3.5v17" })] }), _jsx("p", { className: "rd-hint", children: t("readHint") }), _jsx("p", { className: "rd-hint-sub", children: t("readHintSub") })] }))] }), selecting && _jsx("div", { className: "rd-toast", role: "status", "data-testid": "read-select-hint", children: _jsx("span", { children: t("readSelectHint") }) }), unread && (_jsxs("div", { className: "rd-toast", role: "status", "data-testid": "read-toast", children: [_jsx("span", { children: t("readNoDiagram") }), _jsx("button", { type: "button", className: "rd-btn rd-btn-quiet", onClick: byHand, "data-testid": "read-byhand", children: t("readByHand") })] }))] }));
116
+ return (_jsxs("div", { className: `rd ${picked ? "rd-has-board" : ""}`, style: { "--rd-side": `${sideW}px` }, "data-testid": "reader", children: [_jsx(ReaderBar, { doc: doc, name: book.name, page: page, onLibrary: onLibrary, onPage: view.goTo, nav: { total: all.length, index, searched, pages: view.pages, busy: searching, onStep: step }, select: { on: selecting, toggle: () => setSelecting(!selecting) }, zoom: { percent: view.zoom, by: zoomBy, canOut: view.canZoomOut, canIn: view.canZoomIn } }), _jsxs("div", { className: "rd-body", children: [_jsx("div", { className: `rd-pages ${selecting ? "rd-selecting" : ""}`, ref: view.pane, tabIndex: 0, "data-testid": "read-pages", children: view.laidOut && Array.from({ length: view.pages }, (_, i) => i + 1).map((n) => (_jsx(PageView, { doc: doc, n: n, width: view.width, ratio0: view.ratio0, live: view.near.has(n), found: found.get(n), picked: picked?.page === n && !picked.byHand ? picked.diagram : null, busy: busy?.page === n ? busy : null, selecting: selecting, onPoint: onPoint, onDiagram: open, onBox: onBox, holder: view.holder }, n))) }), _jsx(SideGrip, { width: sideW, label: t("readResize"), onWidth: setSideW }), picked ? (_jsx("aside", { className: "rd-side", "data-testid": "read-board-panel", children: _jsx(BoardPanel, { picked: picked, onClose: () => setPicked(null) }) })) : (_jsxs("aside", { className: "rd-side rd-side-empty", children: [_jsxs("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true, children: [_jsx("rect", { x: "3.5", y: "3.5", width: "17", height: "17", rx: "2" }), _jsx("path", { d: "M3.5 12h17M12 3.5v17" })] }), _jsx("p", { className: "rd-hint", children: t("readHint") }), _jsx("p", { className: "rd-hint-sub", children: t("readHintSub") })] }))] }), selecting && _jsx("div", { className: "rd-toast", role: "status", "data-testid": "read-select-hint", children: _jsx("span", { children: t("readSelectHint") }) }), unread && (_jsxs("div", { className: "rd-toast", role: "status", "data-testid": "read-toast", children: [_jsx("span", { children: t("readNoDiagram") }), _jsx("button", { type: "button", className: "rd-btn rd-btn-quiet", onClick: byHand, "data-testid": "read-byhand", children: t("readByHand") })] }))] }));
117
117
  }
@@ -6,6 +6,8 @@ export interface DiagramNavProps {
6
6
  /** Pages searched, of the book's pages: the count is still growing while they differ. */
7
7
  searched: number;
8
8
  pages: number;
9
+ /** A search is going on or waiting (on a phone the book is searched some pages ahead of the reader, not whole). */
10
+ busy: boolean;
9
11
  onStep(step: -1 | 1): void;
10
12
  }
11
13
  export declare function ReaderBar({ doc, name, page, nav, select, zoom, onLibrary, onPage }: {
package/dist/ReaderBar.js CHANGED
@@ -24,10 +24,10 @@ function Contents({ doc, onPage }) {
24
24
  return null;
25
25
  return (_jsxs("div", { className: "rd-contents", children: [_jsxs("button", { type: "button", className: "rd-chip", onClick: () => setOpen(!open), "aria-expanded": open, "aria-label": t("readContents"), "data-testid": "read-contents-open", children: [_jsx(Icon, { d: "M8 6h12M8 12h12M8 18h12M4 6h.01M4 12h.01M4 18h.01" }), _jsx("span", { children: t("readContents") })] }), open && (_jsx("ul", { className: "rd-contents-list", "data-testid": "read-contents", children: chapters.map((c, i) => (_jsx("li", { children: _jsxs("button", { type: "button", style: { paddingInlineStart: 12 + c.depth * 14 }, onClick: () => { onPage(c.page); setOpen(false); }, children: [_jsx("span", { children: c.title }), _jsx("span", { className: "rd-contents-page", children: c.page })] }) }, i))) }))] }));
26
26
  }
27
- function DiagramNav({ total, index, searched, pages, onStep }) {
27
+ function DiagramNav({ total, index, searched, pages, busy, onStep }) {
28
28
  const t = useT();
29
- const finding = searched < pages;
30
- const about = finding ? t("readFinding", { done: searched, pages }) : t("readDiagrams", { n: total });
29
+ const finding = busy && searched < pages;
30
+ const about = searched < pages ? t("readFinding", { done: searched, pages }) : t("readDiagrams", { n: total });
31
31
  return (_jsxs("div", { className: `rd-nav ${finding ? "finding" : ""}`, title: about, "data-testid": "read-nav", children: [_jsx("button", { type: "button", className: "rd-icon", onClick: () => onStep(-1), disabled: !total, "aria-label": t("readDiagramPrev"), "data-testid": "read-nav-prev", children: _jsx(Icon, { d: "M15 6l-6 6 6 6" }) }), _jsxs("span", { className: "rd-nav-count", style: { minWidth: `calc(${String(total).length * 2 + 3.4}ch + 21px)` }, "aria-label": about, "data-testid": "read-nav-count", children: [_jsxs("svg", { viewBox: "0 0 24 24", "aria-hidden": true, children: [_jsx("rect", { x: "3.5", y: "3.5", width: "17", height: "17", rx: "2.5", fill: "none", stroke: "currentColor", strokeWidth: "1.8" }), _jsx("path", { d: "M3.5 3.5h8.5v8.5H3.5zM12 12h8.5v8.5H12z", fill: "currentColor", opacity: "0.55" })] }), index >= 0 ? _jsxs(_Fragment, { children: [_jsx("b", { children: index + 1 }), _jsxs("i", { children: ["/ ", total] })] }) : _jsx("b", { children: total })] }), _jsx("button", { type: "button", className: "rd-icon", onClick: () => onStep(1), disabled: !total, "aria-label": t("readDiagramNext"), "data-testid": "read-nav-next", children: _jsx(Icon, { d: "M9 6l6 6-6 6" }) }), finding && _jsx("span", { className: "rd-nav-progress", "aria-hidden": true, children: _jsx("span", { style: { width: `${(searched / pages) * 100}%` } }) })] }));
32
32
  }
33
33
  export function ReaderBar({ doc, name, page, nav, select, zoom, onLibrary, onPage }) {
package/dist/find.d.ts CHANGED
@@ -1,19 +1,32 @@
1
1
  /**
2
- * Diagrams on a page of a book. Two ways in:
2
+ * Diagrams on a page of a book. Three ways in:
3
3
  * - findDiagrams reads a whole page in the background: the board finder is run, what it found is covered, and it
4
4
  * is run again, so a page with several diagrams gives them all;
5
5
  * - readAt reads the diagram under a double-click, for a diagram the background pass missed: a window around
6
- * the click, then wider ones, until a board is found that the click is on.
6
+ * the click, then wider ones, until a board is found that the click is on;
7
+ * - readBox reads the diagram in a box the reader drew.
7
8
  * Measured 2026-12-05 on a modern typeset book (41 pages): a board found on 37, every one read with all squares
8
9
  * at 75% or more. An old scanned printing reads far worse; such a read opens in the editor to be checked.
9
10
  */
10
- import { type Recognizer } from "@scoriiu/fenshot";
11
+ import { type BoardScanResult } from "@scoriiu/fenshot";
11
12
  import type { Diagram } from "./store";
13
+ /**
14
+ * All of this runs in the search worker (worker.ts), off the page's thread, on canvases of its own: nothing here
15
+ * may touch the document.
16
+ */
17
+ type Canvas = OffscreenCanvas;
18
+ /** The model, as the worker holds it: what it reads in a picture, with the size of the frame it looked at. */
19
+ export interface Scanner {
20
+ recognize(source: Canvas): Promise<(BoardScanResult & {
21
+ frame: {
22
+ width: number;
23
+ height: number;
24
+ };
25
+ }) | null>;
26
+ }
12
27
  type Rect = [x: number, y: number, w: number, h: number];
13
28
  /** A read worth showing as a diagram without being asked: every square at least this sure. */
14
29
  export declare const SURE = 0.6;
15
- /** Raised when the finder finds more than it did: pages it searched before are then searched again. */
16
- export declare const FINDER = 5;
17
30
  /**
18
31
  * Black to move, as many books print it: a filled mark (a triangle, a square, a disc) beside the board's right
19
32
  * edge, level with its bottom rank or its top one. A hollow mark, or none, says nothing here. The mark is told
@@ -21,18 +34,18 @@ export declare const FINDER = 5;
21
34
  * Seen 2026-12-05 in a book of exercises: 18 of its 44 diagrams carry the filled mark, and each of them has a
22
35
  * mate in one for Black. The box is the board in the canvas's pixels.
23
36
  */
24
- export declare function blackMarked(page: HTMLCanvasElement, x0: number, y0: number, x1: number, y1: number): boolean;
37
+ export declare function blackMarked(page: Canvas, x0: number, y0: number, x1: number, y1: number): boolean;
25
38
  /** A board in a book is square and takes a real share of the page's width. */
26
39
  export declare function plausible(x0: number, y0: number, x1: number, y1: number, pageW: number): boolean;
27
40
  /** The windows to read around a click, nearest first. */
28
41
  export declare function windowsAt(pageW: number, pageH: number, cx: number, cy: number): Rect[];
29
42
  /** The diagram at a point of the page (fractions), or null when no board is found there. */
30
- export declare function readAt(recognizer: Recognizer, page: HTMLCanvasElement, fx: number, fy: number): Promise<Diagram | null>;
43
+ export declare function readAt(scanner: Scanner, page: Canvas, fx: number, fy: number): Promise<Diagram | null>;
31
44
  /**
32
45
  * The diagram in a box the reader drew on the page (fractions of the page), for one neither the search nor a
33
46
  * double-click found: the box with a little room around it, then the box itself. Null when it cannot be read.
34
47
  */
35
- export declare function readBox(recognizer: Recognizer, page: HTMLCanvasElement, box: {
48
+ export declare function readBox(scanner: Scanner, page: Canvas, box: {
36
49
  x0: number;
37
50
  y0: number;
38
51
  x1: number;
@@ -47,5 +60,5 @@ export declare function readBox(recognizer: Recognizer, page: HTMLCanvasElement,
47
60
  * of every such page instead found the same diagrams and took four times as long (325 s against 83 s on a book
48
61
  * of 187 pages). The page's canvas is drawn over: pass a copy.
49
62
  */
50
- export declare function findDiagrams(recognizer: Recognizer, page: HTMLCanvasElement, onFound?: (d: Diagram) => void): Promise<Diagram[]>;
63
+ export declare function findDiagrams(scanner: Scanner, page: Canvas, onFound?: (d: Diagram) => void): Promise<Diagram[]>;
51
64
  export {};
package/dist/find.js CHANGED
@@ -1,17 +1,16 @@
1
1
  /**
2
- * Diagrams on a page of a book. Two ways in:
2
+ * Diagrams on a page of a book. Three ways in:
3
3
  * - findDiagrams reads a whole page in the background: the board finder is run, what it found is covered, and it
4
4
  * is run again, so a page with several diagrams gives them all;
5
5
  * - readAt reads the diagram under a double-click, for a diagram the background pass missed: a window around
6
- * the click, then wider ones, until a board is found that the click is on.
6
+ * the click, then wider ones, until a board is found that the click is on;
7
+ * - readBox reads the diagram in a box the reader drew.
7
8
  * Measured 2026-12-05 on a modern typeset book (41 pages): a board found on 37, every one read with all squares
8
9
  * at 75% or more. An old scanned printing reads far worse; such a read opens in the editor to be checked.
9
10
  */
10
11
  import { boardness, findBlurredBoardCandidates, findChessboardCorners, rgbaToGray, snapCorners } from "@scoriiu/fenshot";
11
12
  /** A read worth showing as a diagram without being asked: every square at least this sure. */
12
13
  export const SURE = 0.6;
13
- /** Raised when the finder finds more than it did: pages it searched before are then searched again. */
14
- export const FINDER = 5;
15
14
  /** A page of exercises holds six or eight diagrams, sometimes twelve. Each look finds one. */
16
15
  const MAX_LOOKS = 24;
17
16
  /**
@@ -89,13 +88,13 @@ export function windowsAt(pageW, pageH, cx, cy) {
89
88
  }
90
89
  /** The board's corners in the pixels of what was read: the recognizer answers in its own, smaller frame. */
91
90
  function inPixels(r, width) {
92
- const k = r.frame ? width / r.frame.width : 1;
91
+ const k = width / r.frame.width;
93
92
  return { x0: r.corners.x0 * k, y0: r.corners.y0 * k, x1: r.corners.x1 * k, y1: r.corners.y1 * k };
94
93
  }
95
- async function read(recognizer, source, [x, y, w, h], pageW, pageH) {
96
- const bitmap = await createImageBitmap(source, x, y, w, h);
97
- const r = await recognizer.recognize(bitmap);
98
- bitmap.close();
94
+ async function read(scanner, source, [x, y, w, h], pageW, pageH) {
95
+ const part = new OffscreenCanvas(w, h);
96
+ part.getContext("2d")?.drawImage(source, x, y, w, h, 0, 0, w, h);
97
+ const r = await scanner.recognize(part);
99
98
  if (!r || !readable(r))
100
99
  return null;
101
100
  const { x0, y0, x1, y1 } = inPixels(r, w);
@@ -109,11 +108,11 @@ const holds = (d, fx, fy) => {
109
108
  return fx >= d.x0 - padX && fx <= d.x1 + padX && fy >= d.y0 - padY && fy <= d.y1 + padY;
110
109
  };
111
110
  /** The diagram at a point of the page (fractions), or null when no board is found there. */
112
- export async function readAt(recognizer, page, fx, fy) {
111
+ export async function readAt(scanner, page, fx, fy) {
113
112
  const { width: w, height: h } = page;
114
113
  let best = null;
115
114
  for (const rect of windowsAt(w, h, fx * w, fy * h)) {
116
- const d = await read(recognizer, page, rect, w, h);
115
+ const d = await read(scanner, page, rect, w, h);
117
116
  if (!d || !holds(d, fx, fy))
118
117
  continue;
119
118
  if (d.min >= SURE)
@@ -127,13 +126,13 @@ export async function readAt(recognizer, page, fx, fy) {
127
126
  * The diagram in a box the reader drew on the page (fractions of the page), for one neither the search nor a
128
127
  * double-click found: the box with a little room around it, then the box itself. Null when it cannot be read.
129
128
  */
130
- export async function readBox(recognizer, page, box) {
129
+ export async function readBox(scanner, page, box) {
131
130
  const { width: w, height: h } = page;
132
131
  const x0 = box.x0 * w, y0 = box.y0 * h, bw = (box.x1 - box.x0) * w, bh = (box.y1 - box.y0) * h;
133
132
  for (const room of [0.08, 0]) {
134
133
  const left = Math.max(0, Math.round(x0 - bw * room)), top = Math.max(0, Math.round(y0 - bh * room));
135
134
  const right = Math.min(w, Math.round(x0 + bw * (1 + room))), bottom = Math.min(h, Math.round(y0 + bh * (1 + room)));
136
- const d = await read(recognizer, page, [left, top, right - left, bottom - top], w, h);
135
+ const d = await read(scanner, page, [left, top, right - left, bottom - top], w, h);
137
136
  if (d)
138
137
  return d;
139
138
  }
@@ -182,7 +181,7 @@ function boardOn(page, scratch, pageW = page.width) {
182
181
  * model read. Answers the box to cover before the next look (null when nothing board-like is left) and the
183
182
  * diagram when it read surely. Boxes are in the page's pixels.
184
183
  */
185
- async function lookIn(recognizer, page, [x, y, w, h], scratch, crop) {
184
+ async function lookIn(scanner, page, [x, y, w, h], scratch, crop) {
186
185
  const whole = x === 0 && y === 0 && w === page.width && h === page.height;
187
186
  const region = whole ? page : crop;
188
187
  if (!whole) {
@@ -193,9 +192,7 @@ async function lookIn(recognizer, page, [x, y, w, h], scratch, crop) {
193
192
  const box = boardOn(region, scratch, page.width);
194
193
  if (!box)
195
194
  return null;
196
- const bitmap = await createImageBitmap(region);
197
- const r = await recognizer.recognize(bitmap);
198
- bitmap.close();
195
+ const r = await scanner.recognize(region);
199
196
  const shift = (b) => ({ x0: b.x0 + x, y0: b.y0 + y, x1: b.x1 + x, y1: b.y1 + y });
200
197
  const read = r && shift(inPixels(r, w));
201
198
  if (!r || !read || !plausible(read.x0, read.y0, read.x1, read.y1, page.width) || r.minConfidence < SURE)
@@ -236,17 +233,17 @@ function gapsIn(found, w, h) {
236
233
  * of every such page instead found the same diagrams and took four times as long (325 s against 83 s on a book
237
234
  * of 187 pages). The page's canvas is drawn over: pass a copy.
238
235
  */
239
- export async function findDiagrams(recognizer, page, onFound) {
236
+ export async function findDiagrams(scanner, page, onFound) {
240
237
  const { width: w, height: h } = page;
241
238
  const pen = page.getContext("2d");
242
239
  if (!pen)
243
240
  return [];
244
- const scratch = document.createElement("canvas"), crop = document.createElement("canvas");
241
+ const scratch = new OffscreenCanvas(1, 1), crop = new OffscreenCanvas(1, 1);
245
242
  const found = [];
246
243
  let looks = 0;
247
244
  const search = async (rect, tries) => {
248
245
  for (let i = 0; i < tries && looks < MAX_LOOKS; i++, looks++) {
249
- const seen = await lookIn(recognizer, page, rect, scratch, crop);
246
+ const seen = await lookIn(scanner, page, rect, scratch, crop);
250
247
  if (!seen)
251
248
  return;
252
249
  const d = seen.diagram;
package/dist/host.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { type ComponentType, type ReactNode } from "react";
2
- import type { Recognizer } from "@scoriiu/fenshot";
2
+ import type { Recognition } from "./protocol";
3
3
  import type { Diagram } from "./store";
4
4
  /**
5
- * What a site gives the reader: the recognizer it already serves, where pdf.js's files are, its words, where to
5
+ * What a site gives the reader: where the model and pdf.js's files are, the search worker, its words, where to
6
6
  * count what readers do, and the board beside the page. fenshot.com and kibitzo.com each give their own; the
7
7
  * reader itself (finding diagrams, the pages, the library) is this one package, so the two can never drift.
8
8
  */
@@ -17,7 +17,14 @@ export interface BoardPanelProps {
17
17
  onClose(): void;
18
18
  }
19
19
  export interface ReaderHost {
20
- recognizer: Recognizer;
20
+ /** Where the tile model (@scoriiu/fenshot's chess-tiles-v2.onnx) and onnxruntime-web's wasm files are served. */
21
+ recognition: Recognition;
22
+ /**
23
+ * Start the search worker. The site has a file of one line, `import "@kibitzo/chess-book-reader/worker"`, and
24
+ * answers here with `new Worker(new URL("./that-file", import.meta.url), { type: "module" })`, so its own
25
+ * bundler builds the worker. Called once for a book that is opened; the reader ends it.
26
+ */
27
+ searchWorker(): Worker;
21
28
  /** pdf.js: its worker, and a base address holding wasm/, cmaps/, standard_fonts/ and iccs/ (scripts/sync-pdfjs.mjs). */
22
29
  pdf: {
23
30
  workerSrc: string;
@@ -86,5 +93,5 @@ export declare const ReaderHostProvider: import("react").Provider<ReaderHost | n
86
93
  export declare function useReaderHost(): ReaderHost;
87
94
  /** The site's words, as `t`. */
88
95
  export declare const useT: () => (key: ReaderKey, vars?: Record<string, string | number>) => string;
89
- /** `track`, safe to call when the site counts nothing. */
96
+ /** `track`, safe to call when the site counts nothing. The same function from one render to the next. */
90
97
  export declare function useTrack(): (event: string, data?: Record<string, string | number | boolean>) => void | undefined;
package/dist/host.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createContext, useContext } from "react";
1
+ import { createContext, useCallback, useContext } from "react";
2
2
  export const READER_EN = {
3
3
  "readWhy1": "Every diagram, counted",
4
4
  "readWhy1Sub": "fenshot goes through the whole book as you read. The bar says how many diagrams it holds, and its arrows take you from one to the next.",
@@ -59,8 +59,8 @@ export function useReaderHost() {
59
59
  }
60
60
  /** The site's words, as `t`. */
61
61
  export const useT = () => useReaderHost().t;
62
- /** `track`, safe to call when the site counts nothing. */
62
+ /** `track`, safe to call when the site counts nothing. The same function from one render to the next. */
63
63
  export function useTrack() {
64
64
  const { track } = useReaderHost();
65
- return (event, data) => track?.(event, data);
65
+ return useCallback((event, data) => track?.(event, data), [track]);
66
66
  }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { BookReader } from "./ReadApp";
2
2
  export { READER_EN, englishWords, type BoardPanelProps, type Picked, type ReaderHost, type ReaderKey } from "./host";
3
+ export type { Recognition } from "./protocol";
3
4
  export { handOver, type Book, type Diagram } from "./store";
package/dist/pdf.d.ts CHANGED
@@ -19,17 +19,25 @@ export declare function chaptersOf(doc: Doc): Promise<{
19
19
  page: number;
20
20
  depth: number;
21
21
  }[]>;
22
+ /** A piece of a page's text and where it starts, in fractions of the page. */
23
+ export interface Word {
24
+ text: string;
25
+ fx: number;
26
+ fy: number;
27
+ }
28
+ /** A page's text, read once for all of its diagrams. Empty for a scan. */
29
+ export declare function wordsOf(doc: Doc, n: number): Promise<Word[]>;
22
30
  /**
23
31
  * Who is to move in a diagram, when the book says so in the words beside it ("Black to play"): the nearest such
24
32
  * words under the board, or over it. Null when the page has no text (a scan) or says nothing.
25
33
  * `box` is the diagram in fractions of the page.
26
34
  */
27
- export declare function turnNear(doc: Doc, n: number, box: {
35
+ export declare function turnNear(words: Word[], box: {
28
36
  x0: number;
29
37
  y0: number;
30
38
  x1: number;
31
39
  y1: number;
32
- }): Promise<"w" | "b" | null>;
40
+ }): "w" | "b" | null;
33
41
  /** The book's first page as a small picture, for its card in the library. */
34
42
  export declare function coverOf(doc: Doc): Promise<string | undefined>;
35
43
  /**
@@ -38,9 +46,9 @@ export declare function coverOf(doc: Doc): Promise<string | undefined>;
38
46
  * null when the page says nothing (the coordinates are part of a picture, or there are none).
39
47
  * `box` is the diagram in fractions of the page.
40
48
  */
41
- export declare function sideBelow(doc: Doc, n: number, box: {
49
+ export declare function sideBelow(words: Word[], box: {
42
50
  x0: number;
43
51
  y0: number;
44
52
  x1: number;
45
53
  y1: number;
46
- }): Promise<"white" | "black" | null>;
54
+ }): "white" | "black" | null;
package/dist/pdf.js CHANGED
@@ -55,26 +55,33 @@ export async function chaptersOf(doc) {
55
55
  const caption = (words) => new RegExp(`(${words})[\\s.!:]*$`);
56
56
  const BLACK_MOVES = caption("black to (move|play)|black'?s move|schwarz am zug|schwarz zieht|trait aux noirs|les noirs jouent|juegan (las )?negras|negras juegan|mueven (las )?negras|negrul (muta|la mutare)|mut[aă] negrul|il nero muove|muove il nero|tocca al nero|zwart aan zet|pretas jogam|jogam as pretas|ход ч[её]рных|ч[её]рные начинают");
57
57
  const WHITE_MOVES = caption("white to (move|play)|white'?s move|wei(ss|ß) am zug|wei(ss|ß) zieht|trait aux blancs|les blancs jouent|juegan (las )?blancas|blancas juegan|mueven (las )?blancas|albul (muta|la mutare)|mut[aă] albul|il bianco muove|muove il bianco|tocca al bianco|wit aan zet|brancas jogam|jogam as brancas|ход белых|белые начинают");
58
+ /** A page's text, read once for all of its diagrams. Empty for a scan. */
59
+ export async function wordsOf(doc, n) {
60
+ const page = await doc.getPage(n);
61
+ const view = page.getViewport({ scale: 1 });
62
+ const out = [];
63
+ for (const item of (await page.getTextContent()).items) {
64
+ if (!("str" in item) || !item.str.trim())
65
+ continue;
66
+ const [x, y] = view.convertToViewportPoint(item.transform[4], item.transform[5]);
67
+ out.push({ text: item.str, fx: x / view.width, fy: y / view.height });
68
+ }
69
+ return out;
70
+ }
58
71
  /**
59
72
  * Who is to move in a diagram, when the book says so in the words beside it ("Black to play"): the nearest such
60
73
  * words under the board, or over it. Null when the page has no text (a scan) or says nothing.
61
74
  * `box` is the diagram in fractions of the page.
62
75
  */
63
- export async function turnNear(doc, n, box) {
64
- const page = await doc.getPage(n);
65
- const view = page.getViewport({ scale: 1 });
76
+ export function turnNear(words, box) {
66
77
  const side = box.x1 - box.x0, height = box.y1 - box.y0;
67
78
  const near = [];
68
- for (const item of (await page.getTextContent()).items) {
69
- if (!("str" in item) || !item.str.trim())
70
- continue;
71
- const [x, y] = view.convertToViewportPoint(item.transform[4], item.transform[5]);
72
- const fx = x / view.width, fy = y / view.height;
79
+ for (const { text, fx, fy } of words) {
73
80
  if (fx < box.x0 - side * 0.6 || fx > box.x1 + side * 0.2)
74
81
  continue;
75
82
  const gap = fy > box.y1 ? fy - box.y1 : fy < box.y0 ? (box.y0 - fy) * 1.5 : null;
76
83
  if (gap !== null && gap < height * 0.7)
77
- near.push({ gap, text: item.str });
84
+ near.push({ gap, text });
78
85
  }
79
86
  near.sort((a, b) => a.gap - b.gap);
80
87
  for (const { text } of near) {
@@ -103,19 +110,13 @@ export async function coverOf(doc) {
103
110
  * null when the page says nothing (the coordinates are part of a picture, or there are none).
104
111
  * `box` is the diagram in fractions of the page.
105
112
  */
106
- export async function sideBelow(doc, n, box) {
107
- const page = await doc.getPage(n);
108
- const view = page.getViewport({ scale: 1 });
113
+ export function sideBelow(words, box) {
109
114
  const side = box.x1 - box.x0, height = box.y1 - box.y0;
110
115
  const at = new Map();
111
- for (const item of (await page.getTextContent()).items) {
112
- if (!("str" in item))
113
- continue;
114
- const mark = item.str.trim().toLowerCase();
116
+ for (const { text, fx, fy } of words) {
117
+ const mark = text.trim().toLowerCase();
115
118
  if (!/^[a-h1-8]$/.test(mark))
116
119
  continue;
117
- const [x, y] = view.convertToViewportPoint(item.transform[4], item.transform[5]);
118
- const fx = x / view.width, fy = y / view.height;
119
120
  const beside = fy > box.y0 - height * 0.05 && fy < box.y1 + height * 0.1 && (Math.abs(fx - box.x0) < side * 0.18 || Math.abs(fx - box.x1) < side * 0.18);
120
121
  const under = fx > box.x0 - side * 0.05 && fx < box.x1 + side * 0.05 && (Math.abs(fy - box.y1) < height * 0.18 || Math.abs(fy - box.y0) < height * 0.18);
121
122
  if (/[1-8]/.test(mark) ? beside : under)
@@ -0,0 +1,64 @@
1
+ import type { Diagram } from "./store";
2
+ /**
3
+ * What the page and the search worker say to each other (search.ts on the page, worker.ts in the worker). The
4
+ * page draws a book's page into a picture and hands it over; everything after that (finding the boards, the
5
+ * model, the marks beside a board) happens in the worker, so the page's own thread stays free for the reader.
6
+ */
7
+ /** Raised when the finder finds more than it did: pages it searched before are then searched again. */
8
+ export declare const FINDER = 5;
9
+ export type Box = {
10
+ x0: number;
11
+ y0: number;
12
+ x1: number;
13
+ y1: number;
14
+ };
15
+ /** Where the model and its runtime are, as absolute addresses (a worker cannot resolve the page's relative ones). */
16
+ export interface Recognition {
17
+ modelUrl: string;
18
+ wasmPaths: string | {
19
+ mjs: string;
20
+ wasm: string;
21
+ };
22
+ }
23
+ export type Ask = {
24
+ type: "init";
25
+ recognition: Recognition;
26
+ }
27
+ /** Every diagram of a page. */
28
+ | {
29
+ type: "page";
30
+ id: number;
31
+ bitmap: ImageBitmap;
32
+ }
33
+ /** The diagram at a point of a page (fractions). */
34
+ | {
35
+ type: "at";
36
+ id: number;
37
+ bitmap: ImageBitmap;
38
+ fx: number;
39
+ fy: number;
40
+ }
41
+ /** The diagram in a box the reader drew (fractions). */
42
+ | {
43
+ type: "box";
44
+ id: number;
45
+ bitmap: ImageBitmap;
46
+ box: Box;
47
+ };
48
+ export type Tell = {
49
+ type: "found";
50
+ id: number;
51
+ diagram: Diagram;
52
+ } | {
53
+ type: "page";
54
+ id: number;
55
+ diagrams: Diagram[];
56
+ } | {
57
+ type: "read";
58
+ id: number;
59
+ diagram: Diagram | null;
60
+ } | {
61
+ type: "error";
62
+ id: number;
63
+ message: string;
64
+ };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * What the page and the search worker say to each other (search.ts on the page, worker.ts in the worker). The
3
+ * page draws a book's page into a picture and hands it over; everything after that (finding the boards, the
4
+ * model, the marks beside a board) happens in the worker, so the page's own thread stays free for the reader.
5
+ */
6
+ /** Raised when the finder finds more than it did: pages it searched before are then searched again. */
7
+ export const FINDER = 5;
@@ -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
+ }
@@ -1,6 +1,7 @@
1
1
  import { type RefObject } from "react";
2
- import type { Box, Point } from "./PageView";
2
+ import type { Point } from "./PageView";
3
3
  import { type Doc } from "./pdf";
4
+ import { type Box } from "./protocol";
4
5
  import { type Diagram } from "./store";
5
6
  /** A diagram and the page it is on. */
6
7
  export interface Spot {
@@ -9,10 +10,16 @@ export interface Spot {
9
10
  }
10
11
  /** The same diagram, found twice. */
11
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;
12
18
  export declare function useDiagrams(doc: Doc, bookId: string, page: number, pane: RefObject<HTMLDivElement | null>): {
13
19
  found: Map<number, Diagram[]>;
14
20
  all: Spot[];
15
21
  searched: number;
22
+ busy: boolean;
16
23
  readPoint: (p: Point) => Promise<Diagram | null>;
17
24
  readIn: (n: number, box: Box) => Promise<Diagram | null>;
18
25
  };
@@ -1,28 +1,35 @@
1
1
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
2
  import { flipPlacement } from "@scoriiu/fenshot";
3
- import { useReaderHost } from "./host";
4
- import { FINDER, findDiagrams, readAt, readBox } from "./find";
5
- import { drawPage, sideBelow, turnNear } from "./pdf";
3
+ import { useReaderHost, useTrack } from "./host";
4
+ import { drawPage, sideBelow, turnNear, wordsOf } from "./pdf";
5
+ import { FINDER } from "./protocol";
6
+ import { openSearch } from "./search";
6
7
  import { allDiagrams, diagramsOf, saveDiagrams } from "./store";
7
8
  /**
8
- * The diagrams of a book. Every page is searched once, in the background: the page being read and the next one
9
- * first, then the rest of the book from there on, one page at a time and only while the reader is not scrolling.
10
- * What is found is kept (store.ts), so a book opened again has its diagrams at once. A double-click reads the
11
- * diagram under it, for one the search missed. One read runs at a time: the search and a double-click take turns.
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).
12
18
  */
13
19
  /** How wide a page is drawn for reading its diagrams: a board of a quarter page then has squares of about 50 px. */
14
20
  const READ_WIDTH = 1700, FIND_WIDTH = 1300;
15
21
  /** The reader has stopped scrolling when the pages have been still this long. */
16
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;
17
26
  /** The same diagram, found twice. */
18
27
  export const same = (a, b) => Math.abs(a.x0 - b.x0) < 0.03 && Math.abs(a.y0 - b.y0) < 0.03;
19
28
  /** The order they are read in: row by row, each row from the left. */
20
29
  const inReadingOrder = (a, b) => (Math.abs(a.y0 - b.y0) > (a.y1 - a.y0) / 2 ? a.y0 - b.y0 : a.x0 - b.x0);
21
- const pause = (ms) => new Promise((r) => setTimeout(r, ms));
22
- async function canvasOf(doc, n, width) {
23
- const canvas = document.createElement("canvas");
30
+ async function pictureOf(doc, n, width, canvas) {
24
31
  await (await drawPage(doc, n, width, canvas)).promise;
25
- return canvas;
32
+ return createImageBitmap(canvas);
26
33
  }
27
34
  /**
28
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
@@ -30,26 +37,44 @@ async function canvasOf(doc, n, width) {
30
37
  * otherwise: the scanner's guess from where the pawns stand is wrong for an endgame with pawns far up the board
31
38
  * (3 of 44 diagrams in a book of exercises, measured 2026-12-05), so it is not asked here.
32
39
  */
33
- async function withTurn(doc, n, d) {
34
- const [turn, below] = await Promise.all([turnNear(doc, n, d).catch(() => null), sideBelow(doc, n, d).catch(() => null)]);
40
+ function withWords(words, d) {
41
+ const turn = turnNear(words, d);
35
42
  const told = turn ? { ...d, turn } : d;
36
- return below === "black" && !told.flipped ? { ...told, placement: flipPlacement(told.placement), flipped: true } : told;
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;
37
58
  }
38
59
  export function useDiagrams(doc, bookId, page, pane) {
39
60
  const pages = doc.numPages;
40
- const { recognizer } = useReaderHost();
61
+ const { searchWorker, recognition } = useReaderHost();
62
+ const count = useTrack();
41
63
  const [found, setFound] = useState(new Map());
42
- /** How many pages have been searched. */
64
+ /** How many pages have been searched, and whether a search is going on or waiting. */
43
65
  const [searched, setSearched] = useState(0);
66
+ const [busy, setBusy] = useState(true);
67
+ const search = useRef(null);
44
68
  const seen = useRef(new Set());
45
69
  const full = useRef(new Set());
46
- const line = useRef(Promise.resolve());
47
- const inTurn = useCallback((job) => {
48
- const next = line.current.then(job, job);
49
- line.current = next.catch(() => { });
50
- return next;
51
- }, []);
52
- useEffect(() => { recognizer.warmUp(); }, [recognizer]);
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]);
53
78
  /** Add diagrams to a page's, each once. */
54
79
  const show = useCallback((n, list) => {
55
80
  setFound((old) => {
@@ -57,49 +82,54 @@ export function useDiagrams(doc, bookId, page, pane) {
57
82
  return fresh.length ? new Map(old).set(n, [...known, ...fresh]) : old;
58
83
  });
59
84
  }, []);
60
- const done = useCallback((n) => { full.current.add(n); setSearched(full.current.size); }, []);
61
- /** Search a page, unless it was searched before by this finder. */
62
- const search = useCallback(async (n) => {
63
- try {
64
- const kept = await diagramsOf(bookId, n);
65
- let list = kept?.list ?? [];
66
- if (!kept?.full || kept.finder !== FINDER) {
67
- // Each diagram shows as soon as it is found: a page of six is not kept waiting for the sixth.
68
- const told = [];
69
- await findDiagrams(recognizer, await canvasOf(doc, n, FIND_WIDTH), (d) => told.push(withTurn(doc, n, d).then((known) => { show(n, [known]); return known; })));
70
- const searchedNow = await Promise.all(told);
71
- list = [...searchedNow, ...list.filter((d) => !searchedNow.some((k) => same(k, d)))];
72
- void saveDiagrams(bookId, n, { full: true, finder: FINDER, list });
73
- }
74
- show(n, list);
75
- }
76
- catch { /* a page that cannot be read has no diagrams */ }
77
- done(n);
78
- }, [doc, bookId, show, done, recognizer]);
79
- // First the page being read and the next one.
80
85
  useEffect(() => {
81
- let gone = false;
82
- const id = setTimeout(() => {
83
- for (const n of [page, page + 1]) {
84
- if (n > pages || seen.current.has(n))
85
- continue;
86
- seen.current.add(n);
87
- void inTurn(async () => { if (gone)
88
- seen.current.delete(n);
89
- else
90
- await search(n); });
91
- }
92
- }, 280);
93
- return () => { gone = true; clearTimeout(id); };
94
- }, [page, pages, inTurn, search]);
95
- // Then the whole book, from the page it was opened on: what was kept at once, the rest page by page.
96
- const from = useRef(page);
97
- useEffect(() => {
98
- let gone = false, moved = 0;
86
+ const s = openSearch(searchWorker(), recognition);
87
+ search.current = s;
88
+ let gone = false, moved = 0, worked = false, total = 0, failed = 0;
99
89
  const el = pane.current;
100
90
  const onScroll = () => { moved = performance.now(); };
101
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
+ };
102
131
  void (async () => {
132
+ // What was kept from before, at once.
103
133
  const kept = await allDiagrams(bookId).catch(() => new Map());
104
134
  if (gone)
105
135
  return;
@@ -108,39 +138,71 @@ export function useDiagrams(doc, bookId, page, pane) {
108
138
  continue;
109
139
  seen.current.add(n);
110
140
  show(n, known.list);
111
- done(n);
141
+ finished(n, known.list);
112
142
  }
113
- for (let i = 0; i < pages && !gone; i++) {
114
- const n = ((from.current - 1 + i) % pages) + 1;
115
- while (!gone && (document.hidden || performance.now() - moved < STILL_MS))
116
- await pause(200);
117
- if (gone || seen.current.has(n))
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);
118
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
+ }
119
166
  seen.current.add(n);
120
- await inTurn(() => search(n));
121
- await pause(40);
167
+ await searchPage(n);
122
168
  }
123
169
  })();
124
- return () => { gone = true; el?.removeEventListener("scroll", onScroll); };
125
- }, [bookId, pages, pane, inTurn, search, show, done]);
126
- /** A diagram the reader pointed at joins its page's, in place of one found there before. */
127
- const keep = useCallback(async (n, read) => {
128
- if (!read)
129
- return null;
130
- const diagram = await withTurn(doc, n, read);
131
- setFound((old) => {
132
- const list = [...(old.get(n) ?? []).filter((d) => !same(d, diagram)), diagram];
133
- void saveDiagrams(bookId, n, { full: full.current.has(n), finder: FINDER, list });
134
- return new Map(old).set(n, list);
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
+ }
135
197
  });
136
- return diagram;
137
- }, [doc, bookId]);
198
+ wake.current();
199
+ }), [doc, bookId]);
138
200
  /** The diagram at a point of a page, read now; null when none can be read there. */
139
- const readPoint = useCallback((p) => inTurn(async () => keep(p.page, await readAt(recognizer, await canvasOf(doc, p.page, READ_WIDTH), p.fx, p.fy))), [doc, inTurn, keep]);
201
+ const readPoint = useCallback((p) => asked(p.page, (s, picture) => s.at(picture, p.fx, p.fy)), [asked]);
140
202
  /** The diagram in a box the reader drew on a page; null when it cannot be read. */
141
- const readIn = useCallback((n, box) => inTurn(async () => keep(n, await readBox(recognizer, await canvasOf(doc, n, READ_WIDTH), box))), [doc, inTurn, keep]);
203
+ const readIn = useCallback((n, box) => asked(n, (s, picture) => s.box(picture, box)), [asked]);
142
204
  /** Every diagram found so far, in the order of the book. */
143
205
  const all = useMemo(() => [...found.keys()].sort((a, b) => a - b)
144
206
  .flatMap((n) => [...(found.get(n) ?? [])].sort(inReadingOrder).map((diagram) => ({ page: n, diagram }))), [found]);
145
- return { found, all, searched, readPoint, readIn };
207
+ return { found, all, searched, busy, readPoint, readIn };
146
208
  }
@@ -0,0 +1 @@
1
+ export {};
package/dist/worker.js ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The search for diagrams, in a worker of its own (founder 2026-12-05: searching a book made the page stutter,
3
+ * 172 freezes of over 0.2 s on a book of 196 pages, because the board finder and the model ran on the thread that
4
+ * also scrolls the page). A site starts it with a file of one line, `import "@kibitzo/chess-book-reader/worker"`,
5
+ * so that its own bundler builds the worker. One job at a time, in the order they arrive: the page decides the
6
+ * order (useDiagrams).
7
+ */
8
+ import { extractTiles, probsToPlacement, recognizeGray, rgbaToGray } from "@scoriiu/fenshot";
9
+ import { findDiagrams, readAt, readBox } from "./find";
10
+ const scope = self;
11
+ /** The recognizer looks at a picture no larger than this (as @scoriiu/fenshot's own recognize does). */
12
+ const MAX_DIM = 1600;
13
+ let model = null;
14
+ let recognition = null;
15
+ function load({ modelUrl, wasmPaths }) {
16
+ return (model ??= (async () => {
17
+ // The plain wasm build, as the recognizer itself loads it.
18
+ const ort = (await import("onnxruntime-web/wasm"));
19
+ ort.env.wasm.wasmPaths = wasmPaths;
20
+ return { ort, session: await ort.InferenceSession.create(modelUrl, { executionProviders: ["wasm"] }) };
21
+ })());
22
+ }
23
+ const frame = new OffscreenCanvas(1, 1);
24
+ const scanner = {
25
+ async recognize(source) {
26
+ // A model that did not load (the network) is asked for again by the next page.
27
+ if (!model && recognition)
28
+ void load(recognition).catch(() => { model = null; });
29
+ if (!model)
30
+ throw new Error("the search worker was not started");
31
+ const k = Math.min(1, MAX_DIM / Math.max(source.width, source.height));
32
+ const width = Math.round(source.width * k), height = Math.round(source.height * k);
33
+ frame.width = width;
34
+ frame.height = height;
35
+ const pen = frame.getContext("2d", { willReadFrequently: true });
36
+ if (!pen)
37
+ return null;
38
+ pen.drawImage(source, 0, 0, width, height);
39
+ const gray = rgbaToGray(pen.getImageData(0, 0, width, height).data, width, height);
40
+ const { ort, session } = await model;
41
+ const scan = await recognizeGray(gray, async (corners) => {
42
+ const out = await session.run({ tiles: new ort.Tensor("float32", extractTiles(gray, corners), [64, 1024]) });
43
+ return probsToPlacement(out["probs"].data);
44
+ });
45
+ return scan && { ...scan, frame: { width, height } };
46
+ },
47
+ };
48
+ /** The picture as a canvas the search may draw over and read pixels from. */
49
+ function canvasOf(bitmap) {
50
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
51
+ canvas.getContext("2d", { willReadFrequently: true })?.drawImage(bitmap, 0, 0);
52
+ bitmap.close();
53
+ return canvas;
54
+ }
55
+ async function answer(ask) {
56
+ if (ask.type === "init") {
57
+ recognition = ask.recognition;
58
+ void load(recognition).catch(() => { model = null; });
59
+ return;
60
+ }
61
+ const page = canvasOf(ask.bitmap);
62
+ if (ask.type === "page") {
63
+ const diagrams = await findDiagrams(scanner, page, (diagram) => scope.postMessage({ type: "found", id: ask.id, diagram }));
64
+ scope.postMessage({ type: "page", id: ask.id, diagrams });
65
+ }
66
+ else {
67
+ const diagram = ask.type === "at" ? await readAt(scanner, page, ask.fx, ask.fy) : await readBox(scanner, page, ask.box);
68
+ scope.postMessage({ type: "read", id: ask.id, diagram });
69
+ }
70
+ }
71
+ let line = Promise.resolve();
72
+ scope.onmessage = (e) => {
73
+ const ask = e.data;
74
+ line = line.then(() => answer(ask)).catch((err) => {
75
+ if (ask.type !== "init")
76
+ scope.postMessage({ type: "error", id: ask.id, message: String(err) });
77
+ });
78
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kibitzo/chess-book-reader",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A chess-book reader for the browser: open a PDF, every diagram is found and read, a click puts it on your board beside the page. React, with the board, words and look given by the site.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -10,13 +10,18 @@
10
10
  "types": "./dist/index.d.ts",
11
11
  "import": "./dist/index.js"
12
12
  },
13
- "./reader.css": "./dist/reader.css"
13
+ "./reader.css": "./dist/reader.css",
14
+ "./worker": {
15
+ "types": "./dist/worker.d.ts",
16
+ "import": "./dist/worker.js"
17
+ }
14
18
  },
15
19
  "files": [
16
20
  "dist"
17
21
  ],
18
22
  "sideEffects": [
19
- "*.css"
23
+ "*.css",
24
+ "./dist/worker.js"
20
25
  ],
21
26
  "scripts": {
22
27
  "build": "tsc -p tsconfig.build.json && cp src/reader.css dist/reader.css",
@@ -27,13 +32,15 @@
27
32
  },
28
33
  "peerDependencies": {
29
34
  "@scoriiu/fenshot": ">=0.1.6",
35
+ "onnxruntime-web": ">=1.17.0",
30
36
  "pdfjs-dist": ">=5",
31
37
  "react": ">=18"
32
38
  },
33
39
  "devDependencies": {
34
40
  "@types/react": "^19.0.0",
35
41
  "pdfjs-dist": "6.5.438",
36
- "typescript": "^5.6.0"
42
+ "typescript": "^5.6.0",
43
+ "onnxruntime-web": "1.26.0"
37
44
  },
38
45
  "keywords": [
39
46
  "chess",