@cogniplay/logic-games-sheet 0.0.0-stage → 0.1.1

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/src/limits.ts ADDED
@@ -0,0 +1,131 @@
1
+ import {
2
+ type FairSharesInstance,
3
+ type GameData,
4
+ clueBands,
5
+ gridGapCells,
6
+ isFairShares,
7
+ isLineCounts,
8
+ isPlaced,
9
+ } from "@cogniplay/logic-games";
10
+
11
+ /**
12
+ * The largest footprint a sheet holds, in millimetres, each way up: the printable
13
+ * area A4 and Letter share (210 × 279 mm) less 10 mm margins and a 40 mm band
14
+ * of text under the board. The content repository's validator and the
15
+ * backend's import assume the same numbers.
16
+ */
17
+ export const boardLimitsMm = {
18
+ upright: { width: 190, height: 219 },
19
+ sideways: { width: 259, height: 150 },
20
+ } as const;
21
+
22
+ export interface SizeMm {
23
+ width: number;
24
+ height: number;
25
+ }
26
+
27
+ const defaultCellSizeMm = 16;
28
+
29
+ /**
30
+ * A board's size in millimetres: its cells' bounding box at the cell size.
31
+ * For Fair Shares that is one grid.
32
+ */
33
+ export function boardSizeMm(
34
+ instance: GameData,
35
+ cellSizeMm: number = defaultCellSizeMm
36
+ ): SizeMm {
37
+ const xs = instance.board.map(([x]) => x);
38
+ const ys = instance.board.map(([, y]) => y);
39
+ return {
40
+ width: (Math.max(...xs) - Math.min(...xs) + 1) * cellSizeMm,
41
+ height: (Math.max(...ys) - Math.min(...ys) + 1) * cellSizeMm,
42
+ };
43
+ }
44
+
45
+ /**
46
+ * The cells the pieces to place, or to share, take under or above the board,
47
+ * at half scale: half a cell of gap and a piece up to three cells tall.
48
+ */
49
+ export const trayBandCells = 2;
50
+
51
+ /** What a Fair Shares board takes with its grids in rows of `across`. */
52
+ function gridsFootprintMm(
53
+ instance: FairSharesInstance,
54
+ across: number,
55
+ cellSizeMm: number
56
+ ): SizeMm {
57
+ const grid = boardSizeMm(instance, cellSizeMm);
58
+ const down = Math.ceil(instance.shares / across);
59
+ const gap = gridGapCells * cellSizeMm;
60
+ const toShare = instance.pieces.some((piece) => !isPlaced(piece));
61
+ return {
62
+ width: across * grid.width + (across - 1) * gap,
63
+ height:
64
+ down * grid.height +
65
+ (down - 1) * gap +
66
+ (toShare ? trayBandCells * cellSizeMm : 0),
67
+ };
68
+ }
69
+
70
+ /**
71
+ * How many of a Fair Shares board's grids lie side by side on its sheet: the
72
+ * most that fit an upright sheet, or failing that the most that fit one
73
+ * sideways. When no number fits either way, the renderer's own choice, so
74
+ * that the footprint reported is the drawing's.
75
+ */
76
+ export function gridsAcross(
77
+ instance: FairSharesInstance,
78
+ cellSizeMm: number = defaultCellSizeMm
79
+ ): number {
80
+ for (const limit of [boardLimitsMm.upright, boardLimitsMm.sideways]) {
81
+ for (let across = instance.shares; across >= 1; across--) {
82
+ const size = gridsFootprintMm(instance, across, cellSizeMm);
83
+ if (size.width <= limit.width && size.height <= limit.height) {
84
+ return across;
85
+ }
86
+ }
87
+ }
88
+ return Math.ceil(Math.sqrt(instance.shares));
89
+ }
90
+
91
+ /**
92
+ * What a board takes on a sheet, in millimetres. For Amoeba that is the
93
+ * board. For Line Counts: its cells, a cell more across when any row has a
94
+ * clue, a cell more down when any column has one, and two cells more down
95
+ * when any piece is to place. For Fair Shares: its grids in rows of
96
+ * `gridsAcross`, a cell between two grids across and down, and two cells
97
+ * more down when any piece is to share. The content repository's validator
98
+ * and the backend's import compute the same from the data.
99
+ */
100
+ export function footprintMm(
101
+ instance: GameData,
102
+ cellSizeMm: number = defaultCellSizeMm
103
+ ): SizeMm {
104
+ if (isFairShares(instance)) {
105
+ return gridsFootprintMm(
106
+ instance,
107
+ gridsAcross(instance, cellSizeMm),
108
+ cellSizeMm
109
+ );
110
+ }
111
+ const board = boardSizeMm(instance, cellSizeMm);
112
+ if (!isLineCounts(instance)) return board;
113
+ const bands = clueBands(instance.clues ?? []);
114
+ const toPlace = instance.pieces.some((piece) => !isPlaced(piece));
115
+ return {
116
+ width: board.width + bands.left * cellSizeMm,
117
+ height:
118
+ board.height + (bands.top + (toPlace ? trayBandCells : 0)) * cellSizeMm,
119
+ };
120
+ }
121
+
122
+ /** Which way the sheet turns for a footprint, or undefined if it fits neither way. */
123
+ export function sheetOrientation(
124
+ size: SizeMm
125
+ ): "portrait" | "landscape" | undefined {
126
+ const fits = (limit: SizeMm) =>
127
+ size.width <= limit.width && size.height <= limit.height;
128
+ if (fits(boardLimitsMm.upright)) return "portrait";
129
+ if (fits(boardLimitsMm.sideways)) return "landscape";
130
+ return undefined;
131
+ }
@@ -0,0 +1,15 @@
1
+ // pdfmake 0.3's in-memory file system, which both its Node and its browser
2
+ // build expose and @types/pdfmake doesn't declare. The font is written into
3
+ // it by name, which is how pdfmake takes a font the same way in both.
4
+ //
5
+ // A module rather than a .d.ts, and imported by pdfmake.ts, so that the
6
+ // augmentation reaches every project that compiles this source, an app's
7
+ // included, and ships in dist.
8
+ declare module "pdfmake" {
9
+ export const virtualfs: {
10
+ existsSync(name: string): boolean;
11
+ writeFileSync(name: string, content: Uint8Array | string): void;
12
+ };
13
+ }
14
+
15
+ export {};
package/src/pdfmake.ts ADDED
@@ -0,0 +1,37 @@
1
+ import pdfmake from "pdfmake";
2
+
3
+ import { robotoRegularBase64 } from "./font/generated/roboto-regular.js";
4
+ import "./pdfmake-augment.js";
5
+
6
+ /** The family name the sheet's text is set in. */
7
+ export const fontName = "Roboto";
8
+
9
+ const fontFile = "Roboto-Regular.ttf";
10
+
11
+ let configured = false;
12
+
13
+ function decodeBase64(text: string): Uint8Array {
14
+ const binary = atob(text);
15
+ const bytes = new Uint8Array(binary.length);
16
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
17
+ return bytes;
18
+ }
19
+
20
+ /**
21
+ * pdfmake with the font registered and its access policies set to deny,
22
+ * configured on the first call. A font source has to be a name in pdfmake's
23
+ * virtual file system; the policies are set because the sheet needs neither
24
+ * URLs nor local files, and pdfmake warns when they are left unset.
25
+ */
26
+ export function configuredPdfmake(): typeof pdfmake {
27
+ if (configured) return pdfmake;
28
+ pdfmake.virtualfs.writeFileSync(fontFile, decodeBase64(robotoRegularBase64));
29
+ pdfmake.addFonts({ [fontName]: { normal: fontFile } });
30
+ pdfmake.setUrlAccessPolicy(() => false);
31
+ // The browser build has no local file access and no such setter.
32
+ if (typeof pdfmake.setLocalAccessPolicy === "function") {
33
+ pdfmake.setLocalAccessPolicy(() => false);
34
+ }
35
+ configured = true;
36
+ return pdfmake;
37
+ }
package/src/sheet.ts ADDED
@@ -0,0 +1,449 @@
1
+ import {
2
+ isFairShares,
3
+ isLineCounts,
4
+ renderBoard,
5
+ } from "@cogniplay/logic-games";
6
+
7
+ import type { ContentSection, TDocumentDefinitions } from "pdfmake/interfaces";
8
+
9
+ import {
10
+ boardLimitsMm,
11
+ boardSizeMm,
12
+ footprintMm,
13
+ gridsAcross,
14
+ sheetOrientation,
15
+ } from "./limits.js";
16
+ import { configuredPdfmake, fontName } from "./pdfmake.js";
17
+ import type { DocumentOptions, SheetOptions } from "./types.js";
18
+ import { wording } from "./wording.js";
19
+
20
+ /** Points per millimetre: the only place the sheet leaves millimetres. */
21
+ const mm = (n: number): number => (n * 72) / 25.4;
22
+
23
+ const marginMm = 10;
24
+ /**
25
+ * The QR code's side, and how far it sits from the page's bottom-right
26
+ * corner: it stands in the corner, not in the margins. A 67-character link at
27
+ * the lowest error correction is 33 modules, so each is 0.9 mm, and the code
28
+ * is about 110 pixels at 100% on a screen: what a phone reads from a screen
29
+ * as well as from paper. A clean print doesn't need more correction.
30
+ */
31
+ const qrMm = 30;
32
+ const qrEdgeMm = 5;
33
+ /** The code's text is centred on the QR code's middle; 9 pt text is about 3 mm tall. Measured from the page's bottom edge to the text's top. */
34
+ const codeTopFromBottomMm = qrEdgeMm + qrMm / 2 + 1.5;
35
+ /** The band at the bottom, inside the margin, that nothing flows into: down to the code's text, with a little room. */
36
+ const footerMm = codeTopFromBottomMm + 1 - marginMm;
37
+ /** The band at the top, inside the margin, that the header draws in and nothing flows into. */
38
+ const headerMm = 5;
39
+ /** Where the flow starts, from the page's edge: under the margin and the header's band. */
40
+ const contentTop = marginMm + headerMm;
41
+ /** The title's top, from the page's edge: below the 5 mm a printer may not reach; 13 pt text is about 5.4 mm tall with its descenders. */
42
+ const titleTopMm = 6;
43
+ /** The rule under the title, from the page's edge: clear of the title's descenders, and the instruction starts 2.5 mm under it. */
44
+ const ruleTopMm = 12.5;
45
+ const ruleStyle = { lineWidth: 0.3, lineColor: "#c4c4c4" };
46
+ /** The least gap between the instruction and the board. */
47
+ const instructionGapMm = 3;
48
+
49
+ /** The renderer's margin around the cells for the heavy outline, which may lie in the page margin. */
50
+ const outlinePaddingMm = 1;
51
+
52
+ /** What a layout pass reports: the page the board landed on, and where its top is. */
53
+ interface Measured {
54
+ boardPage: number;
55
+ boardTopMm: number;
56
+ }
57
+
58
+ const pageSizes = { A4: "A4", Letter: "LETTER" } as const;
59
+ /** The papers' sizes upright, in millimetres. */
60
+ const paperMm = { A4: [210, 297], Letter: [215.9, 279.4] } as const;
61
+
62
+ /** The known values of a choice, or a message naming them. */
63
+ function known<K extends string, V>(
64
+ table: Record<K, V>,
65
+ value: K,
66
+ what: string
67
+ ): V {
68
+ if (!Object.hasOwn(table, value)) {
69
+ const names = Object.keys(table)
70
+ .map((k) => `"${k}"`)
71
+ .join(" or ");
72
+ throw new Error(`Unknown ${what} "${value}": ${names}`);
73
+ }
74
+ return table[value];
75
+ }
76
+
77
+ /** The renderer writes its drawing's size in millimetres on the root element. */
78
+ function drawingSizeMm(svg: string): { width: number; height: number } {
79
+ const match = svg.match(/width="([\d.]+)mm" height="([\d.]+)mm"/);
80
+ if (match === null) {
81
+ throw new Error("The renderer's drawing has no size in millimetres");
82
+ }
83
+ return { width: Number(match[1]), height: Number(match[2]) };
84
+ }
85
+
86
+ /**
87
+ * The PDFKit document pdfmake builds on. Only what the sheet touches: the
88
+ * catalog's viewer preferences, which pdfmake doesn't expose.
89
+ */
90
+ interface PdfKitInternals {
91
+ _root: { data: { ViewerPreferences?: { data: Record<string, unknown> } } };
92
+ ref(data: Record<string, unknown>): { data: Record<string, unknown> };
93
+ }
94
+
95
+ /**
96
+ * A sheet worked out up to the layout: what it prints, and the page it
97
+ * prints on. Everything that can be told without laying the page out has
98
+ * been checked by now.
99
+ */
100
+ interface Prepared {
101
+ code: string;
102
+ instruction: string;
103
+ title: string | undefined;
104
+ link: string | undefined;
105
+ /** The label before the code, in the sheet's language. */
106
+ label: string;
107
+ svg: string;
108
+ drawing: { width: number; height: number };
109
+ pageSize: (typeof pageSizes)[keyof typeof pageSizes];
110
+ orientation: "portrait" | "landscape";
111
+ pageWidth: number;
112
+ /** The QR code's top, from the page's top: the board is centred above it. */
113
+ areaBottom: number;
114
+ }
115
+
116
+ function prepare(options: SheetOptions): Prepared {
117
+ const {
118
+ instance,
119
+ code,
120
+ instruction,
121
+ language,
122
+ paper,
123
+ cellSizeMm,
124
+ marks,
125
+ pieceColours,
126
+ colour = "colour",
127
+ link,
128
+ title,
129
+ } = options;
130
+ const pageSize = known(pageSizes, paper, "paper");
131
+ if (colour !== "colour" && colour !== "greyscale") {
132
+ throw new Error(`Unknown colour "${String(colour)}": colour or greyscale`);
133
+ }
134
+ const { label } = known(wording, language, "language");
135
+
136
+ const size = boardSizeMm(instance, cellSizeMm);
137
+ // What the board takes with its clues and its pieces to place; for Amoeba,
138
+ // the board itself.
139
+ const footprint = footprintMm(instance, cellSizeMm);
140
+ const orientation = sheetOrientation(footprint);
141
+ if (orientation === undefined) {
142
+ const { upright, sideways } = boardLimitsMm;
143
+ const taken =
144
+ footprint.width === size.width && footprint.height === size.height
145
+ ? ""
146
+ : `, ${footprint.width}×${footprint.height} mm with its clues and pieces,`;
147
+ const what = isFairShares(instance)
148
+ ? `${instance.shares} grids of ${size.width}×${size.height} mm, ` +
149
+ `${footprint.width}×${footprint.height} mm with the pieces to share, fit`
150
+ : `A ${size.width}×${size.height} mm board${taken} fits`;
151
+ throw new Error(
152
+ `${what} no sheet: at most ` +
153
+ `${upright.width}×${upright.height} mm upright or ` +
154
+ `${sideways.width}×${sideways.height} mm sideways`
155
+ );
156
+ }
157
+
158
+ const limit =
159
+ orientation === "portrait" ? boardLimitsMm.upright : boardLimitsMm.sideways;
160
+
161
+ // The pieces on the board are ghosts: the child places the real ones over
162
+ // them. A Line Counts board's pieces to place are drawn under it at half
163
+ // scale, in one row as wide as the sheet allows: they say which pieces to
164
+ // take, and the child matches them by shape. A Fair Shares board's pieces
165
+ // to share are drawn the same way above its grids, which lie as many
166
+ // across as the footprint counted.
167
+ const svg = renderBoard(instance, {
168
+ cellSizeMm,
169
+ marks,
170
+ pieceStyle: "ghost",
171
+ pieceColours: colour === "colour" ? pieceColours : undefined,
172
+ trayScale: 0.5,
173
+ trayWidthMm: limit.width,
174
+ ...(isFairShares(instance)
175
+ ? { gridsPerRow: gridsAcross(instance, cellSizeMm) }
176
+ : {}),
177
+ });
178
+ const drawing = drawingSizeMm(svg);
179
+
180
+ // The limits count cells, but a piece or a mark off the board, or pieces to
181
+ // place that need a second row, make the drawing larger than the count; it
182
+ // must still fit the way up the footprint chose.
183
+ if (
184
+ drawing.width - 2 * outlinePaddingMm > limit.width ||
185
+ drawing.height - 2 * outlinePaddingMm > limit.height
186
+ ) {
187
+ throw new Error(
188
+ (isFairShares(instance)
189
+ ? `The pieces to share don't fit beside the ${instance.shares} grids of ` +
190
+ `${size.width}×${size.height} mm: `
191
+ : (isLineCounts(instance)
192
+ ? "The clues and the pieces to place don't fit beside"
193
+ : "A piece or a mark lies off") +
194
+ ` the ${size.width}×${size.height} mm board: `) +
195
+ `the drawing is ${drawing.width}×${drawing.height} mm, which fits no sheet ` +
196
+ (orientation === "portrait" ? "upright" : "sideways")
197
+ );
198
+ }
199
+
200
+ const [upright, long] = paperMm[paper];
201
+ const [pageWidth, pageHeight] =
202
+ orientation === "portrait" ? [upright, long] : [long, upright];
203
+ return {
204
+ code,
205
+ instruction,
206
+ title,
207
+ link,
208
+ label,
209
+ svg,
210
+ drawing,
211
+ pageSize,
212
+ orientation,
213
+ pageWidth,
214
+ // The instruction sits under the title; the board is centred in what the
215
+ // instruction and the QR code leave between them.
216
+ areaBottom: pageHeight - qrEdgeMm - qrMm,
217
+ };
218
+ }
219
+
220
+ /**
221
+ * One sheet's page, as a pdfmake section: a section starts a page of its own,
222
+ * with its own size, orientation, header and footer, so a sheet is the same
223
+ * whether it prints alone or among others. The header is the variant's
224
+ * title; the footer is the teacher's strip: the code, and the QR code to the
225
+ * instance's page in the corner. The board is pushed down by the offset.
226
+ */
227
+ function section(sheet: Prepared, offsetMm: number): ContentSection {
228
+ const { code, instruction, title, link, label, svg, drawing, pageWidth } =
229
+ sheet;
230
+ return {
231
+ section: [
232
+ { text: instruction },
233
+ {
234
+ svg,
235
+ width: mm(drawing.width),
236
+ height: mm(drawing.height),
237
+ alignment: "center",
238
+ margin: [0, mm(instructionGapMm + offsetMm), 0, 0],
239
+ },
240
+ ...(link === undefined
241
+ ? []
242
+ : [
243
+ {
244
+ qr: link,
245
+ fit: mm(qrMm),
246
+ eccLevel: "L" as const,
247
+ absolutePosition: {
248
+ x: mm(pageWidth - qrEdgeMm - qrMm),
249
+ y: mm(sheet.areaBottom),
250
+ },
251
+ },
252
+ ]),
253
+ ],
254
+ pageSize: sheet.pageSize,
255
+ pageOrientation: sheet.orientation,
256
+ // The header's box is the top margin and the band; the rule is placed
257
+ // within it from the page's edge, the title flows from its margin.
258
+ ...(title === undefined
259
+ ? {}
260
+ : {
261
+ header: {
262
+ stack: [
263
+ {
264
+ text: title,
265
+ fontSize: 13,
266
+ alignment: "center",
267
+ margin: [mm(marginMm), mm(titleTopMm), mm(marginMm), 0],
268
+ },
269
+ {
270
+ canvas: [
271
+ {
272
+ type: "line",
273
+ x1: mm(marginMm),
274
+ y1: 0,
275
+ x2: mm(pageWidth - marginMm),
276
+ y2: 0,
277
+ lineWidth: mm(ruleStyle.lineWidth),
278
+ lineColor: ruleStyle.lineColor,
279
+ },
280
+ ],
281
+ absolutePosition: { x: 0, y: mm(ruleTopMm) },
282
+ },
283
+ ],
284
+ },
285
+ }),
286
+ footer: {
287
+ text: `${label} ${code}`,
288
+ fontSize: 9,
289
+ color: "#555",
290
+ // The footer's box is the bottom margin, marginMm + footerMm from the page's edge.
291
+ margin: [
292
+ mm(marginMm),
293
+ mm(marginMm + footerMm - codeTopFromBottomMm),
294
+ mm(marginMm),
295
+ 0,
296
+ ],
297
+ },
298
+ };
299
+ }
300
+
301
+ /**
302
+ * The document for the sheets, each board pushed down by its offset, with
303
+ * where each board landed reported to `measured` as the layout goes, in the
304
+ * sheets' order.
305
+ */
306
+ function definition(
307
+ sheets: readonly Prepared[],
308
+ offsetsMm: readonly number[],
309
+ title: string | undefined,
310
+ measured: Measured[]
311
+ ): TDocumentDefinitions {
312
+ const [first] = sheets;
313
+ if (first === undefined) throw new Error("No sheets to lay out");
314
+ return {
315
+ // The file's name when a viewer saves it: browsers take it from the
316
+ // document's title, and the sheet opens from a blob address whose name
317
+ // is a random id.
318
+ ...(title === undefined ? {} : { info: { title } }),
319
+ pageSize: first.pageSize,
320
+ pageOrientation: first.orientation,
321
+ pageMargins: [
322
+ mm(marginMm),
323
+ mm(contentTop),
324
+ mm(marginMm),
325
+ mm(marginMm + footerMm),
326
+ ],
327
+ defaultStyle: { font: fontName, fontSize: 11 },
328
+ content: sheets.map((sheet, index) =>
329
+ section(sheet, offsetsMm[index] ?? 0)
330
+ ),
331
+ // pdfmake reports every node here with its properties, once each and in
332
+ // the document's order, so the boards are the nodes with an svg.
333
+ pageBreakBefore: (node) => {
334
+ if (node.svg !== undefined) {
335
+ measured.push({
336
+ boardPage: node.startPosition.pageNumber,
337
+ boardTopMm: node.startPosition.top / mm(1),
338
+ });
339
+ }
340
+ return false;
341
+ },
342
+ };
343
+ }
344
+
345
+ /**
346
+ * A sheet among several that can't print, which fails the whole PDF: its
347
+ * code, in front of the reason and on its own for a caller to name the
348
+ * board, and the sheet's own error as the cause.
349
+ */
350
+ export class SheetError extends Error {
351
+ /** The failing sheet's code, such as AMO-03-0005. */
352
+ readonly code: string;
353
+
354
+ constructor(code: string, cause: Error) {
355
+ super(`${code}: ${cause.message}`, { cause });
356
+ this.name = "SheetError";
357
+ this.code = code;
358
+ }
359
+ }
360
+
361
+ /**
362
+ * The sheets in one PDF, a page each. A sheet that can't print fails the
363
+ * whole; with `named`, its error becomes a `SheetError` naming it, since
364
+ * among many the caller can't tell which it was.
365
+ */
366
+ async function render(
367
+ sheets: readonly SheetOptions[],
368
+ title: string | undefined,
369
+ named: boolean
370
+ ): Promise<Uint8Array> {
371
+ const checked = <T>(code: string, check: () => T): T => {
372
+ try {
373
+ return check();
374
+ } catch (error) {
375
+ if (!named || !(error instanceof Error)) throw error;
376
+ throw new SheetError(code, error);
377
+ }
378
+ };
379
+
380
+ const prepared = sheets.map((sheet) =>
381
+ checked(sheet.code, () => prepare(sheet))
382
+ );
383
+
384
+ // pdfmake lays out top-down, so the sheets are laid out twice: once to
385
+ // measure where each board lands under its instruction, and once with each
386
+ // board pushed down by half the room left on its page.
387
+ const measured: Measured[] = [];
388
+ await configuredPdfmake()
389
+ .createPdf(
390
+ definition(
391
+ prepared,
392
+ prepared.map(() => 0),
393
+ title,
394
+ measured
395
+ )
396
+ )
397
+ .getStream();
398
+ const offsetsMm = prepared.map((sheet, index) =>
399
+ checked(sheet.code, () => {
400
+ const board = measured[index];
401
+ const room =
402
+ board === undefined
403
+ ? -1
404
+ : sheet.areaBottom - board.boardTopMm - sheet.drawing.height;
405
+ // Sheet n is page n, unless its instruction pushed its board onto the
406
+ // next one.
407
+ if (board?.boardPage !== index + 1 || room < 0) {
408
+ throw new Error(
409
+ `The instruction (${sheet.instruction.length} characters) is too long for a board this tall`
410
+ );
411
+ }
412
+ return room / 2;
413
+ })
414
+ );
415
+
416
+ const created = configuredPdfmake().createPdf(
417
+ definition(prepared, offsetsMm, title, [])
418
+ );
419
+ const doc = (await created.getStream()) as unknown as PdfKitInternals;
420
+
421
+ // Ask viewers not to scale the page. PDFKit 0.20 ends the ViewerPreferences
422
+ // reference itself in end(), so it must not be ended here.
423
+ const root = doc._root.data;
424
+ root.ViewerPreferences ??= doc.ref({});
425
+ root.ViewerPreferences.data.PrintScaling = "None";
426
+
427
+ return await created.getBuffer();
428
+ }
429
+
430
+ /** One instance's sheet as a one-page PDF. */
431
+ export async function renderSheet(options: SheetOptions): Promise<Uint8Array> {
432
+ return await render([options], options.code, false);
433
+ }
434
+
435
+ /**
436
+ * Several instances' sheets in one PDF, in the order given: each on a page
437
+ * of its own, exactly as it prints alone, turned its own way. A sheet that
438
+ * can't print fails the whole with a `SheetError` naming it; an empty list
439
+ * is an error rather than an empty PDF.
440
+ */
441
+ export async function renderSheets(
442
+ sheets: readonly SheetOptions[],
443
+ { title }: DocumentOptions = {}
444
+ ): Promise<Uint8Array> {
445
+ if (sheets.length === 0) {
446
+ throw new Error("No sheets to render: a document needs at least one");
447
+ }
448
+ return await render(sheets, title, true);
449
+ }
package/src/types.ts ADDED
@@ -0,0 +1,38 @@
1
+ import type { GameData, MarkDrawer } from "@cogniplay/logic-games";
2
+
3
+ export type Paper = "A4" | "Letter";
4
+
5
+ export type SheetLanguage = "hu" | "en";
6
+
7
+ /** Whether the pieces print in the kit's colours or in grey. */
8
+ export type SheetColour = "colour" | "greyscale";
9
+
10
+ export interface SheetOptions {
11
+ /** The instance's data, as the renderer takes it. */
12
+ instance: GameData;
13
+ /** The instance's code, such as AMO-03-0005. */
14
+ code: string;
15
+ /** What the child is told for this instance, in the school's language: one plain line. */
16
+ instruction: string;
17
+ /** The language of the sheet's fixed wording. */
18
+ language: SheetLanguage;
19
+ paper: Paper;
20
+ /** The kit's cell size in millimetres. Default 16. */
21
+ cellSizeMm?: number;
22
+ /** Drawings for mark kinds, passed to the renderer. */
23
+ marks?: Record<string, MarkDrawer>;
24
+ /** The kit's colour per piece id. Without it the pieces are grey. */
25
+ pieceColours?: Record<string, string>;
26
+ /** Default `colour`: the pieces in the kit's colours, when given. */
27
+ colour?: SheetColour;
28
+ /** A link to the instance's page, drawn as a QR code in the footer. None without. */
29
+ link?: string;
30
+ /** The variant's name, in the school's language, as the sheet's header. None without. */
31
+ title?: string;
32
+ }
33
+
34
+ /** What belongs to a document of several sheets rather than to one of them. */
35
+ export interface DocumentOptions {
36
+ /** The document's title, which a viewer names a saved file by. None without. */
37
+ title?: string;
38
+ }
package/src/wording.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { SheetLanguage } from "./types.js";
2
+
3
+ /**
4
+ * The sheet's fixed wording, per language: the label before the code. Fixed
5
+ * wording stays out of the database (backend decision 6), so it lives here.
6
+ */
7
+ export const wording: Record<SheetLanguage, { label: string }> = {
8
+ hu: { label: "Feladat:" },
9
+ en: { label: "Puzzle:" },
10
+ };