@scoriiu/fenshot 0.1.5 → 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.
@@ -0,0 +1,90 @@
1
+ import { type ComponentType, type ReactNode } from "react";
2
+ import type { Recognizer } from "../recognize";
3
+ import type { Diagram } from "./store";
4
+ /**
5
+ * What a site gives the reader: the recognizer it already serves, where pdf.js's files are, its words, where to
6
+ * count what readers do, and the board beside the page. fenshot.com and kibitzo.com each give their own; the
7
+ * reader itself (finding diagrams, the pages, the library) is this one package, so the two can never drift.
8
+ */
9
+ export interface Picked {
10
+ page: number;
11
+ diagram: Diagram;
12
+ /** Nothing could be read where the reader pointed: an empty board to set up, the book beside it. */
13
+ byHand?: boolean;
14
+ }
15
+ export interface BoardPanelProps {
16
+ picked: Picked;
17
+ onClose(): void;
18
+ }
19
+ export interface ReaderHost {
20
+ recognizer: Recognizer;
21
+ /** pdf.js: its worker, and a base address holding wasm/, cmaps/, standard_fonts/ and iccs/ (scripts/sync-pdfjs.mjs). */
22
+ pdf: {
23
+ workerSrc: string;
24
+ assets: string;
25
+ };
26
+ t(key: ReaderKey, vars?: Record<string, string | number>): string;
27
+ /** One anonymous count of something a reader did. Never the book, a page or a position. */
28
+ track?(event: string, data?: Record<string, string | number | boolean>): void;
29
+ /** The board beside the page, inside the reader's side panel (a bottom sheet on a phone). */
30
+ BoardPanel: ComponentType<BoardPanelProps>;
31
+ /** Over the library: the site's own header. */
32
+ header?: ReactNode;
33
+ /** Under the place to drop a book, while the library is empty (a demo film, say). */
34
+ emptyLibrary?: ReactNode;
35
+ }
36
+ export declare const READER_EN: {
37
+ readonly readWhy1: "Every diagram, counted";
38
+ readonly 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.";
39
+ readonly readWhy2: "Play it, or play Boris";
40
+ readonly readWhy2Sub: "A click puts a diagram on a board next to the page: legal moves, Stockfish if you ask for it, and a game against Kibitzo's coach from that position.";
41
+ readonly readWhy3: "Your PDF stays with you";
42
+ readonly readWhy3Sub: "The book is read by your browser and kept on this computer, never uploaded. It opens again on the page where you left it.";
43
+ readonly readAddBook: "Add a book";
44
+ readonly readByHand: "Set it up by hand";
45
+ readonly readCancel: "Cancel";
46
+ readonly readCantOpen: "This PDF could not be opened.";
47
+ readonly readChoose: "Open a PDF";
48
+ readonly readContents: "Contents";
49
+ readonly readDiagramNext: "Next diagram";
50
+ readonly readDiagramPrev: "Previous diagram";
51
+ readonly readDiagrams: "{n} diagrams in this book";
52
+ readonly readDiagramsShort: "{n} diagrams";
53
+ readonly readDropSub: "or drop it anywhere on this page";
54
+ readonly readDropTitle: "Open a chess book";
55
+ readonly readFinding: "Finding the diagrams: {done} of {pages} pages";
56
+ readonly readGoToPage: "Go to page";
57
+ readonly readHint: "Double-click a diagram";
58
+ readonly readHintSub: "It opens here as a board you can play on. The arrows at the top go from one diagram to the next.";
59
+ readonly readLibrary: "Library";
60
+ readonly readMore: "More";
61
+ readonly readNoDiagram: "No diagram could be read there.";
62
+ readonly readNotPdf: "That file is not a PDF.";
63
+ readonly readOpen: "Open";
64
+ readonly readOpenAt: "Open at page {page}";
65
+ readonly readOpening: "Opening your book…";
66
+ readonly readPageOf: "Page {page} of {pages}";
67
+ readonly readPrivate: "Read inside your browser. Your book is never uploaded.";
68
+ readonly readRemove: "Remove";
69
+ readonly readRemoveAsk: "Remove this book from this device?";
70
+ readonly readRename: "Rename";
71
+ readonly readResize: "Resize the board";
72
+ readonly readSelect: "Select diagram";
73
+ readonly readSelectHint: "Drag a box around the diagram.";
74
+ readonly readSelectTitle: "Draw a box around a diagram that was not found";
75
+ readonly readShelf: "On this device";
76
+ readonly readShelfCount: "{n} books";
77
+ readonly readShelfOne: "1 book";
78
+ readonly readZoomIn: "Larger";
79
+ readonly readZoomOut: "Smaller";
80
+ readonly readZoomReset: "Back to 100%";
81
+ };
82
+ export type ReaderKey = keyof typeof READER_EN;
83
+ /** English words with {placeholders} filled, for a site with no translations of its own. */
84
+ export declare function englishWords(key: ReaderKey, vars?: Record<string, string | number>): string;
85
+ export declare const ReaderHostProvider: import("react").Provider<ReaderHost | null>;
86
+ export declare function useReaderHost(): ReaderHost;
87
+ /** The site's words, as `t`. */
88
+ export declare const useT: () => (key: ReaderKey, vars?: Record<string, string | number>) => string;
89
+ /** `track`, safe to call when the site counts nothing. */
90
+ export declare function useTrack(): (event: string, data?: Record<string, string | number | boolean>) => void | undefined;
@@ -0,0 +1,66 @@
1
+ import { createContext, useContext } from "react";
2
+ export const READER_EN = {
3
+ "readWhy1": "Every diagram, counted",
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.",
5
+ "readWhy2": "Play it, or play Boris",
6
+ "readWhy2Sub": "A click puts a diagram on a board next to the page: legal moves, Stockfish if you ask for it, and a game against Kibitzo's coach from that position.",
7
+ "readWhy3": "Your PDF stays with you",
8
+ "readWhy3Sub": "The book is read by your browser and kept on this computer, never uploaded. It opens again on the page where you left it.",
9
+ "readAddBook": "Add a book",
10
+ "readByHand": "Set it up by hand",
11
+ "readCancel": "Cancel",
12
+ "readCantOpen": "This PDF could not be opened.",
13
+ "readChoose": "Open a PDF",
14
+ "readContents": "Contents",
15
+ "readDiagramNext": "Next diagram",
16
+ "readDiagramPrev": "Previous diagram",
17
+ "readDiagrams": "{n} diagrams in this book",
18
+ "readDiagramsShort": "{n} diagrams",
19
+ "readDropSub": "or drop it anywhere on this page",
20
+ "readDropTitle": "Open a chess book",
21
+ "readFinding": "Finding the diagrams: {done} of {pages} pages",
22
+ "readGoToPage": "Go to page",
23
+ "readHint": "Double-click a diagram",
24
+ "readHintSub": "It opens here as a board you can play on. The arrows at the top go from one diagram to the next.",
25
+ "readLibrary": "Library",
26
+ "readMore": "More",
27
+ "readNoDiagram": "No diagram could be read there.",
28
+ "readNotPdf": "That file is not a PDF.",
29
+ "readOpen": "Open",
30
+ "readOpenAt": "Open at page {page}",
31
+ "readOpening": "Opening your book…",
32
+ "readPageOf": "Page {page} of {pages}",
33
+ "readPrivate": "Read inside your browser. Your book is never uploaded.",
34
+ "readRemove": "Remove",
35
+ "readRemoveAsk": "Remove this book from this device?",
36
+ "readRename": "Rename",
37
+ "readResize": "Resize the board",
38
+ "readSelect": "Select diagram",
39
+ "readSelectHint": "Drag a box around the diagram.",
40
+ "readSelectTitle": "Draw a box around a diagram that was not found",
41
+ "readShelf": "On this device",
42
+ "readShelfCount": "{n} books",
43
+ "readShelfOne": "1 book",
44
+ "readZoomIn": "Larger",
45
+ "readZoomOut": "Smaller",
46
+ "readZoomReset": "Back to 100%"
47
+ };
48
+ /** English words with {placeholders} filled, for a site with no translations of its own. */
49
+ export function englishWords(key, vars) {
50
+ return READER_EN[key].replace(/\{(\w+)\}/g, (m, v) => (vars && v in vars ? String(vars[v]) : m));
51
+ }
52
+ const HostContext = createContext(null);
53
+ export const ReaderHostProvider = HostContext.Provider;
54
+ export function useReaderHost() {
55
+ const host = useContext(HostContext);
56
+ if (!host)
57
+ throw new Error("the reader needs a ReaderHostProvider");
58
+ return host;
59
+ }
60
+ /** The site's words, as `t`. */
61
+ export const useT = () => useReaderHost().t;
62
+ /** `track`, safe to call when the site counts nothing. */
63
+ export function useTrack() {
64
+ const { track } = useReaderHost();
65
+ return (event, data) => track?.(event, data);
66
+ }
@@ -0,0 +1,3 @@
1
+ export { BookReader } from "./ReadApp";
2
+ export { READER_EN, englishWords, type BoardPanelProps, type Picked, type ReaderHost, type ReaderKey } from "./host";
3
+ export { handOver, type Book, type Diagram } from "./store";
@@ -0,0 +1,3 @@
1
+ export { BookReader } from "./ReadApp";
2
+ export { READER_EN, englishWords } from "./host";
3
+ export { handOver } from "./store";
@@ -0,0 +1,46 @@
1
+ /**
2
+ * pdf.js, loaded only when a book is opened (it is 1 MB): a document from a file, and a page drawn to a canvas at
3
+ * a width in pixels. Everything happens in the browser; no part of a book leaves the device.
4
+ */
5
+ import type { PDFDocumentProxy, RenderTask } from "pdfjs-dist";
6
+ export type Doc = PDFDocumentProxy;
7
+ export declare function configurePdf(next: {
8
+ workerSrc: string;
9
+ assets: string;
10
+ }): void;
11
+ export declare function openPdf(file: Blob): Promise<Doc>;
12
+ /** A page's height over its width. */
13
+ export declare function ratioOf(doc: Doc, n: number): Promise<number>;
14
+ /** Draw page `n` on `canvas`, `width` pixels wide. The returned task can be cancelled when the page scrolls away. */
15
+ export declare function drawPage(doc: Doc, n: number, width: number, canvas: HTMLCanvasElement): Promise<RenderTask>;
16
+ /** The book's own list of chapters, each with the page it opens on. Empty when the PDF has none. */
17
+ export declare function chaptersOf(doc: Doc): Promise<{
18
+ title: string;
19
+ page: number;
20
+ depth: number;
21
+ }[]>;
22
+ /**
23
+ * Who is to move in a diagram, when the book says so in the words beside it ("Black to play"): the nearest such
24
+ * words under the board, or over it. Null when the page has no text (a scan) or says nothing.
25
+ * `box` is the diagram in fractions of the page.
26
+ */
27
+ export declare function turnNear(doc: Doc, n: number, box: {
28
+ x0: number;
29
+ y0: number;
30
+ x1: number;
31
+ y1: number;
32
+ }): Promise<"w" | "b" | null>;
33
+ /** The book's first page as a small picture, for its card in the library. */
34
+ export declare function coverOf(doc: Doc): Promise<string | undefined>;
35
+ /**
36
+ * Which side a diagram is printed from, when the page carries the board's coordinates as text: "black" when the
37
+ * rank numbers beside it run 1 to 8 downwards or the file letters under it run h to a, "white" the other way,
38
+ * null when the page says nothing (the coordinates are part of a picture, or there are none).
39
+ * `box` is the diagram in fractions of the page.
40
+ */
41
+ export declare function sideBelow(doc: Doc, n: number, box: {
42
+ x0: number;
43
+ y0: number;
44
+ x1: number;
45
+ y1: number;
46
+ }): Promise<"white" | "black" | null>;
@@ -0,0 +1,130 @@
1
+ let lib = null;
2
+ function pdfjs() {
3
+ lib ??= import("pdfjs-dist").then((m) => {
4
+ m.GlobalWorkerOptions.workerSrc = config.workerSrc;
5
+ return m;
6
+ });
7
+ return lib;
8
+ }
9
+ /** Where pdf.js's worker and the files it fetches as a book needs them are (the site says: ReaderHost.pdf). */
10
+ let config = { workerSrc: "", assets: "/pdfjs/" };
11
+ export function configurePdf(next) {
12
+ config = { ...next, assets: next.assets.endsWith("/") ? next.assets : `${next.assets}/` };
13
+ }
14
+ const fetched = () => ({ wasmUrl: `${config.assets}wasm/`, cMapUrl: `${config.assets}cmaps/`, cMapPacked: true, standardFontDataUrl: `${config.assets}standard_fonts/`, iccUrl: `${config.assets}iccs/` });
15
+ export async function openPdf(file) {
16
+ const { getDocument } = await pdfjs();
17
+ return getDocument({ data: await file.arrayBuffer(), ...fetched() }).promise;
18
+ }
19
+ /** A page's height over its width. */
20
+ export async function ratioOf(doc, n) {
21
+ const v = (await doc.getPage(n)).getViewport({ scale: 1 });
22
+ return v.height / v.width;
23
+ }
24
+ /** Draw page `n` on `canvas`, `width` pixels wide. The returned task can be cancelled when the page scrolls away. */
25
+ export async function drawPage(doc, n, width, canvas) {
26
+ const page = await doc.getPage(n);
27
+ const base = page.getViewport({ scale: 1 });
28
+ const viewport = page.getViewport({ scale: width / base.width });
29
+ canvas.width = Math.round(viewport.width);
30
+ canvas.height = Math.round(viewport.height);
31
+ return page.render({ canvas, viewport });
32
+ }
33
+ /** The book's own list of chapters, each with the page it opens on. Empty when the PDF has none. */
34
+ export async function chaptersOf(doc) {
35
+ const out = [];
36
+ const walk = async (items, depth) => {
37
+ for (const item of items) {
38
+ try {
39
+ const dest = typeof item.dest === "string" ? await doc.getDestination(item.dest) : item.dest;
40
+ const ref = Array.isArray(dest) ? dest[0] : null;
41
+ if (ref && typeof ref === "object")
42
+ out.push({ title: item.title.trim(), page: (await doc.getPageIndex(ref)) + 1, depth });
43
+ }
44
+ catch { /* a chapter that points nowhere is left out */ }
45
+ if (item.items?.length && depth < 1)
46
+ await walk(item.items, depth + 1);
47
+ }
48
+ };
49
+ const outline = (await doc.getOutline());
50
+ if (outline)
51
+ await walk(outline, 0);
52
+ return out;
53
+ }
54
+ /** "Black to play" as a caption ends its line: "forcing Black to play 6…Kd8" in the author's prose is not one. */
55
+ const caption = (words) => new RegExp(`(${words})[\\s.!:]*$`);
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
+ 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
+ /**
59
+ * Who is to move in a diagram, when the book says so in the words beside it ("Black to play"): the nearest such
60
+ * words under the board, or over it. Null when the page has no text (a scan) or says nothing.
61
+ * `box` is the diagram in fractions of the page.
62
+ */
63
+ export async function turnNear(doc, n, box) {
64
+ const page = await doc.getPage(n);
65
+ const view = page.getViewport({ scale: 1 });
66
+ const side = box.x1 - box.x0, height = box.y1 - box.y0;
67
+ 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;
73
+ if (fx < box.x0 - side * 0.6 || fx > box.x1 + side * 0.2)
74
+ continue;
75
+ const gap = fy > box.y1 ? fy - box.y1 : fy < box.y0 ? (box.y0 - fy) * 1.5 : null;
76
+ if (gap !== null && gap < height * 0.7)
77
+ near.push({ gap, text: item.str });
78
+ }
79
+ near.sort((a, b) => a.gap - b.gap);
80
+ for (const { text } of near) {
81
+ const line = text.toLowerCase().normalize("NFC").trim();
82
+ if (BLACK_MOVES.test(line))
83
+ return "b";
84
+ if (WHITE_MOVES.test(line))
85
+ return "w";
86
+ }
87
+ return null;
88
+ }
89
+ /** The book's first page as a small picture, for its card in the library. */
90
+ export async function coverOf(doc) {
91
+ try {
92
+ const canvas = document.createElement("canvas");
93
+ await (await drawPage(doc, 1, 192, canvas)).promise;
94
+ return canvas.toDataURL("image/jpeg", 0.72);
95
+ }
96
+ catch {
97
+ return undefined;
98
+ }
99
+ }
100
+ /**
101
+ * Which side a diagram is printed from, when the page carries the board's coordinates as text: "black" when the
102
+ * rank numbers beside it run 1 to 8 downwards or the file letters under it run h to a, "white" the other way,
103
+ * null when the page says nothing (the coordinates are part of a picture, or there are none).
104
+ * `box` is the diagram in fractions of the page.
105
+ */
106
+ export async function sideBelow(doc, n, box) {
107
+ const page = await doc.getPage(n);
108
+ const view = page.getViewport({ scale: 1 });
109
+ const side = box.x1 - box.x0, height = box.y1 - box.y0;
110
+ 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();
115
+ if (!/^[a-h1-8]$/.test(mark))
116
+ continue;
117
+ const [x, y] = view.convertToViewportPoint(item.transform[4], item.transform[5]);
118
+ const fx = x / view.width, fy = y / view.height;
119
+ 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
+ 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
+ if (/[1-8]/.test(mark) ? beside : under)
122
+ at.set(mark, { fx, fy });
123
+ }
124
+ const one = at.get("1"), eight = at.get("8"), a = at.get("a"), h = at.get("h");
125
+ if (one && eight && Math.abs(one.fy - eight.fy) > height * 0.5)
126
+ return one.fy > eight.fy ? "white" : "black";
127
+ if (a && h && Math.abs(a.fx - h.fx) > side * 0.5)
128
+ return a.fx < h.fx ? "white" : "black";
129
+ return null;
130
+ }