@ai-matrx/print 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/CHANGELOG.md +25 -0
- package/dist/barcode.cjs +182 -0
- package/dist/barcode.cjs.map +1 -0
- package/dist/barcode.d.cts +94 -0
- package/dist/barcode.d.ts +94 -0
- package/dist/barcode.js +151 -0
- package/dist/barcode.js.map +1 -0
- package/dist/booklet.cjs +202 -0
- package/dist/booklet.cjs.map +1 -0
- package/dist/booklet.d.cts +90 -0
- package/dist/booklet.d.ts +90 -0
- package/dist/booklet.js +179 -0
- package/dist/booklet.js.map +1 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -0
- package/dist/index.d.ts +3 -0
- package/dist/qr-styled.cjs +219 -0
- package/dist/qr-styled.cjs.map +1 -0
- package/dist/qr-styled.d.cts +150 -0
- package/dist/qr-styled.d.ts +150 -0
- package/dist/qr-styled.js +188 -0
- package/dist/qr-styled.js.map +1 -0
- package/package.json +34 -2
package/dist/booklet.cjs
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/booklet.ts
|
|
21
|
+
var booklet_exports = {};
|
|
22
|
+
__export(booklet_exports, {
|
|
23
|
+
bookletSizeWarning: () => bookletSizeWarning,
|
|
24
|
+
buildBookletDocument: () => buildBookletDocument,
|
|
25
|
+
imposeBooklet: () => imposeBooklet,
|
|
26
|
+
printBooklet: () => printBooklet
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(booklet_exports);
|
|
29
|
+
|
|
30
|
+
// src/core.ts
|
|
31
|
+
function escapeHtml(str) {
|
|
32
|
+
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
33
|
+
}
|
|
34
|
+
function openPrintWindow(htmlDocument, filename = "print") {
|
|
35
|
+
const win = window.open("", "_blank", "width=920,height=720,scrollbars=yes");
|
|
36
|
+
if (!win) {
|
|
37
|
+
const blob = new Blob([htmlDocument], { type: "text/html;charset=utf-8" });
|
|
38
|
+
const url = URL.createObjectURL(blob);
|
|
39
|
+
const a = document.createElement("a");
|
|
40
|
+
a.href = url;
|
|
41
|
+
a.download = `${filename.replace(/\s+/g, "-").toLowerCase()}.html`;
|
|
42
|
+
document.body.appendChild(a);
|
|
43
|
+
a.click();
|
|
44
|
+
document.body.removeChild(a);
|
|
45
|
+
URL.revokeObjectURL(url);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
win.document.open();
|
|
49
|
+
win.document.write(htmlDocument);
|
|
50
|
+
win.document.close();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// src/booklet.ts
|
|
54
|
+
var PAGES_PER_SHEET = 4;
|
|
55
|
+
var SADDLE_STITCH_MAX_PAGES = 48;
|
|
56
|
+
function imposeBooklet(pageCount) {
|
|
57
|
+
if (!Number.isInteger(pageCount) || pageCount < 1) {
|
|
58
|
+
throw new RangeError(
|
|
59
|
+
`imposeBooklet: pageCount must be a positive integer, received ${String(pageCount)}`
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
const padded = Math.ceil(pageCount / PAGES_PER_SHEET) * PAGES_PER_SHEET;
|
|
63
|
+
const slot = (n) => n > pageCount ? 0 : n;
|
|
64
|
+
const sheets = [];
|
|
65
|
+
for (let i = 1; i <= padded / PAGES_PER_SHEET; i += 1) {
|
|
66
|
+
sheets.push({
|
|
67
|
+
front: [slot(padded - 2 * i + 2), slot(2 * i - 1)],
|
|
68
|
+
back: [slot(2 * i), slot(padded - 2 * i + 1)]
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
return { paddedPageCount: padded, sheets, requiresShortEdgeDuplex: true };
|
|
72
|
+
}
|
|
73
|
+
function bookletSizeWarning(pageCount) {
|
|
74
|
+
if (!Number.isInteger(pageCount) || pageCount < 1) return null;
|
|
75
|
+
const padded = Math.ceil(pageCount / PAGES_PER_SHEET) * PAGES_PER_SHEET;
|
|
76
|
+
if (padded <= SADDLE_STITCH_MAX_PAGES) return null;
|
|
77
|
+
return `This booklet is ${padded} pages (${padded / PAGES_PER_SHEET} sheets). Past about ${SADDLE_STITCH_MAX_PAGES} pages a saddle-stitch booklet gets too thick to fold flat and the inner pages creep out at the fore-edge. Consider printing it as a plain workbook instead, or splitting it into ${SADDLE_STITCH_MAX_PAGES}-page signatures.`;
|
|
78
|
+
}
|
|
79
|
+
var BOOKLET_STYLES = `
|
|
80
|
+
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
|
81
|
+
|
|
82
|
+
@page { size: 11in 8.5in; margin: 0; }
|
|
83
|
+
|
|
84
|
+
html, body {
|
|
85
|
+
background: #fff;
|
|
86
|
+
color: #1a1a1a;
|
|
87
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
.bk-side {
|
|
91
|
+
display: flex;
|
|
92
|
+
flex-direction: row;
|
|
93
|
+
width: 11in;
|
|
94
|
+
height: 8.5in;
|
|
95
|
+
page-break-after: always;
|
|
96
|
+
break-after: page;
|
|
97
|
+
overflow: hidden;
|
|
98
|
+
}
|
|
99
|
+
.bk-side:last-of-type { page-break-after: auto; break-after: auto; }
|
|
100
|
+
|
|
101
|
+
.bk-page {
|
|
102
|
+
width: 5.5in;
|
|
103
|
+
height: 8.5in;
|
|
104
|
+
overflow: hidden;
|
|
105
|
+
position: relative;
|
|
106
|
+
}
|
|
107
|
+
.bk-blank { /* intentionally empty \u2014 a padded slot */ }
|
|
108
|
+
|
|
109
|
+
.bk-banner {
|
|
110
|
+
background: #fef3c7;
|
|
111
|
+
border: 2px solid #f59e0b;
|
|
112
|
+
border-radius: 8px;
|
|
113
|
+
padding: 14px 18px;
|
|
114
|
+
margin: 18px;
|
|
115
|
+
font-size: 13px;
|
|
116
|
+
line-height: 1.55;
|
|
117
|
+
color: #78350f;
|
|
118
|
+
max-width: 11in;
|
|
119
|
+
}
|
|
120
|
+
.bk-banner h2 { font-size: 15px; margin-bottom: 6px; }
|
|
121
|
+
.bk-banner ol { margin: 6px 0 6px 20px; }
|
|
122
|
+
.bk-banner strong { font-weight: 700; }
|
|
123
|
+
.bk-banner .bk-size-warning {
|
|
124
|
+
display: block;
|
|
125
|
+
margin-top: 10px;
|
|
126
|
+
padding-top: 10px;
|
|
127
|
+
border-top: 1px solid #f59e0b;
|
|
128
|
+
color: #7f1d1d;
|
|
129
|
+
font-weight: 600;
|
|
130
|
+
}
|
|
131
|
+
.bk-actions { display: flex; gap: 10px; margin: 0 18px 18px; }
|
|
132
|
+
.bk-btn {
|
|
133
|
+
padding: 8px 20px; border-radius: 8px; font-size: 13px; font-family: inherit;
|
|
134
|
+
font-weight: 600; cursor: pointer; border: none;
|
|
135
|
+
}
|
|
136
|
+
.bk-btn-primary { background: #2563eb; color: #fff; }
|
|
137
|
+
.bk-btn-secondary { background: #f3f4f6; color: #374151; border: 1px solid #d1d5db; }
|
|
138
|
+
|
|
139
|
+
@media print {
|
|
140
|
+
.screen-only { display: none !important; }
|
|
141
|
+
.bk-side { page-break-after: always; break-after: page; }
|
|
142
|
+
}
|
|
143
|
+
`;
|
|
144
|
+
function renderBox(page, pagesHtml) {
|
|
145
|
+
const html = page === 0 ? void 0 : pagesHtml[page - 1];
|
|
146
|
+
if (html === void 0) {
|
|
147
|
+
return `<div class="bk-page bk-blank" data-page="0"></div>`;
|
|
148
|
+
}
|
|
149
|
+
return `<div class="bk-page" data-page="${page}">${html}</div>`;
|
|
150
|
+
}
|
|
151
|
+
function renderSide(spread, pagesHtml) {
|
|
152
|
+
return `<section class="bk-side">${renderBox(spread[0], pagesHtml)}${renderBox(spread[1], pagesHtml)}</section>`;
|
|
153
|
+
}
|
|
154
|
+
function renderBanner(imposition, warning) {
|
|
155
|
+
const sheetCount = imposition.sheets.length;
|
|
156
|
+
const warningHtml = warning ? `<span class="bk-size-warning">${escapeHtml(warning)}</span>` : "";
|
|
157
|
+
return `<div class="bk-banner screen-only">
|
|
158
|
+
<h2>Booklet print settings \u2014 set these exactly</h2>
|
|
159
|
+
<ol>
|
|
160
|
+
<li>Orientation: <strong>Landscape</strong></li>
|
|
161
|
+
<li>Two-sided printing: <strong>ON</strong></li>
|
|
162
|
+
<li>Flip on <strong>SHORT edge</strong> (also called "tumble" or "short-edge binding") \u2014 long-edge flip prints every back side upside-down</li>
|
|
163
|
+
<li>Scale: <strong>100%</strong> (never "fit to page")</li>
|
|
164
|
+
<li>Margins: <strong>None</strong></li>
|
|
165
|
+
</ol>
|
|
166
|
+
<p><strong>Print all pages, fold the whole stack in half, staple the spine.</strong>
|
|
167
|
+
${sheetCount} sheet${sheetCount === 1 ? "" : "s"} of paper, ${imposition.paddedPageCount} booklet pages.</p>
|
|
168
|
+
${warningHtml}
|
|
169
|
+
</div>`;
|
|
170
|
+
}
|
|
171
|
+
function buildBookletDocument(pagesHtml, opts) {
|
|
172
|
+
const title = opts?.title ?? "Booklet";
|
|
173
|
+
const pageStyles = opts?.pageStyles ?? "";
|
|
174
|
+
const imposition = imposeBooklet(Math.max(1, pagesHtml.length));
|
|
175
|
+
const warning = bookletSizeWarning(pagesHtml.length);
|
|
176
|
+
const sides = imposition.sheets.map((sheet) => renderSide(sheet.front, pagesHtml) + renderSide(sheet.back, pagesHtml)).join("\n");
|
|
177
|
+
return `<!DOCTYPE html>
|
|
178
|
+
<html lang="en">
|
|
179
|
+
<head>
|
|
180
|
+
<meta charset="UTF-8">
|
|
181
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
182
|
+
<title>${escapeHtml(title)}</title>
|
|
183
|
+
<style>
|
|
184
|
+
${BOOKLET_STYLES}
|
|
185
|
+
${pageStyles}
|
|
186
|
+
</style>
|
|
187
|
+
</head>
|
|
188
|
+
<body>
|
|
189
|
+
${renderBanner(imposition, warning)}
|
|
190
|
+
<div class="bk-actions screen-only">
|
|
191
|
+
<button class="bk-btn bk-btn-primary" onclick="window.print()">Print / Save as PDF</button>
|
|
192
|
+
<button class="bk-btn bk-btn-secondary" onclick="window.close()">Close</button>
|
|
193
|
+
</div>
|
|
194
|
+
${sides}
|
|
195
|
+
</body>
|
|
196
|
+
</html>`;
|
|
197
|
+
}
|
|
198
|
+
function printBooklet(pagesHtml, opts) {
|
|
199
|
+
const title = opts?.title ?? "Booklet";
|
|
200
|
+
openPrintWindow(buildBookletDocument(pagesHtml, opts), title);
|
|
201
|
+
}
|
|
202
|
+
//# sourceMappingURL=booklet.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/booklet.ts","../src/core.ts"],"sourcesContent":["/**\n * @ai-matrx/print/booklet — saddle-stitch booklet imposition.\n *\n * The education white space: no test-prep / worksheet tool offers \"turn this\n * into a fold-and-staple booklet\". This module is the whole capability —\n * the imposition math, the size guidance, and a 2-up landscape print lane\n * composed over ./core.\n *\n * Zero dependencies: pure arithmetic plus string composition. Import-inert —\n * `window` is touched only inside printBooklet, at call time.\n *\n * ── THE MATH ────────────────────────────────────────────────────────────────\n * A saddle-stitch booklet is a stack of sheets folded in half together and\n * stapled through the spine. Every sheet carries FOUR logical pages (two per\n * side), so the page count is padded up to a multiple of 4 with blanks.\n *\n * For sheet i (1-indexed, i = 1..N/4) of an N-page (padded) booklet:\n * front spread = [N − 2i + 2, 2i − 1] (left, right)\n * back spread = [2i, N − 2i + 1] (left, right)\n *\n * Worked anchor, N = 8:\n * sheet 1 → front [8, 1] back [2, 7]\n * sheet 2 → front [6, 3] back [4, 5]\n * Every spread's two page numbers sum to N + 1 — the invariant that makes the\n * fold work, and the cheapest way to check an imposition is right.\n *\n * ── THE DUPLEX TRAP ─────────────────────────────────────────────────────────\n * These spreads are 2-up LANDSCAPE. Ordinary duplex printing flips on the LONG\n * edge, which for a landscape sheet means the back side lands upside-down\n * relative to the front — the booklet folds into gibberish. There are exactly\n * two fixes: instruct the human to select short-edge (tumble) duplex, or\n * pre-rotate every back side 180°. A print-window lane cannot pre-rotate\n * reliably (browsers differ on how `@page`/transform interact with duplex), so\n * THIS lane instructs. `BookletImposition.requiresShortEdgeDuplex` exposes the\n * trap in the type system so a future PDF lane — which owns its own page\n * transforms — can take the pre-rotate branch instead of the instruction.\n */\n\nimport { escapeHtml, openPrintWindow } from \"./core\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/**\n * One physical sheet of paper. Each tuple is [left, right] as the reader sees\n * that side laid flat, in 1-based logical page numbers.\n * `0` means a blank pad page (a slot past the end of the supplied content).\n */\nexport interface BookletSheet {\n front: [number, number];\n back: [number, number];\n}\n\nexport interface BookletImposition {\n /** Supplied page count rounded UP to the next multiple of 4. */\n paddedPageCount: number;\n /** Sheets in print order: sheet 1 outermost, last sheet at the fold. */\n sheets: BookletSheet[];\n /**\n * true when ordinary long-edge duplex would flip the backs — consumer must\n * either instruct short-edge/tumble duplex or pre-rotate backs 180° (PDF\n * lanes). Always true for this 2-up landscape imposition.\n */\n requiresShortEdgeDuplex: true;\n}\n\nexport interface BookletPrintOptions {\n title?: string;\n /** CSS injected after the layout styles — style the caller's page content. */\n pageStyles?: string;\n}\n\n// ─── Imposition ──────────────────────────────────────────────────────────────\n\n/** Sheets carry four logical pages each; everything pads to this. */\nconst PAGES_PER_SHEET = 4;\n\n/**\n * Past roughly this many letter pages, a saddle-stitch booklet gets too thick\n * to fold cleanly and the creep (inner pages pushing out at the fore-edge)\n * becomes visible. Callers should offer \"print as a workbook instead\".\n */\nconst SADDLE_STITCH_MAX_PAGES = 48;\n\n/**\n * Impose `pageCount` logical pages onto saddle-stitch sheets.\n *\n * Padding is appended at the END of the logical page run, so pad slots always\n * carry the HIGHEST page numbers — which is why they surface as `0` in the\n * spreads nearest the front cover (N=1 → sheet 1 front [0, 1], back [0, 0]).\n *\n * @throws RangeError when pageCount is not a positive integer.\n */\nexport function imposeBooklet(pageCount: number): BookletImposition {\n if (!Number.isInteger(pageCount) || pageCount < 1) {\n throw new RangeError(\n `imposeBooklet: pageCount must be a positive integer, received ${String(pageCount)}`,\n );\n }\n\n const padded = Math.ceil(pageCount / PAGES_PER_SHEET) * PAGES_PER_SHEET;\n // A slot past the supplied content is a blank pad page, reported as 0.\n const slot = (n: number): number => (n > pageCount ? 0 : n);\n\n const sheets: BookletSheet[] = [];\n for (let i = 1; i <= padded / PAGES_PER_SHEET; i += 1) {\n sheets.push({\n front: [slot(padded - 2 * i + 2), slot(2 * i - 1)],\n back: [slot(2 * i), slot(padded - 2 * i + 1)],\n });\n }\n\n return { paddedPageCount: padded, sheets, requiresShortEdgeDuplex: true };\n}\n\n/**\n * Human warning when a booklet is too fat to saddle-stitch well, else null.\n * Measured on the PADDED count — that is what actually goes through the folder.\n */\nexport function bookletSizeWarning(pageCount: number): string | null {\n if (!Number.isInteger(pageCount) || pageCount < 1) return null;\n const padded = Math.ceil(pageCount / PAGES_PER_SHEET) * PAGES_PER_SHEET;\n if (padded <= SADDLE_STITCH_MAX_PAGES) return null;\n return (\n `This booklet is ${padded} pages (${padded / PAGES_PER_SHEET} sheets). ` +\n `Past about ${SADDLE_STITCH_MAX_PAGES} pages a saddle-stitch booklet gets too thick to fold flat ` +\n `and the inner pages creep out at the fore-edge. Consider printing it as a plain workbook instead, ` +\n `or splitting it into ${SADDLE_STITCH_MAX_PAGES}-page signatures.`\n );\n}\n\n// ─── Print lane ──────────────────────────────────────────────────────────────\n\nconst BOOKLET_STYLES = `\n *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }\n\n @page { size: 11in 8.5in; margin: 0; }\n\n html, body {\n background: #fff;\n color: #1a1a1a;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif;\n }\n\n .bk-side {\n display: flex;\n flex-direction: row;\n width: 11in;\n height: 8.5in;\n page-break-after: always;\n break-after: page;\n overflow: hidden;\n }\n .bk-side:last-of-type { page-break-after: auto; break-after: auto; }\n\n .bk-page {\n width: 5.5in;\n height: 8.5in;\n overflow: hidden;\n position: relative;\n }\n .bk-blank { /* intentionally empty — a padded slot */ }\n\n .bk-banner {\n background: #fef3c7;\n border: 2px solid #f59e0b;\n border-radius: 8px;\n padding: 14px 18px;\n margin: 18px;\n font-size: 13px;\n line-height: 1.55;\n color: #78350f;\n max-width: 11in;\n }\n .bk-banner h2 { font-size: 15px; margin-bottom: 6px; }\n .bk-banner ol { margin: 6px 0 6px 20px; }\n .bk-banner strong { font-weight: 700; }\n .bk-banner .bk-size-warning {\n display: block;\n margin-top: 10px;\n padding-top: 10px;\n border-top: 1px solid #f59e0b;\n color: #7f1d1d;\n font-weight: 600;\n }\n .bk-actions { display: flex; gap: 10px; margin: 0 18px 18px; }\n .bk-btn {\n padding: 8px 20px; border-radius: 8px; font-size: 13px; font-family: inherit;\n font-weight: 600; cursor: pointer; border: none;\n }\n .bk-btn-primary { background: #2563eb; color: #fff; }\n .bk-btn-secondary { background: #f3f4f6; color: #374151; border: 1px solid #d1d5db; }\n\n @media print {\n .screen-only { display: none !important; }\n .bk-side { page-break-after: always; break-after: page; }\n }\n`;\n\nfunction renderBox(page: number, pagesHtml: readonly string[]): string {\n // Content fragments are TRUSTED HTML supplied by the caller — they are\n // already-rendered pages, so they are injected verbatim and NOT escaped.\n const html = page === 0 ? undefined : pagesHtml[page - 1];\n if (html === undefined) {\n return `<div class=\"bk-page bk-blank\" data-page=\"0\"></div>`;\n }\n return `<div class=\"bk-page\" data-page=\"${page}\">${html}</div>`;\n}\n\nfunction renderSide(spread: readonly [number, number], pagesHtml: readonly string[]): string {\n return `<section class=\"bk-side\">${renderBox(spread[0], pagesHtml)}${renderBox(spread[1], pagesHtml)}</section>`;\n}\n\nfunction renderBanner(imposition: BookletImposition, warning: string | null): string {\n const sheetCount = imposition.sheets.length;\n const warningHtml = warning\n ? `<span class=\"bk-size-warning\">${escapeHtml(warning)}</span>`\n : \"\";\n return `<div class=\"bk-banner screen-only\">\n <h2>Booklet print settings — set these exactly</h2>\n <ol>\n <li>Orientation: <strong>Landscape</strong></li>\n <li>Two-sided printing: <strong>ON</strong></li>\n <li>Flip on <strong>SHORT edge</strong> (also called \"tumble\" or \"short-edge binding\") — long-edge flip prints every back side upside-down</li>\n <li>Scale: <strong>100%</strong> (never \"fit to page\")</li>\n <li>Margins: <strong>None</strong></li>\n </ol>\n <p><strong>Print all pages, fold the whole stack in half, staple the spine.</strong>\n ${sheetCount} sheet${sheetCount === 1 ? \"\" : \"s\"} of paper, ${imposition.paddedPageCount} booklet pages.</p>\n ${warningHtml}\n </div>`;\n}\n\n/**\n * Compose the full booklet document.\n *\n * `pagesHtml[i]` is the already-rendered HTML for logical page i+1. Those\n * fragments are TRUSTED and injected verbatim (they are rendered pages, and\n * escaping them would print markup). Only the title is escaped.\n */\nexport function buildBookletDocument(\n pagesHtml: readonly string[],\n opts?: BookletPrintOptions,\n): string {\n const title = opts?.title ?? \"Booklet\";\n const pageStyles = opts?.pageStyles ?? \"\";\n const imposition = imposeBooklet(Math.max(1, pagesHtml.length));\n const warning = bookletSizeWarning(pagesHtml.length);\n\n // Sheet order: sheet1 front, sheet1 back, sheet2 front, ... — print the whole\n // run, then fold the stack as one.\n const sides = imposition.sheets\n .map((sheet) => renderSide(sheet.front, pagesHtml) + renderSide(sheet.back, pagesHtml))\n .join(\"\\n\");\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(title)}</title>\n <style>\n${BOOKLET_STYLES}\n${pageStyles}\n </style>\n</head>\n<body>\n${renderBanner(imposition, warning)}\n <div class=\"bk-actions screen-only\">\n <button class=\"bk-btn bk-btn-primary\" onclick=\"window.print()\">Print / Save as PDF</button>\n <button class=\"bk-btn bk-btn-secondary\" onclick=\"window.close()\">Close</button>\n </div>\n${sides}\n</body>\n</html>`;\n}\n\n/** Build the booklet document and open it in a print window. */\nexport function printBooklet(\n pagesHtml: readonly string[],\n opts?: BookletPrintOptions,\n): void {\n const title = opts?.title ?? \"Booklet\";\n openPrintWindow(buildBookletDocument(pagesHtml, opts), title);\n}\n","/**\n * @ai-matrx/print/core — the Block Print contract & print-window composition.\n *\n * Ported VERBATIM from matrx-frontend `lib/block-print/block-print-utils.ts`\n * (2026-08-29 state, including the `number` and `select` PrintSetting types the\n * commerce label lane added). Zero dependencies; touches `window` only at call\n * time, so the module stays import-inert and RSC-safe.\n *\n * BlockPrinter is the only interface a host system needs to know about.\n * Each printable unit exports its own BlockPrinter alongside its render\n * component; host code only ever calls print(data, variantId, settings).\n *\n * `buildFitTextScript` is the ONE auto-shrink script (the flashcards\n * FIT_TEXT pattern, parameterized by selector so the label lane shares it).\n */\n\n// ─── Contract ────────────────────────────────────────────────────────────────\n\nexport interface PrintVariant {\n id: string;\n label: string;\n description?: string;\n}\n\n/**\n * A single user-configurable setting shown in the print dialog.\n * Extend the discriminated union for new control types\n * without breaking existing printers.\n */\nexport type PrintSetting =\n | {\n type: \"boolean\";\n id: string;\n label: string;\n description?: string;\n /** Default value shown when the dialog first opens */\n defaultValue: boolean;\n /** Which variant IDs this setting applies to. Omit = applies to all. */\n appliesTo?: string[];\n }\n | {\n /**\n * A numeric \"from → to\" range control, rendered as two small number inputs.\n * Writes two entries into the resolved PrintSettings map — one under fromId,\n * one under toId. Printers interpret 0 (or missing) as \"no bound\" by convention.\n */\n type: \"range\";\n /** Stable id used as React key — not written to the settings map */\n id: string;\n label: string;\n description?: string;\n /** Settings map key for the lower bound value */\n fromId: string;\n /** Settings map key for the upper bound value */\n toId: string;\n defaultFrom: number;\n defaultTo: number;\n /** Minimum accepted value for each input (inclusive). Default 0. */\n min?: number;\n /** Placeholder shown when the input is empty (0). Default \"start\" / \"end\". */\n fromPlaceholder?: string;\n toPlaceholder?: string;\n /** Which variant IDs this setting applies to. Omit = applies to all. */\n appliesTo?: string[];\n }\n | {\n /** A single numeric input (e.g. \"start at label #\", \"copies\"). */\n type: \"number\";\n id: string;\n label: string;\n description?: string;\n defaultValue: number;\n /** Minimum accepted value (inclusive). Default 0. */\n min?: number;\n /** Maximum accepted value (inclusive). Omit = unbounded. */\n max?: number;\n /** Which variant IDs this setting applies to. Omit = applies to all. */\n appliesTo?: string[];\n }\n | {\n /** A one-of-N choice rendered as a compact segmented row. */\n type: \"select\";\n id: string;\n label: string;\n description?: string;\n options: { value: string; label: string }[];\n defaultValue: string;\n /** Which variant IDs this setting applies to. Omit = applies to all. */\n appliesTo?: string[];\n };\n\n/** A resolved map of setting id → current value, passed to print(). */\nexport type PrintSettings = Record<string, boolean | string | number>;\n\n/**\n * The self-contained print capability that each block can export.\n * Host code only ever calls print(data, variantId, settings) — it never inspects internals.\n */\nexport interface BlockPrinter {\n /** Tooltip / aria-label for the print button in the block header */\n label: string;\n\n /**\n * Variants offered to the user before printing.\n * Empty array = no options dialog shown; prints immediately with defaults.\n */\n variants: PrintVariant[];\n\n /**\n * Optional user-configurable settings shown below the variant picker.\n * Omit entirely if the block has no configurable settings.\n */\n settings?: PrintSetting[];\n\n /**\n * Execute the print.\n * data — the block's structured data (serverData or parsed content)\n * variantId — which variant was chosen (undefined = default / no variants)\n * settings — resolved setting values chosen by the user\n */\n print: (\n data: unknown,\n variantId?: string,\n settings?: PrintSettings,\n ) => void | Promise<void>;\n}\n\n// ─── Shared Utilities ─────────────────────────────────────────────────────────\n\nconst PRINT_STYLES = `\n *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }\n\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif;\n font-size: 11pt;\n line-height: 1.6;\n color: #1a1a1a;\n background: #fff;\n max-width: 860px;\n margin: 0 auto;\n padding: 28px 36px;\n }\n\n .print-actions {\n display: flex;\n gap: 10px;\n margin-bottom: 24px;\n padding-bottom: 18px;\n border-bottom: 2px solid #e5e7eb;\n }\n\n .print-btn {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 8px 20px;\n border-radius: 8px;\n font-size: 13px;\n font-family: inherit;\n cursor: pointer;\n border: none;\n font-weight: 600;\n }\n\n .print-btn-primary { background: #2563eb; color: #fff; }\n .print-btn-secondary { background: #f3f4f6; color: #374151; border: 1px solid #d1d5db; }\n\n h1 { font-size: 22pt; font-weight: 700; margin-bottom: 0.5em; }\n h2 { font-size: 16pt; font-weight: 700; margin: 1.2em 0 0.4em; border-bottom: 1px solid #e5e7eb; padding-bottom: 0.2em; }\n h3 { font-size: 13pt; font-weight: 600; margin: 1em 0 0.3em; }\n p { margin-bottom: 0.7em; }\n\n table {\n width: 100%;\n border-collapse: collapse;\n margin: 1em 0;\n font-size: 10pt;\n }\n th {\n background: #1e293b;\n color: #f8fafc;\n font-weight: 600;\n text-align: left;\n padding: 7px 12px;\n border: 1px solid #334155;\n }\n td {\n padding: 6px 12px;\n border: 1px solid #e2e8f0;\n vertical-align: top;\n }\n tr:nth-child(even) td { background: #f8fafc; }\n\n @media print {\n body { max-width: 100%; padding: 0; }\n .print-actions { display: none !important; }\n th { -webkit-print-color-adjust: exact; print-color-adjust: exact; }\n }\n`;\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n\n/**\n * Wrap body HTML in a complete, styled print document.\n */\nexport function buildPrintDocument(\n bodyHtml: string,\n title = \"AI Response\",\n extraStyles = \"\",\n): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${escapeHtml(title)}</title>\n <style>\n${PRINT_STYLES}\n${extraStyles}\n </style>\n</head>\n<body>\n <div class=\"print-actions\">\n <button class=\"print-btn print-btn-primary\" onclick=\"window.print()\">Print / Save as PDF</button>\n <button class=\"print-btn print-btn-secondary\" onclick=\"window.close()\">Close</button>\n </div>\n <div class=\"content\">\n${bodyHtml}\n </div>\n</body>\n</html>`;\n}\n\n/**\n * Open a new browser window and write a complete HTML document into it.\n * Falls back to downloading an .html file if the popup is blocked.\n */\nexport function openPrintWindow(\n htmlDocument: string,\n filename = \"print\",\n): void {\n const win = window.open(\"\", \"_blank\", \"width=920,height=720,scrollbars=yes\");\n if (!win) {\n // Popup blocked — fall back to file download\n const blob = new Blob([htmlDocument], { type: \"text/html;charset=utf-8\" });\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = `${filename.replace(/\\s+/g, \"-\").toLowerCase()}.html`;\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n URL.revokeObjectURL(url);\n return;\n }\n win.document.open();\n win.document.write(htmlDocument);\n win.document.close();\n}\n\n/**\n * Shorthand: build the document and open it in one call.\n */\nexport function printHtmlContent(\n bodyHtml: string,\n title = \"AI Response\",\n extraStyles = \"\",\n): void {\n const doc = buildPrintDocument(bodyHtml, title, extraStyles);\n openPrintWindow(doc, title);\n}\n\n/**\n * Build the auto-shrink script that runs INSIDE a printed window: for every\n * element matching each selector, its font-size is reduced (0.5pt steps, 6pt\n * floor) until it fits its parent element's box. This is the flashcards\n * FIT_TEXT behavior verbatim, parameterized by selector so every lane\n * (flashcards card text, Avery text, label captions) shares the ONE loop.\n *\n * Pass the same selectors the original used to get byte-identical behavior:\n * flashcards passes `[\".card-text .card-text-inner\", \".avery-text-wrap .avery-text\"]`.\n */\nexport function buildFitTextScript(selectors: readonly string[]): string {\n const selectorsJson = JSON.stringify([...selectors]);\n return `\n<script>\n(function() {\n function fitText(el, container) {\n // container is the bounding box we must fit inside\n var maxW = container.clientWidth;\n var maxH = container.clientHeight;\n var size = parseFloat(window.getComputedStyle(el).fontSize);\n var minSize = 6;\n // Give the element a chance to reflow at current size before measuring\n el.style.fontSize = size + \"pt\";\n while (size > minSize && (el.scrollWidth > maxW + 1 || el.scrollHeight > maxH + 1)) {\n size -= 0.5;\n el.style.fontSize = size + \"pt\";\n }\n }\n function runAll() {\n var selectors = ${selectorsJson};\n for (var s = 0; s < selectors.length; s++) {\n var els = document.querySelectorAll(selectors[s]);\n for (var i = 0; i < els.length; i++) {\n fitText(els[i], els[i].parentElement);\n }\n }\n }\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", runAll);\n } else {\n // document.write pages may already be loaded\n setTimeout(runAll, 0);\n }\n})();\n</script>`;\n}\n\nexport { escapeHtml };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwMA,SAAS,WAAW,KAAqB;AACvC,SAAO,IACJ,QAAQ,MAAM,OAAO,EACrB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ,EACtB,QAAQ,MAAM,OAAO;AAC1B;AAqCO,SAAS,gBACd,cACA,WAAW,SACL;AACN,QAAM,MAAM,OAAO,KAAK,IAAI,UAAU,qCAAqC;AAC3E,MAAI,CAAC,KAAK;AAER,UAAM,OAAO,IAAI,KAAK,CAAC,YAAY,GAAG,EAAE,MAAM,0BAA0B,CAAC;AACzE,UAAM,MAAM,IAAI,gBAAgB,IAAI;AACpC,UAAM,IAAI,SAAS,cAAc,GAAG;AACpC,MAAE,OAAO;AACT,MAAE,WAAW,GAAG,SAAS,QAAQ,QAAQ,GAAG,EAAE,YAAY,CAAC;AAC3D,aAAS,KAAK,YAAY,CAAC;AAC3B,MAAE,MAAM;AACR,aAAS,KAAK,YAAY,CAAC;AAC3B,QAAI,gBAAgB,GAAG;AACvB;AAAA,EACF;AACA,MAAI,SAAS,KAAK;AAClB,MAAI,SAAS,MAAM,YAAY;AAC/B,MAAI,SAAS,MAAM;AACrB;;;AD/LA,IAAM,kBAAkB;AAOxB,IAAM,0BAA0B;AAWzB,SAAS,cAAc,WAAsC;AAClE,MAAI,CAAC,OAAO,UAAU,SAAS,KAAK,YAAY,GAAG;AACjD,UAAM,IAAI;AAAA,MACR,iEAAiE,OAAO,SAAS,CAAC;AAAA,IACpF;AAAA,EACF;AAEA,QAAM,SAAS,KAAK,KAAK,YAAY,eAAe,IAAI;AAExD,QAAM,OAAO,CAAC,MAAuB,IAAI,YAAY,IAAI;AAEzD,QAAM,SAAyB,CAAC;AAChC,WAAS,IAAI,GAAG,KAAK,SAAS,iBAAiB,KAAK,GAAG;AACrD,WAAO,KAAK;AAAA,MACV,OAAO,CAAC,KAAK,SAAS,IAAI,IAAI,CAAC,GAAG,KAAK,IAAI,IAAI,CAAC,CAAC;AAAA,MACjD,MAAM,CAAC,KAAK,IAAI,CAAC,GAAG,KAAK,SAAS,IAAI,IAAI,CAAC,CAAC;AAAA,IAC9C,CAAC;AAAA,EACH;AAEA,SAAO,EAAE,iBAAiB,QAAQ,QAAQ,yBAAyB,KAAK;AAC1E;AAMO,SAAS,mBAAmB,WAAkC;AACnE,MAAI,CAAC,OAAO,UAAU,SAAS,KAAK,YAAY,EAAG,QAAO;AAC1D,QAAM,SAAS,KAAK,KAAK,YAAY,eAAe,IAAI;AACxD,MAAI,UAAU,wBAAyB,QAAO;AAC9C,SACE,mBAAmB,MAAM,WAAW,SAAS,eAAe,wBAC9C,uBAAuB,qLAEb,uBAAuB;AAEnD;AAIA,IAAM,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkEvB,SAAS,UAAU,MAAc,WAAsC;AAGrE,QAAM,OAAO,SAAS,IAAI,SAAY,UAAU,OAAO,CAAC;AACxD,MAAI,SAAS,QAAW;AACtB,WAAO;AAAA,EACT;AACA,SAAO,mCAAmC,IAAI,KAAK,IAAI;AACzD;AAEA,SAAS,WAAW,QAAmC,WAAsC;AAC3F,SAAO,4BAA4B,UAAU,OAAO,CAAC,GAAG,SAAS,CAAC,GAAG,UAAU,OAAO,CAAC,GAAG,SAAS,CAAC;AACtG;AAEA,SAAS,aAAa,YAA+B,SAAgC;AACnF,QAAM,aAAa,WAAW,OAAO;AACrC,QAAM,cAAc,UAChB,iCAAiC,WAAW,OAAO,CAAC,YACpD;AACJ,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAUH,UAAU,SAAS,eAAe,IAAI,KAAK,GAAG,cAAc,WAAW,eAAe;AAAA,MACtF,WAAW;AAAA;AAEjB;AASO,SAAS,qBACd,WACA,MACQ;AACR,QAAM,QAAQ,MAAM,SAAS;AAC7B,QAAM,aAAa,MAAM,cAAc;AACvC,QAAM,aAAa,cAAc,KAAK,IAAI,GAAG,UAAU,MAAM,CAAC;AAC9D,QAAM,UAAU,mBAAmB,UAAU,MAAM;AAInD,QAAM,QAAQ,WAAW,OACtB,IAAI,CAAC,UAAU,WAAW,MAAM,OAAO,SAAS,IAAI,WAAW,MAAM,MAAM,SAAS,CAAC,EACrF,KAAK,IAAI;AAEZ,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA,WAKE,WAAW,KAAK,CAAC;AAAA;AAAA,EAE1B,cAAc;AAAA,EACd,UAAU;AAAA;AAAA;AAAA;AAAA,EAIV,aAAa,YAAY,OAAO,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA,EAKjC,KAAK;AAAA;AAAA;AAGP;AAGO,SAAS,aACd,WACA,MACM;AACN,QAAM,QAAQ,MAAM,SAAS;AAC7B,kBAAgB,qBAAqB,WAAW,IAAI,GAAG,KAAK;AAC9D;","names":[]}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @ai-matrx/print/booklet — saddle-stitch booklet imposition.
|
|
3
|
+
*
|
|
4
|
+
* The education white space: no test-prep / worksheet tool offers "turn this
|
|
5
|
+
* into a fold-and-staple booklet". This module is the whole capability —
|
|
6
|
+
* the imposition math, the size guidance, and a 2-up landscape print lane
|
|
7
|
+
* composed over ./core.
|
|
8
|
+
*
|
|
9
|
+
* Zero dependencies: pure arithmetic plus string composition. Import-inert —
|
|
10
|
+
* `window` is touched only inside printBooklet, at call time.
|
|
11
|
+
*
|
|
12
|
+
* ── THE MATH ────────────────────────────────────────────────────────────────
|
|
13
|
+
* A saddle-stitch booklet is a stack of sheets folded in half together and
|
|
14
|
+
* stapled through the spine. Every sheet carries FOUR logical pages (two per
|
|
15
|
+
* side), so the page count is padded up to a multiple of 4 with blanks.
|
|
16
|
+
*
|
|
17
|
+
* For sheet i (1-indexed, i = 1..N/4) of an N-page (padded) booklet:
|
|
18
|
+
* front spread = [N − 2i + 2, 2i − 1] (left, right)
|
|
19
|
+
* back spread = [2i, N − 2i + 1] (left, right)
|
|
20
|
+
*
|
|
21
|
+
* Worked anchor, N = 8:
|
|
22
|
+
* sheet 1 → front [8, 1] back [2, 7]
|
|
23
|
+
* sheet 2 → front [6, 3] back [4, 5]
|
|
24
|
+
* Every spread's two page numbers sum to N + 1 — the invariant that makes the
|
|
25
|
+
* fold work, and the cheapest way to check an imposition is right.
|
|
26
|
+
*
|
|
27
|
+
* ── THE DUPLEX TRAP ─────────────────────────────────────────────────────────
|
|
28
|
+
* These spreads are 2-up LANDSCAPE. Ordinary duplex printing flips on the LONG
|
|
29
|
+
* edge, which for a landscape sheet means the back side lands upside-down
|
|
30
|
+
* relative to the front — the booklet folds into gibberish. There are exactly
|
|
31
|
+
* two fixes: instruct the human to select short-edge (tumble) duplex, or
|
|
32
|
+
* pre-rotate every back side 180°. A print-window lane cannot pre-rotate
|
|
33
|
+
* reliably (browsers differ on how `@page`/transform interact with duplex), so
|
|
34
|
+
* THIS lane instructs. `BookletImposition.requiresShortEdgeDuplex` exposes the
|
|
35
|
+
* trap in the type system so a future PDF lane — which owns its own page
|
|
36
|
+
* transforms — can take the pre-rotate branch instead of the instruction.
|
|
37
|
+
*/
|
|
38
|
+
/**
|
|
39
|
+
* One physical sheet of paper. Each tuple is [left, right] as the reader sees
|
|
40
|
+
* that side laid flat, in 1-based logical page numbers.
|
|
41
|
+
* `0` means a blank pad page (a slot past the end of the supplied content).
|
|
42
|
+
*/
|
|
43
|
+
interface BookletSheet {
|
|
44
|
+
front: [number, number];
|
|
45
|
+
back: [number, number];
|
|
46
|
+
}
|
|
47
|
+
interface BookletImposition {
|
|
48
|
+
/** Supplied page count rounded UP to the next multiple of 4. */
|
|
49
|
+
paddedPageCount: number;
|
|
50
|
+
/** Sheets in print order: sheet 1 outermost, last sheet at the fold. */
|
|
51
|
+
sheets: BookletSheet[];
|
|
52
|
+
/**
|
|
53
|
+
* true when ordinary long-edge duplex would flip the backs — consumer must
|
|
54
|
+
* either instruct short-edge/tumble duplex or pre-rotate backs 180° (PDF
|
|
55
|
+
* lanes). Always true for this 2-up landscape imposition.
|
|
56
|
+
*/
|
|
57
|
+
requiresShortEdgeDuplex: true;
|
|
58
|
+
}
|
|
59
|
+
interface BookletPrintOptions {
|
|
60
|
+
title?: string;
|
|
61
|
+
/** CSS injected after the layout styles — style the caller's page content. */
|
|
62
|
+
pageStyles?: string;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Impose `pageCount` logical pages onto saddle-stitch sheets.
|
|
66
|
+
*
|
|
67
|
+
* Padding is appended at the END of the logical page run, so pad slots always
|
|
68
|
+
* carry the HIGHEST page numbers — which is why they surface as `0` in the
|
|
69
|
+
* spreads nearest the front cover (N=1 → sheet 1 front [0, 1], back [0, 0]).
|
|
70
|
+
*
|
|
71
|
+
* @throws RangeError when pageCount is not a positive integer.
|
|
72
|
+
*/
|
|
73
|
+
declare function imposeBooklet(pageCount: number): BookletImposition;
|
|
74
|
+
/**
|
|
75
|
+
* Human warning when a booklet is too fat to saddle-stitch well, else null.
|
|
76
|
+
* Measured on the PADDED count — that is what actually goes through the folder.
|
|
77
|
+
*/
|
|
78
|
+
declare function bookletSizeWarning(pageCount: number): string | null;
|
|
79
|
+
/**
|
|
80
|
+
* Compose the full booklet document.
|
|
81
|
+
*
|
|
82
|
+
* `pagesHtml[i]` is the already-rendered HTML for logical page i+1. Those
|
|
83
|
+
* fragments are TRUSTED and injected verbatim (they are rendered pages, and
|
|
84
|
+
* escaping them would print markup). Only the title is escaped.
|
|
85
|
+
*/
|
|
86
|
+
declare function buildBookletDocument(pagesHtml: readonly string[], opts?: BookletPrintOptions): string;
|
|
87
|
+
/** Build the booklet document and open it in a print window. */
|
|
88
|
+
declare function printBooklet(pagesHtml: readonly string[], opts?: BookletPrintOptions): void;
|
|
89
|
+
|
|
90
|
+
export { type BookletImposition, type BookletPrintOptions, type BookletSheet, bookletSizeWarning, buildBookletDocument, imposeBooklet, printBooklet };
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @ai-matrx/print/booklet — saddle-stitch booklet imposition.
|
|
3
|
+
*
|
|
4
|
+
* The education white space: no test-prep / worksheet tool offers "turn this
|
|
5
|
+
* into a fold-and-staple booklet". This module is the whole capability —
|
|
6
|
+
* the imposition math, the size guidance, and a 2-up landscape print lane
|
|
7
|
+
* composed over ./core.
|
|
8
|
+
*
|
|
9
|
+
* Zero dependencies: pure arithmetic plus string composition. Import-inert —
|
|
10
|
+
* `window` is touched only inside printBooklet, at call time.
|
|
11
|
+
*
|
|
12
|
+
* ── THE MATH ────────────────────────────────────────────────────────────────
|
|
13
|
+
* A saddle-stitch booklet is a stack of sheets folded in half together and
|
|
14
|
+
* stapled through the spine. Every sheet carries FOUR logical pages (two per
|
|
15
|
+
* side), so the page count is padded up to a multiple of 4 with blanks.
|
|
16
|
+
*
|
|
17
|
+
* For sheet i (1-indexed, i = 1..N/4) of an N-page (padded) booklet:
|
|
18
|
+
* front spread = [N − 2i + 2, 2i − 1] (left, right)
|
|
19
|
+
* back spread = [2i, N − 2i + 1] (left, right)
|
|
20
|
+
*
|
|
21
|
+
* Worked anchor, N = 8:
|
|
22
|
+
* sheet 1 → front [8, 1] back [2, 7]
|
|
23
|
+
* sheet 2 → front [6, 3] back [4, 5]
|
|
24
|
+
* Every spread's two page numbers sum to N + 1 — the invariant that makes the
|
|
25
|
+
* fold work, and the cheapest way to check an imposition is right.
|
|
26
|
+
*
|
|
27
|
+
* ── THE DUPLEX TRAP ─────────────────────────────────────────────────────────
|
|
28
|
+
* These spreads are 2-up LANDSCAPE. Ordinary duplex printing flips on the LONG
|
|
29
|
+
* edge, which for a landscape sheet means the back side lands upside-down
|
|
30
|
+
* relative to the front — the booklet folds into gibberish. There are exactly
|
|
31
|
+
* two fixes: instruct the human to select short-edge (tumble) duplex, or
|
|
32
|
+
* pre-rotate every back side 180°. A print-window lane cannot pre-rotate
|
|
33
|
+
* reliably (browsers differ on how `@page`/transform interact with duplex), so
|
|
34
|
+
* THIS lane instructs. `BookletImposition.requiresShortEdgeDuplex` exposes the
|
|
35
|
+
* trap in the type system so a future PDF lane — which owns its own page
|
|
36
|
+
* transforms — can take the pre-rotate branch instead of the instruction.
|
|
37
|
+
*/
|
|
38
|
+
/**
|
|
39
|
+
* One physical sheet of paper. Each tuple is [left, right] as the reader sees
|
|
40
|
+
* that side laid flat, in 1-based logical page numbers.
|
|
41
|
+
* `0` means a blank pad page (a slot past the end of the supplied content).
|
|
42
|
+
*/
|
|
43
|
+
interface BookletSheet {
|
|
44
|
+
front: [number, number];
|
|
45
|
+
back: [number, number];
|
|
46
|
+
}
|
|
47
|
+
interface BookletImposition {
|
|
48
|
+
/** Supplied page count rounded UP to the next multiple of 4. */
|
|
49
|
+
paddedPageCount: number;
|
|
50
|
+
/** Sheets in print order: sheet 1 outermost, last sheet at the fold. */
|
|
51
|
+
sheets: BookletSheet[];
|
|
52
|
+
/**
|
|
53
|
+
* true when ordinary long-edge duplex would flip the backs — consumer must
|
|
54
|
+
* either instruct short-edge/tumble duplex or pre-rotate backs 180° (PDF
|
|
55
|
+
* lanes). Always true for this 2-up landscape imposition.
|
|
56
|
+
*/
|
|
57
|
+
requiresShortEdgeDuplex: true;
|
|
58
|
+
}
|
|
59
|
+
interface BookletPrintOptions {
|
|
60
|
+
title?: string;
|
|
61
|
+
/** CSS injected after the layout styles — style the caller's page content. */
|
|
62
|
+
pageStyles?: string;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Impose `pageCount` logical pages onto saddle-stitch sheets.
|
|
66
|
+
*
|
|
67
|
+
* Padding is appended at the END of the logical page run, so pad slots always
|
|
68
|
+
* carry the HIGHEST page numbers — which is why they surface as `0` in the
|
|
69
|
+
* spreads nearest the front cover (N=1 → sheet 1 front [0, 1], back [0, 0]).
|
|
70
|
+
*
|
|
71
|
+
* @throws RangeError when pageCount is not a positive integer.
|
|
72
|
+
*/
|
|
73
|
+
declare function imposeBooklet(pageCount: number): BookletImposition;
|
|
74
|
+
/**
|
|
75
|
+
* Human warning when a booklet is too fat to saddle-stitch well, else null.
|
|
76
|
+
* Measured on the PADDED count — that is what actually goes through the folder.
|
|
77
|
+
*/
|
|
78
|
+
declare function bookletSizeWarning(pageCount: number): string | null;
|
|
79
|
+
/**
|
|
80
|
+
* Compose the full booklet document.
|
|
81
|
+
*
|
|
82
|
+
* `pagesHtml[i]` is the already-rendered HTML for logical page i+1. Those
|
|
83
|
+
* fragments are TRUSTED and injected verbatim (they are rendered pages, and
|
|
84
|
+
* escaping them would print markup). Only the title is escaped.
|
|
85
|
+
*/
|
|
86
|
+
declare function buildBookletDocument(pagesHtml: readonly string[], opts?: BookletPrintOptions): string;
|
|
87
|
+
/** Build the booklet document and open it in a print window. */
|
|
88
|
+
declare function printBooklet(pagesHtml: readonly string[], opts?: BookletPrintOptions): void;
|
|
89
|
+
|
|
90
|
+
export { type BookletImposition, type BookletPrintOptions, type BookletSheet, bookletSizeWarning, buildBookletDocument, imposeBooklet, printBooklet };
|
package/dist/booklet.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// src/core.ts
|
|
2
|
+
function escapeHtml(str) {
|
|
3
|
+
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
4
|
+
}
|
|
5
|
+
function openPrintWindow(htmlDocument, filename = "print") {
|
|
6
|
+
const win = window.open("", "_blank", "width=920,height=720,scrollbars=yes");
|
|
7
|
+
if (!win) {
|
|
8
|
+
const blob = new Blob([htmlDocument], { type: "text/html;charset=utf-8" });
|
|
9
|
+
const url = URL.createObjectURL(blob);
|
|
10
|
+
const a = document.createElement("a");
|
|
11
|
+
a.href = url;
|
|
12
|
+
a.download = `${filename.replace(/\s+/g, "-").toLowerCase()}.html`;
|
|
13
|
+
document.body.appendChild(a);
|
|
14
|
+
a.click();
|
|
15
|
+
document.body.removeChild(a);
|
|
16
|
+
URL.revokeObjectURL(url);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
win.document.open();
|
|
20
|
+
win.document.write(htmlDocument);
|
|
21
|
+
win.document.close();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// src/booklet.ts
|
|
25
|
+
var PAGES_PER_SHEET = 4;
|
|
26
|
+
var SADDLE_STITCH_MAX_PAGES = 48;
|
|
27
|
+
function imposeBooklet(pageCount) {
|
|
28
|
+
if (!Number.isInteger(pageCount) || pageCount < 1) {
|
|
29
|
+
throw new RangeError(
|
|
30
|
+
`imposeBooklet: pageCount must be a positive integer, received ${String(pageCount)}`
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
const padded = Math.ceil(pageCount / PAGES_PER_SHEET) * PAGES_PER_SHEET;
|
|
34
|
+
const slot = (n) => n > pageCount ? 0 : n;
|
|
35
|
+
const sheets = [];
|
|
36
|
+
for (let i = 1; i <= padded / PAGES_PER_SHEET; i += 1) {
|
|
37
|
+
sheets.push({
|
|
38
|
+
front: [slot(padded - 2 * i + 2), slot(2 * i - 1)],
|
|
39
|
+
back: [slot(2 * i), slot(padded - 2 * i + 1)]
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
return { paddedPageCount: padded, sheets, requiresShortEdgeDuplex: true };
|
|
43
|
+
}
|
|
44
|
+
function bookletSizeWarning(pageCount) {
|
|
45
|
+
if (!Number.isInteger(pageCount) || pageCount < 1) return null;
|
|
46
|
+
const padded = Math.ceil(pageCount / PAGES_PER_SHEET) * PAGES_PER_SHEET;
|
|
47
|
+
if (padded <= SADDLE_STITCH_MAX_PAGES) return null;
|
|
48
|
+
return `This booklet is ${padded} pages (${padded / PAGES_PER_SHEET} sheets). Past about ${SADDLE_STITCH_MAX_PAGES} pages a saddle-stitch booklet gets too thick to fold flat and the inner pages creep out at the fore-edge. Consider printing it as a plain workbook instead, or splitting it into ${SADDLE_STITCH_MAX_PAGES}-page signatures.`;
|
|
49
|
+
}
|
|
50
|
+
var BOOKLET_STYLES = `
|
|
51
|
+
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
|
52
|
+
|
|
53
|
+
@page { size: 11in 8.5in; margin: 0; }
|
|
54
|
+
|
|
55
|
+
html, body {
|
|
56
|
+
background: #fff;
|
|
57
|
+
color: #1a1a1a;
|
|
58
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
.bk-side {
|
|
62
|
+
display: flex;
|
|
63
|
+
flex-direction: row;
|
|
64
|
+
width: 11in;
|
|
65
|
+
height: 8.5in;
|
|
66
|
+
page-break-after: always;
|
|
67
|
+
break-after: page;
|
|
68
|
+
overflow: hidden;
|
|
69
|
+
}
|
|
70
|
+
.bk-side:last-of-type { page-break-after: auto; break-after: auto; }
|
|
71
|
+
|
|
72
|
+
.bk-page {
|
|
73
|
+
width: 5.5in;
|
|
74
|
+
height: 8.5in;
|
|
75
|
+
overflow: hidden;
|
|
76
|
+
position: relative;
|
|
77
|
+
}
|
|
78
|
+
.bk-blank { /* intentionally empty \u2014 a padded slot */ }
|
|
79
|
+
|
|
80
|
+
.bk-banner {
|
|
81
|
+
background: #fef3c7;
|
|
82
|
+
border: 2px solid #f59e0b;
|
|
83
|
+
border-radius: 8px;
|
|
84
|
+
padding: 14px 18px;
|
|
85
|
+
margin: 18px;
|
|
86
|
+
font-size: 13px;
|
|
87
|
+
line-height: 1.55;
|
|
88
|
+
color: #78350f;
|
|
89
|
+
max-width: 11in;
|
|
90
|
+
}
|
|
91
|
+
.bk-banner h2 { font-size: 15px; margin-bottom: 6px; }
|
|
92
|
+
.bk-banner ol { margin: 6px 0 6px 20px; }
|
|
93
|
+
.bk-banner strong { font-weight: 700; }
|
|
94
|
+
.bk-banner .bk-size-warning {
|
|
95
|
+
display: block;
|
|
96
|
+
margin-top: 10px;
|
|
97
|
+
padding-top: 10px;
|
|
98
|
+
border-top: 1px solid #f59e0b;
|
|
99
|
+
color: #7f1d1d;
|
|
100
|
+
font-weight: 600;
|
|
101
|
+
}
|
|
102
|
+
.bk-actions { display: flex; gap: 10px; margin: 0 18px 18px; }
|
|
103
|
+
.bk-btn {
|
|
104
|
+
padding: 8px 20px; border-radius: 8px; font-size: 13px; font-family: inherit;
|
|
105
|
+
font-weight: 600; cursor: pointer; border: none;
|
|
106
|
+
}
|
|
107
|
+
.bk-btn-primary { background: #2563eb; color: #fff; }
|
|
108
|
+
.bk-btn-secondary { background: #f3f4f6; color: #374151; border: 1px solid #d1d5db; }
|
|
109
|
+
|
|
110
|
+
@media print {
|
|
111
|
+
.screen-only { display: none !important; }
|
|
112
|
+
.bk-side { page-break-after: always; break-after: page; }
|
|
113
|
+
}
|
|
114
|
+
`;
|
|
115
|
+
function renderBox(page, pagesHtml) {
|
|
116
|
+
const html = page === 0 ? void 0 : pagesHtml[page - 1];
|
|
117
|
+
if (html === void 0) {
|
|
118
|
+
return `<div class="bk-page bk-blank" data-page="0"></div>`;
|
|
119
|
+
}
|
|
120
|
+
return `<div class="bk-page" data-page="${page}">${html}</div>`;
|
|
121
|
+
}
|
|
122
|
+
function renderSide(spread, pagesHtml) {
|
|
123
|
+
return `<section class="bk-side">${renderBox(spread[0], pagesHtml)}${renderBox(spread[1], pagesHtml)}</section>`;
|
|
124
|
+
}
|
|
125
|
+
function renderBanner(imposition, warning) {
|
|
126
|
+
const sheetCount = imposition.sheets.length;
|
|
127
|
+
const warningHtml = warning ? `<span class="bk-size-warning">${escapeHtml(warning)}</span>` : "";
|
|
128
|
+
return `<div class="bk-banner screen-only">
|
|
129
|
+
<h2>Booklet print settings \u2014 set these exactly</h2>
|
|
130
|
+
<ol>
|
|
131
|
+
<li>Orientation: <strong>Landscape</strong></li>
|
|
132
|
+
<li>Two-sided printing: <strong>ON</strong></li>
|
|
133
|
+
<li>Flip on <strong>SHORT edge</strong> (also called "tumble" or "short-edge binding") \u2014 long-edge flip prints every back side upside-down</li>
|
|
134
|
+
<li>Scale: <strong>100%</strong> (never "fit to page")</li>
|
|
135
|
+
<li>Margins: <strong>None</strong></li>
|
|
136
|
+
</ol>
|
|
137
|
+
<p><strong>Print all pages, fold the whole stack in half, staple the spine.</strong>
|
|
138
|
+
${sheetCount} sheet${sheetCount === 1 ? "" : "s"} of paper, ${imposition.paddedPageCount} booklet pages.</p>
|
|
139
|
+
${warningHtml}
|
|
140
|
+
</div>`;
|
|
141
|
+
}
|
|
142
|
+
function buildBookletDocument(pagesHtml, opts) {
|
|
143
|
+
const title = opts?.title ?? "Booklet";
|
|
144
|
+
const pageStyles = opts?.pageStyles ?? "";
|
|
145
|
+
const imposition = imposeBooklet(Math.max(1, pagesHtml.length));
|
|
146
|
+
const warning = bookletSizeWarning(pagesHtml.length);
|
|
147
|
+
const sides = imposition.sheets.map((sheet) => renderSide(sheet.front, pagesHtml) + renderSide(sheet.back, pagesHtml)).join("\n");
|
|
148
|
+
return `<!DOCTYPE html>
|
|
149
|
+
<html lang="en">
|
|
150
|
+
<head>
|
|
151
|
+
<meta charset="UTF-8">
|
|
152
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
153
|
+
<title>${escapeHtml(title)}</title>
|
|
154
|
+
<style>
|
|
155
|
+
${BOOKLET_STYLES}
|
|
156
|
+
${pageStyles}
|
|
157
|
+
</style>
|
|
158
|
+
</head>
|
|
159
|
+
<body>
|
|
160
|
+
${renderBanner(imposition, warning)}
|
|
161
|
+
<div class="bk-actions screen-only">
|
|
162
|
+
<button class="bk-btn bk-btn-primary" onclick="window.print()">Print / Save as PDF</button>
|
|
163
|
+
<button class="bk-btn bk-btn-secondary" onclick="window.close()">Close</button>
|
|
164
|
+
</div>
|
|
165
|
+
${sides}
|
|
166
|
+
</body>
|
|
167
|
+
</html>`;
|
|
168
|
+
}
|
|
169
|
+
function printBooklet(pagesHtml, opts) {
|
|
170
|
+
const title = opts?.title ?? "Booklet";
|
|
171
|
+
openPrintWindow(buildBookletDocument(pagesHtml, opts), title);
|
|
172
|
+
}
|
|
173
|
+
export {
|
|
174
|
+
bookletSizeWarning,
|
|
175
|
+
buildBookletDocument,
|
|
176
|
+
imposeBooklet,
|
|
177
|
+
printBooklet
|
|
178
|
+
};
|
|
179
|
+
//# sourceMappingURL=booklet.js.map
|