@scoriiu/fenshot 0.1.6 → 0.1.7
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 +25 -2
- package/dist/reader/Library.d.ts +11 -0
- package/dist/reader/Library.js +74 -0
- package/dist/reader/PageView.d.ts +35 -0
- package/dist/reader/PageView.js +80 -0
- package/dist/reader/ReadApp.d.ts +9 -0
- package/dist/reader/ReadApp.js +122 -0
- package/dist/reader/Reader.d.ts +8 -0
- package/dist/reader/Reader.js +117 -0
- package/dist/reader/ReaderBar.d.ts +30 -0
- package/dist/reader/ReaderBar.js +36 -0
- package/dist/reader/SideGrip.d.ts +12 -0
- package/dist/reader/SideGrip.js +66 -0
- package/dist/reader/find.d.ts +42 -0
- package/dist/reader/find.js +279 -0
- package/dist/reader/host.d.ts +90 -0
- package/dist/reader/host.js +66 -0
- package/dist/reader/index.d.ts +3 -0
- package/dist/reader/index.js +3 -0
- package/dist/reader/pdf.d.ts +46 -0
- package/dist/reader/pdf.js +130 -0
- package/dist/reader/reader.css +1084 -0
- package/dist/reader/store.d.ts +63 -0
- package/dist/reader/store.js +103 -0
- package/dist/reader/useDiagrams.d.ts +18 -0
- package/dist/reader/useDiagrams.js +146 -0
- package/dist/reader/usePages.d.ts +18 -0
- package/dist/reader/usePages.js +148 -0
- package/package.json +29 -7
|
@@ -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;
|
|
@@ -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,18 @@
|
|
|
1
|
+
import { type RefObject } from "react";
|
|
2
|
+
import type { Box, Point } from "./PageView";
|
|
3
|
+
import { type Doc } from "./pdf";
|
|
4
|
+
import { type Diagram } from "./store";
|
|
5
|
+
/** A diagram and the page it is on. */
|
|
6
|
+
export interface Spot {
|
|
7
|
+
page: number;
|
|
8
|
+
diagram: Diagram;
|
|
9
|
+
}
|
|
10
|
+
/** The same diagram, found twice. */
|
|
11
|
+
export declare const same: (a: Diagram, b: Diagram) => boolean;
|
|
12
|
+
export declare function useDiagrams(doc: Doc, bookId: string, page: number, pane: RefObject<HTMLDivElement | null>): {
|
|
13
|
+
found: Map<number, Diagram[]>;
|
|
14
|
+
all: Spot[];
|
|
15
|
+
searched: number;
|
|
16
|
+
readPoint: (p: Point) => Promise<Diagram | null>;
|
|
17
|
+
readIn: (n: number, box: Box) => Promise<Diagram | null>;
|
|
18
|
+
};
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
2
|
+
import { flipPlacement } from "../fen";
|
|
3
|
+
import { useReaderHost } from "./host";
|
|
4
|
+
import { FINDER, findDiagrams, readAt, readBox } from "./find";
|
|
5
|
+
import { drawPage, sideBelow, turnNear } from "./pdf";
|
|
6
|
+
import { allDiagrams, diagramsOf, saveDiagrams } from "./store";
|
|
7
|
+
/**
|
|
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.
|
|
12
|
+
*/
|
|
13
|
+
/** How wide a page is drawn for reading its diagrams: a board of a quarter page then has squares of about 50 px. */
|
|
14
|
+
const READ_WIDTH = 1700, FIND_WIDTH = 1300;
|
|
15
|
+
/** The reader has stopped scrolling when the pages have been still this long. */
|
|
16
|
+
const STILL_MS = 400;
|
|
17
|
+
/** The same diagram, found twice. */
|
|
18
|
+
export const same = (a, b) => Math.abs(a.x0 - b.x0) < 0.03 && Math.abs(a.y0 - b.y0) < 0.03;
|
|
19
|
+
/** The order they are read in: row by row, each row from the left. */
|
|
20
|
+
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");
|
|
24
|
+
await (await drawPage(doc, n, width, canvas)).promise;
|
|
25
|
+
return canvas;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* A diagram with what the page's words say of it: who is to move (a caption counts for more than a mark beside
|
|
29
|
+
* the board), and which side it is printed from. A book prints from White's side unless its coordinates say
|
|
30
|
+
* otherwise: the scanner's guess from where the pawns stand is wrong for an endgame with pawns far up the board
|
|
31
|
+
* (3 of 44 diagrams in a book of exercises, measured 2026-12-05), so it is not asked here.
|
|
32
|
+
*/
|
|
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)]);
|
|
35
|
+
const told = turn ? { ...d, turn } : d;
|
|
36
|
+
return below === "black" && !told.flipped ? { ...told, placement: flipPlacement(told.placement), flipped: true } : told;
|
|
37
|
+
}
|
|
38
|
+
export function useDiagrams(doc, bookId, page, pane) {
|
|
39
|
+
const pages = doc.numPages;
|
|
40
|
+
const { recognizer } = useReaderHost();
|
|
41
|
+
const [found, setFound] = useState(new Map());
|
|
42
|
+
/** How many pages have been searched. */
|
|
43
|
+
const [searched, setSearched] = useState(0);
|
|
44
|
+
const seen = useRef(new Set());
|
|
45
|
+
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]);
|
|
53
|
+
/** Add diagrams to a page's, each once. */
|
|
54
|
+
const show = useCallback((n, list) => {
|
|
55
|
+
setFound((old) => {
|
|
56
|
+
const known = old.get(n) ?? [], fresh = list.filter((d) => !known.some((k) => same(k, d)));
|
|
57
|
+
return fresh.length ? new Map(old).set(n, [...known, ...fresh]) : old;
|
|
58
|
+
});
|
|
59
|
+
}, []);
|
|
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
|
+
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;
|
|
99
|
+
const el = pane.current;
|
|
100
|
+
const onScroll = () => { moved = performance.now(); };
|
|
101
|
+
el?.addEventListener("scroll", onScroll, { passive: true });
|
|
102
|
+
void (async () => {
|
|
103
|
+
const kept = await allDiagrams(bookId).catch(() => new Map());
|
|
104
|
+
if (gone)
|
|
105
|
+
return;
|
|
106
|
+
for (const [n, known] of kept) {
|
|
107
|
+
if (!known.full || known.finder !== FINDER || n > pages)
|
|
108
|
+
continue;
|
|
109
|
+
seen.current.add(n);
|
|
110
|
+
show(n, known.list);
|
|
111
|
+
done(n);
|
|
112
|
+
}
|
|
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))
|
|
118
|
+
continue;
|
|
119
|
+
seen.current.add(n);
|
|
120
|
+
await inTurn(() => search(n));
|
|
121
|
+
await pause(40);
|
|
122
|
+
}
|
|
123
|
+
})();
|
|
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);
|
|
135
|
+
});
|
|
136
|
+
return diagram;
|
|
137
|
+
}, [doc, bookId]);
|
|
138
|
+
/** 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]);
|
|
140
|
+
/** 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]);
|
|
142
|
+
/** Every diagram found so far, in the order of the book. */
|
|
143
|
+
const all = useMemo(() => [...found.keys()].sort((a, b) => a - b)
|
|
144
|
+
.flatMap((n) => [...(found.get(n) ?? [])].sort(inReadingOrder).map((diagram) => ({ page: n, diagram }))), [found]);
|
|
145
|
+
return { found, all, searched, readPoint, readIn };
|
|
146
|
+
}
|
|
@@ -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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@scoriiu/fenshot",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "Screenshot in, FEN out. Chessboard recognition in the browser: detects the board in any screenshot or book diagram and reads the position with a CNN tile classifier.",
|
|
3
|
+
"version": "0.1.7",
|
|
4
|
+
"description": "Screenshot in, FEN out. Chessboard recognition in the browser: detects the board in any screenshot or book diagram and reads the position with a CNN tile classifier. With a chess-book reader for React (@scoriiu/fenshot/reader).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -10,15 +10,22 @@
|
|
|
10
10
|
"types": "./dist/index.d.ts",
|
|
11
11
|
"import": "./dist/index.js"
|
|
12
12
|
},
|
|
13
|
+
"./reader": {
|
|
14
|
+
"types": "./dist/reader/index.d.ts",
|
|
15
|
+
"import": "./dist/reader/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./reader.css": "./dist/reader/reader.css",
|
|
13
18
|
"./model/chess-tiles-v2.onnx": "./model/chess-tiles-v2.onnx"
|
|
14
19
|
},
|
|
15
20
|
"files": [
|
|
16
21
|
"dist",
|
|
17
22
|
"model"
|
|
18
23
|
],
|
|
19
|
-
"sideEffects":
|
|
24
|
+
"sideEffects": [
|
|
25
|
+
"*.css"
|
|
26
|
+
],
|
|
20
27
|
"scripts": {
|
|
21
|
-
"build": "tsc -p tsconfig.build.json",
|
|
28
|
+
"build": "tsc -p tsconfig.build.json && cp src/reader/reader.css dist/reader/reader.css",
|
|
22
29
|
"test": "vitest run",
|
|
23
30
|
"prepublishOnly": "npm run build && npm run test"
|
|
24
31
|
},
|
|
@@ -26,14 +33,18 @@
|
|
|
26
33
|
"access": "public"
|
|
27
34
|
},
|
|
28
35
|
"peerDependencies": {
|
|
29
|
-
"onnxruntime-web": ">=1.17.0"
|
|
36
|
+
"onnxruntime-web": ">=1.17.0",
|
|
37
|
+
"pdfjs-dist": ">=5",
|
|
38
|
+
"react": ">=18"
|
|
30
39
|
},
|
|
31
40
|
"devDependencies": {
|
|
32
41
|
"@types/pngjs": "^6.0.5",
|
|
33
42
|
"onnxruntime-web": "1.26.0",
|
|
34
43
|
"pngjs": "^7.0.0",
|
|
35
44
|
"typescript": "^5.6.0",
|
|
36
|
-
"vitest": "^3.0.0"
|
|
45
|
+
"vitest": "^3.0.0",
|
|
46
|
+
"@types/react": "^19.0.0",
|
|
47
|
+
"pdfjs-dist": "6.5.438"
|
|
37
48
|
},
|
|
38
49
|
"keywords": [
|
|
39
50
|
"chess",
|
|
@@ -43,7 +54,10 @@
|
|
|
43
54
|
"chessboard",
|
|
44
55
|
"recognition",
|
|
45
56
|
"onnx",
|
|
46
|
-
"lichess"
|
|
57
|
+
"lichess",
|
|
58
|
+
"pdf",
|
|
59
|
+
"chess book",
|
|
60
|
+
"react"
|
|
47
61
|
],
|
|
48
62
|
"author": "Kibitzo (https://kibitzo.com)",
|
|
49
63
|
"license": "MIT",
|
|
@@ -54,5 +68,13 @@
|
|
|
54
68
|
"homepage": "https://github.com/scoriiu/fenshot#readme",
|
|
55
69
|
"bugs": {
|
|
56
70
|
"url": "https://github.com/scoriiu/fenshot/issues"
|
|
71
|
+
},
|
|
72
|
+
"peerDependenciesMeta": {
|
|
73
|
+
"pdfjs-dist": {
|
|
74
|
+
"optional": true
|
|
75
|
+
},
|
|
76
|
+
"react": {
|
|
77
|
+
"optional": true
|
|
78
|
+
}
|
|
57
79
|
}
|
|
58
80
|
}
|