@marver-design/marver 0.30.1 → 0.32.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 +70 -0
- package/README.md +12 -8
- package/dist/{anchor-check-Bv4o-R2T.mjs → anchor-check-DZtX13ly.mjs} +1 -1
- package/dist/{board-tree-BXR8dw4b.mjs → board-tree-DGj0HhEE.mjs} +6 -2
- package/dist/{boards-EH2onUXM.mjs → boards-Cim1GTKc.mjs} +32 -2
- package/dist/{boards-BeWtjGUM.mjs → boards-jHmEPLV7.mjs} +7 -7
- package/dist/{build-zWGXSzly.mjs → build-D2dHEWX-.mjs} +14 -17
- package/dist/{capture-DEtM4qm5.mjs → capture-HaS-1or8.mjs} +1 -1
- package/dist/cli.mjs +38 -20
- package/dist/{collab-BEAcXrBb.mjs → collab-D2NcrOB8.mjs} +53 -14
- package/dist/comment-actions-Bxf9Ld4g.mjs +351 -0
- package/dist/{comments-XNhMmSSu.mjs → comments-ocvsnt2j.mjs} +85 -10
- package/dist/config-B0YcFtqS.mjs +510 -0
- package/dist/{context-BUnFiyA3.mjs → context-Cj2TcC0H.mjs} +3 -3
- package/dist/{daemon-CChgWJNq.mjs → daemon-D6TrdgMi.mjs} +268 -28
- package/dist/deep-link-DYtuT740.mjs +163 -0
- package/dist/{dev-DOgIITpT.mjs → dev-DMQYbw-2.mjs} +23 -16
- package/dist/devices-uJZ2inMq.mjs +155 -0
- package/dist/{events-CLH4ijKP.mjs → events-Dieo1482.mjs} +49 -4
- package/dist/{init-CYlFaRzG.mjs → init-BgusplYn.mjs} +40 -10
- package/dist/{jam-Cj5gBvwD.mjs → jam-CkuLL8A8.mjs} +1 -1
- package/dist/{link-BFFRgrMt.mjs → link-aZq5cExV.mjs} +54 -7
- package/dist/{logo-CXY-1yrn.mjs → logo-C9s7-Cy9.mjs} +89 -66
- package/dist/{ls-NqmePKOf.mjs → ls-DGVIW-Io.mjs} +1 -1
- package/dist/{manifest-DPZ3WNg_.mjs → manifest-CK8Qh4Nq.mjs} +255 -13
- package/dist/{marks-BnNANic9.mjs → marks-C8oX8kbE.mjs} +3 -3
- package/dist/{marks-DBp3h1Mc.mjs → marks-Dt-5JXCp.mjs} +18 -5
- package/dist/{marver-id-gate-vBLb_Icb.mjs → marver-id-gate-BAeuMeaU.mjs} +11 -7
- package/dist/md-B9_13Q0R.mjs +105 -0
- package/dist/notes-CRAX4wgk.mjs +148 -0
- package/dist/own-C8Mq0Hnf.mjs +128 -0
- package/dist/pdf-Cf9GIoIM.mjs +2299 -0
- package/dist/pdf-HB0prF75.mjs +117 -0
- package/dist/{perf-6MOTHxay.mjs → perf-9ZEF5KLO.mjs} +5 -5
- package/dist/{perf-BCxAo0IS.mjs → perf-BA_NDarr.mjs} +2 -1
- package/dist/{plugin-CFWBcAba.mjs → plugin-DesQP9L5.mjs} +565 -107
- package/dist/{poster-DPPpQiva.mjs → poster-Bb6WraCA.mjs} +1 -1
- package/dist/{profile-B1FKOM1e.mjs → profile-cdmSer1k.mjs} +1 -1
- package/dist/{publish-bakes-_Zx8crP3.mjs → publish-bakes-EjMmukJB.mjs} +3 -3
- package/dist/{queue-DeSQm24g.mjs → queue-BLLfdlDw.mjs} +156 -11
- package/dist/{recover-mDUVsnPd.mjs → recover-B3dmatx4.mjs} +2 -2
- package/dist/{serve-DQv3Ti6X.mjs → serve-kcF6-H8V.mjs} +4 -4
- package/dist/{session-VDJfXEEm.mjs → session-DBF-nQvq.mjs} +29 -3
- package/dist/{share-Bu_kuOKL.mjs → share-CS2mg27O.mjs} +1 -1
- package/dist/{shot-d4h_hJi9.mjs → shot-Bjt2MQe3.mjs} +4 -4
- package/dist/{shot-DBWN8hPP.mjs → shot-BuUCG46-.mjs} +1 -1
- package/dist/show-DhmiUu01.mjs +101 -0
- package/dist/{sizes-wjXDev3b.mjs → sizes-BckcL4Zz.mjs} +1 -1
- package/dist/{slots-Dn4Onb0V.mjs → slots-BOcfIqxy.mjs} +15 -3
- package/dist/{summary-Y8MY1Wuc.mjs → summary-cPmRDGpX.mjs} +1 -1
- package/dist/{sync-CMozOwZ0.mjs → sync-BNWwh8OF.mjs} +205 -7
- package/dist/{work-DJxH7cCX.mjs → work-B4tydWnf.mjs} +38 -2
- package/dist/{work-BYWD_1Zf.mjs → work-CzIXp7n1.mjs} +3 -3
- package/docs/app.md +143 -6
- package/docs/boards-and-folders.md +41 -7
- package/docs/jam-session.md +5 -0
- package/docs/live-jam.md +9 -0
- package/docs/pdf.md +108 -0
- package/docs/publish.md +9 -9
- package/docs/sharing.md +11 -0
- package/docs/slides.md +11 -1
- package/package.json +3 -1
- package/src/client/content/index.tsx +4 -2
- package/src/client/frame-host/main.tsx +3 -0
- package/src/client/shell/App.tsx +71 -24
- package/src/client/shell/BoardList.tsx +16 -7
- package/src/client/shell/Comments.tsx +77 -16
- package/src/client/shell/Play.tsx +104 -27
- package/src/client/shell/Toolbar.tsx +4 -3
- package/src/client/shell/app-bridge.ts +40 -5
- package/src/client/shell/canvas/Canvas.tsx +30 -8
- package/src/client/shell/canvas/FrameNode.tsx +3 -1
- package/src/client/shell/canvas/ctl.ts +16 -0
- package/src/client/shell/commands.ts +20 -0
- package/src/client/shell/comments-store.ts +81 -2
- package/src/client/shell/devices.tsx +42 -0
- package/src/client/shell/goto.ts +56 -9
- package/src/client/shell/icons.tsx +11 -4
- package/src/client/shell/immersive.ts +123 -0
- package/src/client/shell/inset.ts +29 -3
- package/src/client/shell/jam-lines.ts +5 -3
- package/src/client/shell/jam-panel.tsx +17 -5
- package/src/client/shell/marks-ui.tsx +54 -0
- package/src/client/shell/notes.ts +21 -0
- package/src/client/shell/pdf-export.tsx +154 -0
- package/src/client/shell/pdf-notes.ts +20 -0
- package/src/client/shell/recorder-signals.ts +5 -2
- package/src/client/shell/show.ts +250 -0
- package/src/client/shell/store.ts +23 -38
- package/src/client/shell/styles.css +68 -6
- package/src/shared/app-api.ts +90 -4
- package/src/shared/auto-place.ts +32 -0
- package/src/shared/board-tree.ts +3 -0
- package/src/shared/board-types.ts +6 -2
- package/src/shared/deep-link.ts +212 -0
- package/src/shared/devices.ts +89 -0
- package/src/shared/events.ts +48 -5
- package/src/shared/export-plan.ts +98 -0
- package/src/shared/immersive.ts +13 -0
- package/src/shared/perf-records.ts +1 -1
- package/templates/AGENTS-embedded.md +76 -12
- package/templates/AGENTS-studio.md +76 -12
- package/templates/instructions/boards.md +6 -5
- package/templates/instructions/configure.md +32 -2
- package/templates/instructions/iterate.md +8 -0
- package/templates/instructions/jam.md +9 -0
- package/templates/instructions/publish.md +14 -4
- package/templates/instructions/review.md +4 -0
- package/templates/instructions/slides.md +67 -1
- package/templates/instructions/welcome.md +9 -5
- package/templates/playbooks/publish-canvas/PLAYBOOK.md +1 -1
- package/dist/config-BezZTiov.mjs +0 -182
|
@@ -0,0 +1,2299 @@
|
|
|
1
|
+
import { a as ROUTE, o as slideSize } from "./cli.mjs";
|
|
2
|
+
import { s as checkRealDirs } from "./boards-Cim1GTKc.mjs";
|
|
3
|
+
import { n as BOARD_NAME } from "./board-tree-DGj0HhEE.mjs";
|
|
4
|
+
import { s as onPdfReset } from "./plugin-DesQP9L5.mjs";
|
|
5
|
+
import { c as pool, f as staleSurface, p as Browser } from "./shot-Bjt2MQe3.mjs";
|
|
6
|
+
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { join, sep } from "node:path";
|
|
8
|
+
import { randomBytes } from "node:crypto";
|
|
9
|
+
import { tmpdir } from "node:os";
|
|
10
|
+
import { execFile } from "node:child_process";
|
|
11
|
+
import { PDFDocument, PDFHexString, PDFName, PDFNumber, PDFString } from "pdf-lib";
|
|
12
|
+
//#region src/client/shell/play-order.ts
|
|
13
|
+
function deckOrder(nodes, frames) {
|
|
14
|
+
const rows = nodes.map((n, i) => ({
|
|
15
|
+
n,
|
|
16
|
+
i,
|
|
17
|
+
f: frames.get(n.frame)
|
|
18
|
+
})).filter(({ n, f }) => !n.missing && !!f);
|
|
19
|
+
const excluded = rows.filter(({ f }) => f.kind !== "tsx" || !f.slide).map(({ f }) => f.id);
|
|
20
|
+
const seen = /* @__PURE__ */ new Set();
|
|
21
|
+
return {
|
|
22
|
+
deck: rows.filter(({ f }) => f.kind === "tsx" && !!f.slide).sort((a, b) => a.n.y - b.n.y || a.n.x - b.n.x || a.i - b.i).filter(({ n }) => !seen.has(n.frame) && (seen.add(n.frame), true)).map(({ n }) => n.frame),
|
|
23
|
+
excluded: [...new Set(excluded)]
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/shared/export-plan.ts
|
|
28
|
+
/**
|
|
29
|
+
* The export plan (spec 31 Part A #2): which frames a board prints, in which order, at which size and theme. One
|
|
30
|
+
* definition, read by the PDF (src/server/pdf.ts) and by Play (src/client/shell/Play.tsx), so a deck's pages and the
|
|
31
|
+
* stage never disagree.
|
|
32
|
+
*
|
|
33
|
+
* - a *slides* board (it plays as slides: its publish policy says `type: slides` or `open: slides`) prints its deck:
|
|
34
|
+
* slide frames in reading order (y, then x), deduped - `deckOrder`, the order slides mode plays;
|
|
35
|
+
* - any other board prints its nodes in the board's own order (Play's order), deduped, html frames included (Play
|
|
36
|
+
* cannot mount them on its stage; the PDF prints them from their own document);
|
|
37
|
+
* - a page is the size the stage shows: a `slide: true` frame's stage (`slideSize`) on any board, else the device Play
|
|
38
|
+
* picks for the node - the viewport whose width is the node's, else the frame's declared viewport, else the first -
|
|
39
|
+
* at that viewport's height;
|
|
40
|
+
* - its theme: the export's own when one is asked, else the node's, else the frame's, else light;
|
|
41
|
+
* - a node whose frame the manifest does not list is skipped, and named.
|
|
42
|
+
*
|
|
43
|
+
* Pure and dependency-free (beyond the two shared rules it composes), so the server, the shell and the tests import it.
|
|
44
|
+
*/
|
|
45
|
+
/** The device Play shows a node at (spec 31 #2): the viewport whose width is the node's, else the frame's declared
|
|
46
|
+
* viewport, else the first. Undefined only when the project has no viewport at all. */
|
|
47
|
+
function presentDevice(node, frame, viewports) {
|
|
48
|
+
const names = Object.keys(viewports);
|
|
49
|
+
return (node?.w !== void 0 ? names.find((v) => viewports[v].width === node.w) : void 0) ?? (frame?.viewport && viewports[frame.viewport] ? frame.viewport : names[0]);
|
|
50
|
+
}
|
|
51
|
+
/** A board's frames in its own order, deduped, its missing ones skipped - Play's list (`html: false`, what its stage can
|
|
52
|
+
* mount) and the PDF's (`html: true`). */
|
|
53
|
+
function boardOrder(nodes, frameOf, o) {
|
|
54
|
+
const seen = /* @__PURE__ */ new Set();
|
|
55
|
+
const out = [];
|
|
56
|
+
for (const n of nodes) {
|
|
57
|
+
if (n.missing || seen.has(n.frame)) continue;
|
|
58
|
+
const f = frameOf(n);
|
|
59
|
+
if (!f || !o.html && f.kind !== "tsx") continue;
|
|
60
|
+
seen.add(n.frame);
|
|
61
|
+
out.push(n);
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
/** A frame's title, else its id's last part with spaces for dashes (as Play's pill names a frame). */
|
|
66
|
+
const titleOf = (f) => f.title?.trim() || (f.id.split("/").pop() ?? f.id).replace(/-/g, " ");
|
|
67
|
+
/** The plan for one board (spec 31 #2). `theme` is the export's own (`--theme`), when one was asked. */
|
|
68
|
+
function exportPlan(o) {
|
|
69
|
+
const byId = new Map(o.frames.map((f) => [f.id, f]));
|
|
70
|
+
const skipped = [];
|
|
71
|
+
const seenMissing = /* @__PURE__ */ new Set();
|
|
72
|
+
for (const n of o.nodes) if (!byId.has(n.frame) && !seenMissing.has(n.frame)) {
|
|
73
|
+
seenMissing.add(n.frame);
|
|
74
|
+
skipped.push({
|
|
75
|
+
frame: n.frame,
|
|
76
|
+
why: "missing"
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
const page = (f, node) => {
|
|
80
|
+
const theme = o.theme ?? node?.theme ?? f.theme ?? "light";
|
|
81
|
+
const sl = slideSize(f, o.viewports);
|
|
82
|
+
if (sl) return {
|
|
83
|
+
frame: f.id,
|
|
84
|
+
kind: f.kind,
|
|
85
|
+
width: sl.width,
|
|
86
|
+
height: sl.height,
|
|
87
|
+
theme,
|
|
88
|
+
title: titleOf(f)
|
|
89
|
+
};
|
|
90
|
+
const device = presentDevice(node, f, o.viewports);
|
|
91
|
+
const vp = device ? o.viewports[device] : void 0;
|
|
92
|
+
if (!vp) return null;
|
|
93
|
+
return {
|
|
94
|
+
frame: f.id,
|
|
95
|
+
kind: f.kind,
|
|
96
|
+
width: vp.width,
|
|
97
|
+
height: vp.height,
|
|
98
|
+
theme,
|
|
99
|
+
title: titleOf(f),
|
|
100
|
+
device
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
const pages = [];
|
|
104
|
+
if (o.slides) {
|
|
105
|
+
const { deck, excluded } = deckOrder(o.nodes.map((n) => ({
|
|
106
|
+
...n,
|
|
107
|
+
missing: n.missing || !byId.has(n.frame)
|
|
108
|
+
})), byId);
|
|
109
|
+
for (const id of excluded) skipped.push({
|
|
110
|
+
frame: id,
|
|
111
|
+
why: "not a slide"
|
|
112
|
+
});
|
|
113
|
+
for (const id of deck) {
|
|
114
|
+
const p = page(byId.get(id), o.nodes.find((n) => n.frame === id));
|
|
115
|
+
if (p) pages.push(p);
|
|
116
|
+
}
|
|
117
|
+
} else for (const n of boardOrder(o.nodes, (x) => byId.get(x.frame), { html: true })) {
|
|
118
|
+
const p = page(byId.get(n.frame), n);
|
|
119
|
+
if (p) pages.push(p);
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
pages,
|
|
123
|
+
skipped
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
//#endregion
|
|
127
|
+
//#region src/server/pdf-page.ts
|
|
128
|
+
/**
|
|
129
|
+
* The scripts deck PDFs run inside a slide's own document and in the job's helper tab (spec 31 Part A) - plain
|
|
130
|
+
* browser JavaScript, kept as functions here so they typecheck, and sent to Chrome by their source
|
|
131
|
+
* (`Function.prototype.toString`). Nothing in them may close over this module: each takes its inputs as arguments.
|
|
132
|
+
*
|
|
133
|
+
* In the slide (`__mvPdf`, installed once per document by `PDF_INSTALL`):
|
|
134
|
+
* - `freeze()` - the finished slide, deterministically (#4): a finite animation is given `fill: both` and finished, an
|
|
135
|
+
* infinite one paused at time 0 (its first pose), SVG SMIL paused, a video paused at its first frame;
|
|
136
|
+
* - `clipped(W, H)` - does the document reach past the stage (#3)?
|
|
137
|
+
* - `stage(W, H)` - the page geometry: `@page` at the stage size, the stage clipped, page breaks off, colours exact;
|
|
138
|
+
* - `detect(W, H)` - the effects Chrome cannot print, outermost first (#7), each stamped `data-mv-pdf`;
|
|
139
|
+
* - `links()` - every `https:`/`http:`/`mailto:` link's boxes, for a raster page's annotations;
|
|
140
|
+
* - `prepare(i)` / `restore()` - the state one patch's capture is taken in, and back;
|
|
141
|
+
* - `apply(patches)` - every certified-to-be capture put in place.
|
|
142
|
+
*
|
|
143
|
+
* In the helper tab (an about:blank page of the job's own browser, never a slide): `crop` (a capture's boxes out of one
|
|
144
|
+
* full screenshot) and `compare` (two pictures, inside boxes and outside them).
|
|
145
|
+
*/
|
|
146
|
+
/** Runs in the slide: installs `window.__mvPdf`. */
|
|
147
|
+
function install() {
|
|
148
|
+
const w = window;
|
|
149
|
+
if (w.__mvPdf) return true;
|
|
150
|
+
const touched = [];
|
|
151
|
+
const setStyle = (el, prop, value) => {
|
|
152
|
+
touched.push({
|
|
153
|
+
el,
|
|
154
|
+
prop,
|
|
155
|
+
value: el.style.getPropertyValue(prop),
|
|
156
|
+
prio: el.style.getPropertyPriority(prop)
|
|
157
|
+
});
|
|
158
|
+
el.style.setProperty(prop, value, "important");
|
|
159
|
+
};
|
|
160
|
+
const restoreStyles = () => {
|
|
161
|
+
for (let k = touched.length - 1; k >= 0; k--) {
|
|
162
|
+
const t = touched[k];
|
|
163
|
+
if (t.value) t.el.style.setProperty(t.prop, t.value, t.prio);
|
|
164
|
+
else t.el.style.removeProperty(t.prop);
|
|
165
|
+
}
|
|
166
|
+
touched.length = 0;
|
|
167
|
+
};
|
|
168
|
+
const hits = /* @__PURE__ */ new Map();
|
|
169
|
+
const shadowFix = /* @__PURE__ */ new Map();
|
|
170
|
+
const kinds = /* @__PURE__ */ new Map();
|
|
171
|
+
/** a filter list made only of drop-shadow()s (each may hold a colour function) */
|
|
172
|
+
const dropOnly = (f) => {
|
|
173
|
+
let depth = 0, names = [], cur = "";
|
|
174
|
+
for (const ch of f) if (ch === "(") {
|
|
175
|
+
if (depth === 0) names.push(cur.trim());
|
|
176
|
+
depth++;
|
|
177
|
+
cur = "";
|
|
178
|
+
} else if (ch === ")") depth--;
|
|
179
|
+
else if (depth === 0) cur += ch;
|
|
180
|
+
return names.length > 0 && names.every((n) => n === "drop-shadow");
|
|
181
|
+
};
|
|
182
|
+
const effectOf = (cs, dropShadowPrints) => {
|
|
183
|
+
const bf = cs.backdropFilter || cs.webkitBackdropFilter || "none";
|
|
184
|
+
const f = cs.filter || "none";
|
|
185
|
+
const bl = cs.mixBlendMode || "normal";
|
|
186
|
+
const mask = cs.maskImage || cs.webkitMaskImage || "none";
|
|
187
|
+
const whole = f !== "none" && !(dropShadowPrints && dropOnly(f)) ? `filter: ${f}` : bl !== "normal" ? `mix-blend-mode: ${bl}` : mask !== "none" ? "mask-image" : "";
|
|
188
|
+
return {
|
|
189
|
+
glass: bf !== "none",
|
|
190
|
+
whole
|
|
191
|
+
};
|
|
192
|
+
};
|
|
193
|
+
/** a transform that does not keep a box an upright box (a rotation, a skew, a flip, a perspective), on the element or
|
|
194
|
+
* any ancestor: a patch's capture would not map onto it. A move or a positive scale keeps it: the capture is the
|
|
195
|
+
* box's own border box, and the same transform takes both to the screen */
|
|
196
|
+
const transformed = (el) => {
|
|
197
|
+
for (let a = el; a && a !== document.documentElement; a = a.parentElement) {
|
|
198
|
+
const c = getComputedStyle(a);
|
|
199
|
+
if (c.transform && c.transform !== "none") {
|
|
200
|
+
const m = /^matrix\(([^)]+)\)$/.exec(c.transform);
|
|
201
|
+
if (!m) return true;
|
|
202
|
+
const v = m[1].split(",").map(Number);
|
|
203
|
+
if (!(v[0] > 0) || !(v[3] > 0) || Math.abs(v[1]) > 1e-6 || Math.abs(v[2]) > 1e-6) return true;
|
|
204
|
+
}
|
|
205
|
+
if (c.scale && c.scale !== "none" && c.scale.split(/\s+/).some((x) => !(parseFloat(x) > 0))) return true;
|
|
206
|
+
if (c.rotate && c.rotate !== "none" && !/^0(deg|rad|turn)?$/.test(c.rotate)) return true;
|
|
207
|
+
}
|
|
208
|
+
return false;
|
|
209
|
+
};
|
|
210
|
+
/** Large soft box-shadows print as solid grey boxes (Chrome's PDF backend, measured on the build): each blurred outer
|
|
211
|
+
* shadow is replaced by a stack of unblurred spread shadows that follows its Gaussian falloff - vector, and within a
|
|
212
|
+
* few levels of the blur on screen. Small ones print right and stay as they are. */
|
|
213
|
+
const SHADOW_AREA = 2e4;
|
|
214
|
+
const splitTop = (v) => {
|
|
215
|
+
const out = [];
|
|
216
|
+
let d = 0, cur = "";
|
|
217
|
+
for (const ch of v) {
|
|
218
|
+
if (ch === "(") d++;
|
|
219
|
+
if (ch === ")") d--;
|
|
220
|
+
if (ch === "," && d === 0) {
|
|
221
|
+
out.push(cur.trim());
|
|
222
|
+
cur = "";
|
|
223
|
+
} else cur += ch;
|
|
224
|
+
}
|
|
225
|
+
if (cur.trim()) out.push(cur.trim());
|
|
226
|
+
return out;
|
|
227
|
+
};
|
|
228
|
+
/** a CSS colour as sRGB bytes and an alpha, read back through a 1x1 canvas (gamut-mapped like the screen) */
|
|
229
|
+
let probe = null;
|
|
230
|
+
const srgb = (c) => {
|
|
231
|
+
try {
|
|
232
|
+
if (!probe) {
|
|
233
|
+
const cv = document.createElement("canvas");
|
|
234
|
+
cv.width = cv.height = 1;
|
|
235
|
+
probe = cv.getContext("2d", { willReadFrequently: true });
|
|
236
|
+
}
|
|
237
|
+
if (!probe) return null;
|
|
238
|
+
probe.clearRect(0, 0, 1, 1);
|
|
239
|
+
probe.fillStyle = "#000";
|
|
240
|
+
probe.fillStyle = c;
|
|
241
|
+
probe.fillRect(0, 0, 1, 1);
|
|
242
|
+
const d = probe.getImageData(0, 0, 1, 1).data;
|
|
243
|
+
return [
|
|
244
|
+
d[0],
|
|
245
|
+
d[1],
|
|
246
|
+
d[2],
|
|
247
|
+
d[3] / 255
|
|
248
|
+
];
|
|
249
|
+
} catch {
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
const erf = (x) => {
|
|
254
|
+
const t = 1 / (1 + .3275911 * Math.abs(x));
|
|
255
|
+
const y = 1 - ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - .284496736) * t + .254829592) * t * Math.exp(-x * x);
|
|
256
|
+
return x >= 0 ? y : -y;
|
|
257
|
+
};
|
|
258
|
+
const phi = (x) => .5 * (1 + erf(x / Math.SQRT2));
|
|
259
|
+
/** the element's box-shadow with each large blurred outer shadow stacked, and the extent it reaches; null when none needs it */
|
|
260
|
+
const stackShadows = (v, w, h) => {
|
|
261
|
+
if (!v || v === "none") return null;
|
|
262
|
+
let changed = false, reach = 0;
|
|
263
|
+
const parts = splitTop(v).map((part) => {
|
|
264
|
+
const m = /^(.+?)\s+(-?[\d.]+)px\s+(-?[\d.]+)px\s+([\d.]+)px\s+(-?[\d.]+)px$/.exec(part);
|
|
265
|
+
if (!m) return part;
|
|
266
|
+
const rgba = srgb(m[1]);
|
|
267
|
+
if (!rgba) return part;
|
|
268
|
+
const [r, g, b, a] = rgba;
|
|
269
|
+
const x = Number(m[2]), y = Number(m[3]), B = Number(m[4]), S = Number(m[5]);
|
|
270
|
+
if (!(B >= 2) || !(a > 0) || (w + 2 * (B + S)) * (h + 2 * (B + S)) < SHADOW_AREA) return part;
|
|
271
|
+
changed = true;
|
|
272
|
+
reach = Math.max(reach, Math.abs(x) + B + Math.max(0, S), Math.abs(y) + B + Math.max(0, S));
|
|
273
|
+
const sg = B / 2, N = 16, e = (k) => 2 * sg - k * (4 * sg / N);
|
|
274
|
+
const layers = [];
|
|
275
|
+
let prev = 0;
|
|
276
|
+
for (let k = 0; k <= N; k++) {
|
|
277
|
+
const A = k < N ? a * phi(-((e(k) + e(k + 1)) / 2) / sg) : a;
|
|
278
|
+
const ak = 1 - (1 - A) / (1 - prev);
|
|
279
|
+
prev = A;
|
|
280
|
+
if (ak > 5e-4) layers.push(`rgba(${r}, ${g}, ${b}, ${ak.toFixed(4)}) ${x}px ${y}px 0px ${(S + e(k)).toFixed(2)}px`);
|
|
281
|
+
}
|
|
282
|
+
return layers.join(", ");
|
|
283
|
+
});
|
|
284
|
+
return changed ? {
|
|
285
|
+
css: parts.join(", "),
|
|
286
|
+
reach
|
|
287
|
+
} : null;
|
|
288
|
+
};
|
|
289
|
+
/** the element's box as the stage shows it: in the viewport, inside every clipping ancestor; null when nothing shows */
|
|
290
|
+
/** the part of the stage an element can show in: the viewport, inside every clipping ancestor */
|
|
291
|
+
/** an ancestor that is the containing block of a fixed-position descendant (CSS Transforms, Filter Effects, Containment) */
|
|
292
|
+
const holdsFixed = (c) => !!(c.transform && c.transform !== "none" || c.perspective && c.perspective !== "none" || c.filter && c.filter !== "none" || (c.backdropFilter ?? "none") !== "none" || /paint|layout|strict|content/.test(c.contain || "") || /transform|perspective|filter/.test(c.willChange || "") || c.scale && c.scale !== "none" || c.rotate && c.rotate !== "none" || c.translate && c.translate !== "none");
|
|
293
|
+
/** which ancestors clip an element: those in its containing-block chain (CSS 2.2 11.1.1) - every ancestor of an
|
|
294
|
+
* in-flow box, only a positioned one (or one holding fixed descendants) for an absolute box, only one holding fixed
|
|
295
|
+
* descendants for a fixed box; each clipping ancestor then passes the question on by its own position */
|
|
296
|
+
const placeOf = (c) => c.position === "fixed" ? "fixed" : c.position === "absolute" ? "abs" : "flow";
|
|
297
|
+
const clipOf = (el, W, H) => {
|
|
298
|
+
let x0 = 0, y0 = 0, x1 = W, y1 = H;
|
|
299
|
+
let need = placeOf(getComputedStyle(el));
|
|
300
|
+
for (let a = el.parentElement; a && a !== document.body && a !== document.documentElement; a = a.parentElement) {
|
|
301
|
+
const c = getComputedStyle(a);
|
|
302
|
+
if (!(need === "flow" ? true : need === "abs" ? c.position !== "static" || holdsFixed(c) : holdsFixed(c))) continue;
|
|
303
|
+
if (c.overflowX !== "visible") {
|
|
304
|
+
const b = a.getBoundingClientRect();
|
|
305
|
+
x0 = Math.max(x0, b.left);
|
|
306
|
+
x1 = Math.min(x1, b.right);
|
|
307
|
+
}
|
|
308
|
+
if (c.overflowY !== "visible") {
|
|
309
|
+
const b = a.getBoundingClientRect();
|
|
310
|
+
y0 = Math.max(y0, b.top);
|
|
311
|
+
y1 = Math.min(y1, b.bottom);
|
|
312
|
+
}
|
|
313
|
+
need = placeOf(c);
|
|
314
|
+
}
|
|
315
|
+
return {
|
|
316
|
+
x0,
|
|
317
|
+
y0,
|
|
318
|
+
x1,
|
|
319
|
+
y1
|
|
320
|
+
};
|
|
321
|
+
};
|
|
322
|
+
const shown = (el, W, H) => {
|
|
323
|
+
const r = el.getBoundingClientRect();
|
|
324
|
+
if (r.width < 1 || r.height < 1) return null;
|
|
325
|
+
const ck = el.checkVisibility;
|
|
326
|
+
if (ck && !ck.call(el, {
|
|
327
|
+
opacityProperty: true,
|
|
328
|
+
visibilityProperty: false
|
|
329
|
+
})) return null;
|
|
330
|
+
const c = clipOf(el, W, H);
|
|
331
|
+
const x0 = Math.max(c.x0, r.left), y0 = Math.max(c.y0, r.top), x1 = Math.min(c.x1, r.right), y1 = Math.min(c.y1, r.bottom);
|
|
332
|
+
return x1 - x0 >= 1 && y1 - y0 >= 1 ? {
|
|
333
|
+
x: r.left,
|
|
334
|
+
y: r.top,
|
|
335
|
+
w: r.width,
|
|
336
|
+
h: r.height
|
|
337
|
+
} : null;
|
|
338
|
+
};
|
|
339
|
+
/** How far past its border box an element's effect draws (CSS px): a blur's falloff, a drop-shadow, its own outer
|
|
340
|
+
* box-shadow - a whole patch captures that much around it, and paints it back from an overlay that may reach as far */
|
|
341
|
+
const reachOf = (cs) => {
|
|
342
|
+
let e = 0;
|
|
343
|
+
const f = cs.filter || "";
|
|
344
|
+
for (const m of f.matchAll(/(^|[\s)])blur\(([\d.]+)px\)/g)) e = Math.max(e, 3 * parseFloat(m[2]));
|
|
345
|
+
for (const m of f.matchAll(/drop-shadow\(((?:[^()]|\([^()]*\))*)\)/g)) {
|
|
346
|
+
const n = [...m[1].matchAll(/(-?[\d.]+)px/g)].map((x) => parseFloat(x[1]));
|
|
347
|
+
e = Math.max(e, Math.max(Math.abs(n[0] || 0), Math.abs(n[1] || 0)) + 1.5 * (n[2] || 0));
|
|
348
|
+
}
|
|
349
|
+
if (cs.boxShadow && cs.boxShadow !== "none") for (const part of splitTop(cs.boxShadow)) {
|
|
350
|
+
if (/\binset\b/.test(part)) continue;
|
|
351
|
+
const n = [...part.matchAll(/(-?[\d.]+)px/g)].map((x) => parseFloat(x[1]));
|
|
352
|
+
e = Math.max(e, Math.max(Math.abs(n[0] || 0), Math.abs(n[1] || 0)) + (n[2] || 0) + Math.max(0, n[3] || 0));
|
|
353
|
+
}
|
|
354
|
+
return e > 0 ? Math.ceil(e) + 2 : 0;
|
|
355
|
+
};
|
|
356
|
+
/** per whole patch drawn by an overlay: how far its capture reaches past its border box on each side (CSS px, viewport) */
|
|
357
|
+
const reaches = /* @__PURE__ */ new Map();
|
|
358
|
+
/** every `https:`, `http:` or `mailto:` link under `root` with its boxes - an html `<a href>` or an svg `<a>` (whose
|
|
359
|
+
* href is an SVGAnimatedString, or an xlink:href), resolved against the document */
|
|
360
|
+
const linksUnder = (root) => {
|
|
361
|
+
const out = [];
|
|
362
|
+
const W = innerWidth, H = innerHeight;
|
|
363
|
+
for (const a of Array.from(root.querySelectorAll("a"))) {
|
|
364
|
+
const raw = a.getAttribute("href") ?? a.getAttributeNS("http://www.w3.org/1999/xlink", "href");
|
|
365
|
+
if (!raw) continue;
|
|
366
|
+
let href;
|
|
367
|
+
try {
|
|
368
|
+
href = new URL(raw, document.baseURI).href;
|
|
369
|
+
} catch {
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
if (!/^(https?:|mailto:)/i.test(href)) continue;
|
|
373
|
+
const ck = a.checkVisibility;
|
|
374
|
+
if (ck && !ck.call(a, {
|
|
375
|
+
opacityProperty: true,
|
|
376
|
+
visibilityProperty: true
|
|
377
|
+
})) continue;
|
|
378
|
+
const clip = clipOf(a, W, H);
|
|
379
|
+
const rects = [];
|
|
380
|
+
for (const r of Array.from(a.getClientRects())) {
|
|
381
|
+
const x0 = Math.max(r.left, clip.x0), y0 = Math.max(r.top, clip.y0), x1 = Math.min(r.right, clip.x1), y1 = Math.min(r.bottom, clip.y1);
|
|
382
|
+
if (x1 - x0 >= 1 && y1 - y0 >= 1) rects.push({
|
|
383
|
+
x: x0,
|
|
384
|
+
y: y0,
|
|
385
|
+
w: x1 - x0,
|
|
386
|
+
h: y1 - y0
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
if (rects.length) out.push({
|
|
390
|
+
href,
|
|
391
|
+
rects
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
return out;
|
|
395
|
+
};
|
|
396
|
+
const REPLACED = /* @__PURE__ */ new Set([
|
|
397
|
+
"IMG",
|
|
398
|
+
"CANVAS",
|
|
399
|
+
"VIDEO",
|
|
400
|
+
"IFRAME",
|
|
401
|
+
"OBJECT",
|
|
402
|
+
"EMBED",
|
|
403
|
+
"INPUT",
|
|
404
|
+
"SELECT",
|
|
405
|
+
"TEXTAREA",
|
|
406
|
+
"svg"
|
|
407
|
+
]);
|
|
408
|
+
w.__mvPdf = {
|
|
409
|
+
freeze() {
|
|
410
|
+
const out = {
|
|
411
|
+
finite: 0,
|
|
412
|
+
infinite: 0,
|
|
413
|
+
smil: 0,
|
|
414
|
+
video: 0
|
|
415
|
+
};
|
|
416
|
+
for (const a of document.getAnimations()) try {
|
|
417
|
+
const eff = a.effect;
|
|
418
|
+
const t = eff ? eff.getComputedTiming() : null;
|
|
419
|
+
if (t && t.iterations === Infinity) {
|
|
420
|
+
a.pause();
|
|
421
|
+
a.currentTime = 0;
|
|
422
|
+
out.infinite++;
|
|
423
|
+
} else {
|
|
424
|
+
if (eff) eff.updateTiming({ fill: "both" });
|
|
425
|
+
a.finish();
|
|
426
|
+
out.finite++;
|
|
427
|
+
}
|
|
428
|
+
} catch {
|
|
429
|
+
try {
|
|
430
|
+
a.pause();
|
|
431
|
+
} catch {}
|
|
432
|
+
}
|
|
433
|
+
for (const s of Array.from(document.querySelectorAll("svg"))) try {
|
|
434
|
+
if (s.animationsPaused && !s.animationsPaused()) {
|
|
435
|
+
s.pauseAnimations();
|
|
436
|
+
out.smil++;
|
|
437
|
+
}
|
|
438
|
+
} catch {}
|
|
439
|
+
for (const v of Array.from(document.querySelectorAll("video"))) try {
|
|
440
|
+
v.pause();
|
|
441
|
+
v.autoplay = false;
|
|
442
|
+
if (v.currentTime !== 0) v.currentTime = 0;
|
|
443
|
+
out.video++;
|
|
444
|
+
} catch {}
|
|
445
|
+
return out;
|
|
446
|
+
},
|
|
447
|
+
clipped(W, H) {
|
|
448
|
+
const d = document.documentElement, b = document.body;
|
|
449
|
+
return Math.max(d.scrollHeight, b ? b.scrollHeight : 0) > H + 1 || Math.max(d.scrollWidth, b ? b.scrollWidth : 0) > W + 1;
|
|
450
|
+
},
|
|
451
|
+
/** the page geometry, and nothing that lays the slide out again: `@page` at the stage size, every forced break off
|
|
452
|
+
* (content after one would leave page 1), colours exact. A document taller than its stage prints past page 1, which
|
|
453
|
+
* is dropped - the stage's own clip, without restyling html or body (which reflows a flex or grid body) */
|
|
454
|
+
stage(W, H) {
|
|
455
|
+
let st = document.getElementById("mv-pdf-stage");
|
|
456
|
+
if (!st) {
|
|
457
|
+
st = document.createElement("style");
|
|
458
|
+
st.id = "mv-pdf-stage";
|
|
459
|
+
document.head.appendChild(st);
|
|
460
|
+
}
|
|
461
|
+
st.textContent = `@page { size: ${W}px ${H}px; margin: 0 }
|
|
462
|
+
*, *::before, *::after { break-before: auto !important; break-after: auto !important; break-inside: auto !important;
|
|
463
|
+
page-break-before: auto !important; page-break-after: auto !important; page-break-inside: auto !important;
|
|
464
|
+
-webkit-print-color-adjust: exact !important; print-color-adjust: exact !important }`;
|
|
465
|
+
},
|
|
466
|
+
detect(W, H, dropShadowPrints) {
|
|
467
|
+
const out = [];
|
|
468
|
+
for (const el of Array.from(document.querySelectorAll("[data-mv-pdf]"))) el.removeAttribute("data-mv-pdf");
|
|
469
|
+
for (const el of Array.from(document.querySelectorAll("[data-mv-pdf-sh]"))) el.removeAttribute("data-mv-pdf-sh");
|
|
470
|
+
hits.clear();
|
|
471
|
+
shadowFix.clear();
|
|
472
|
+
reaches.clear();
|
|
473
|
+
const visit = (el) => {
|
|
474
|
+
for (const k of Array.from(el.children)) {
|
|
475
|
+
if (k.id === "mv-pdf-links") continue;
|
|
476
|
+
const cs = getComputedStyle(k);
|
|
477
|
+
if (cs.display === "none") continue;
|
|
478
|
+
const own = effectOf(cs, dropShadowPrints);
|
|
479
|
+
let whole = own.whole;
|
|
480
|
+
for (const ps of ["::before", "::after"]) {
|
|
481
|
+
const p = getComputedStyle(k, ps);
|
|
482
|
+
if (!p.content || p.content === "none" || p.content === "normal" || p.display === "none") continue;
|
|
483
|
+
const e = effectOf(p, dropShadowPrints);
|
|
484
|
+
if (e.whole || e.glass) {
|
|
485
|
+
whole = whole || `${ps} ${e.whole || "backdrop-filter"}`;
|
|
486
|
+
break;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
const media = k.tagName === "CANVAS" || k.tagName === "VIDEO" ? k.tagName.toLowerCase() : "";
|
|
490
|
+
let target = k;
|
|
491
|
+
let kind = whole || media ? "whole" : own.glass ? "glass" : null;
|
|
492
|
+
if (kind && k instanceof SVGElement && k.tagName !== "svg") {
|
|
493
|
+
let top = k;
|
|
494
|
+
for (let o = k.ownerSVGElement; o; o = o.ownerSVGElement) top = o;
|
|
495
|
+
target = top;
|
|
496
|
+
kind = "whole";
|
|
497
|
+
}
|
|
498
|
+
if (kind) {
|
|
499
|
+
const rect = shown(target, W, H);
|
|
500
|
+
if (rect) {
|
|
501
|
+
if (target.hasAttribute("data-mv-pdf")) continue;
|
|
502
|
+
const i = out.length;
|
|
503
|
+
target.setAttribute("data-mv-pdf", String(i));
|
|
504
|
+
hits.set(i, target);
|
|
505
|
+
let box = rect;
|
|
506
|
+
const tcs = getComputedStyle(target);
|
|
507
|
+
if (kind === "whole" && !REPLACED.has(target.tagName) && tcs.display !== "inline" && tcs.overflowX === "visible" && tcs.overflowY === "visible") {
|
|
508
|
+
const e = Math.max(reachOf(tcs), reachOf(getComputedStyle(target, "::before")), reachOf(getComputedStyle(target, "::after")));
|
|
509
|
+
const x0 = Math.max(0, rect.x - e), y0 = Math.max(0, rect.y - e), x1 = Math.min(W, rect.x + rect.w + e), y1 = Math.min(H, rect.y + rect.h + e);
|
|
510
|
+
reaches.set(i, {
|
|
511
|
+
l: rect.x - x0,
|
|
512
|
+
t: rect.y - y0,
|
|
513
|
+
r: x1 - rect.x - rect.w,
|
|
514
|
+
b: y1 - rect.y - rect.h
|
|
515
|
+
});
|
|
516
|
+
box = {
|
|
517
|
+
x: x0,
|
|
518
|
+
y: y0,
|
|
519
|
+
w: x1 - x0,
|
|
520
|
+
h: y1 - y0
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
out.push({
|
|
524
|
+
i,
|
|
525
|
+
kind,
|
|
526
|
+
why: whole || media || "backdrop-filter",
|
|
527
|
+
rect: box,
|
|
528
|
+
transformed: transformed(target),
|
|
529
|
+
replaced: REPLACED.has(target.tagName)
|
|
530
|
+
});
|
|
531
|
+
if (kind === "whole" || target !== k) continue;
|
|
532
|
+
} else if (kind === "whole") continue;
|
|
533
|
+
}
|
|
534
|
+
if (!(k instanceof SVGElement)) visit(k);
|
|
535
|
+
else visitSvg(k);
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
function visitSvg(el) {
|
|
539
|
+
for (const c of Array.from(el.children)) {
|
|
540
|
+
visitOne(c);
|
|
541
|
+
visitSvg(c);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
function visitOne(c) {
|
|
545
|
+
const e = effectOf(getComputedStyle(c), dropShadowPrints);
|
|
546
|
+
if (!e.whole && !e.glass) return;
|
|
547
|
+
let top = c;
|
|
548
|
+
for (let o = c.ownerSVGElement; o; o = o.ownerSVGElement) top = o;
|
|
549
|
+
if (top.hasAttribute("data-mv-pdf")) return;
|
|
550
|
+
const rect = shown(top, W, H);
|
|
551
|
+
if (!rect) return;
|
|
552
|
+
const i = out.length;
|
|
553
|
+
top.setAttribute("data-mv-pdf", String(i));
|
|
554
|
+
hits.set(i, top);
|
|
555
|
+
out.push({
|
|
556
|
+
i,
|
|
557
|
+
kind: "whole",
|
|
558
|
+
why: e.whole || "backdrop-filter",
|
|
559
|
+
rect,
|
|
560
|
+
transformed: transformed(top),
|
|
561
|
+
replaced: true
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
for (const r of [document.documentElement, document.body]) {
|
|
565
|
+
if (!r) continue;
|
|
566
|
+
for (const ps of [
|
|
567
|
+
"",
|
|
568
|
+
"::before",
|
|
569
|
+
"::after"
|
|
570
|
+
]) {
|
|
571
|
+
const c = getComputedStyle(r, ps || null);
|
|
572
|
+
if (ps && (!c.content || c.content === "none" || c.content === "normal")) continue;
|
|
573
|
+
const e = effectOf(c, dropShadowPrints);
|
|
574
|
+
if (e.whole || e.glass) {
|
|
575
|
+
out.push({
|
|
576
|
+
i: out.length,
|
|
577
|
+
kind: "root",
|
|
578
|
+
why: `${r === document.body ? "body" : "html"}${ps} ${e.whole || "backdrop-filter"}`,
|
|
579
|
+
rect: {
|
|
580
|
+
x: 0,
|
|
581
|
+
y: 0,
|
|
582
|
+
w: W,
|
|
583
|
+
h: H
|
|
584
|
+
},
|
|
585
|
+
transformed: false,
|
|
586
|
+
replaced: false
|
|
587
|
+
});
|
|
588
|
+
return out;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
if (document.body) visit(document.body);
|
|
593
|
+
const inWhole = (el) => out.some((h) => h.kind === "whole" && hits.get(h.i) !== el && hits.get(h.i).contains(el));
|
|
594
|
+
for (const el of document.body ? [document.body, ...Array.from(document.body.querySelectorAll("*"))] : []) {
|
|
595
|
+
if (el.id === "mv-pdf-links" || inWhole(el)) continue;
|
|
596
|
+
const r = el.getBoundingClientRect();
|
|
597
|
+
if (r.width < 1 || r.height < 1) continue;
|
|
598
|
+
const fixes = {};
|
|
599
|
+
let reach = 0;
|
|
600
|
+
for (const ps of [
|
|
601
|
+
"",
|
|
602
|
+
"::before",
|
|
603
|
+
"::after"
|
|
604
|
+
]) {
|
|
605
|
+
const c = getComputedStyle(el, ps || null);
|
|
606
|
+
if (ps && (!c.content || c.content === "none" || c.content === "normal")) continue;
|
|
607
|
+
const w = ps ? parseFloat(c.width) || r.width : r.width, h = ps ? parseFloat(c.height) || r.height : r.height;
|
|
608
|
+
const st = stackShadows(c.boxShadow, w, h);
|
|
609
|
+
if (st) {
|
|
610
|
+
fixes[ps || "self"] = st.css;
|
|
611
|
+
reach = Math.max(reach, st.reach);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
if (!Object.keys(fixes).length) continue;
|
|
615
|
+
const box = {
|
|
616
|
+
x: r.left - reach,
|
|
617
|
+
y: r.top - reach,
|
|
618
|
+
w: r.width + 2 * reach,
|
|
619
|
+
h: r.height + 2 * reach
|
|
620
|
+
};
|
|
621
|
+
if (box.x >= W || box.y >= H || box.x + box.w <= 0 || box.y + box.h <= 0) continue;
|
|
622
|
+
const i = out.length;
|
|
623
|
+
el.setAttribute("data-mv-pdf-sh", String(i));
|
|
624
|
+
hits.set(i, el);
|
|
625
|
+
shadowFix.set(i, fixes);
|
|
626
|
+
out.push({
|
|
627
|
+
i,
|
|
628
|
+
kind: "shadow",
|
|
629
|
+
why: "box-shadow",
|
|
630
|
+
rect: box,
|
|
631
|
+
transformed: transformed(el),
|
|
632
|
+
replaced: false
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
return out;
|
|
636
|
+
},
|
|
637
|
+
links() {
|
|
638
|
+
return linksUnder(document);
|
|
639
|
+
},
|
|
640
|
+
/** the state patch `i` is captured in: the elements drawn after it and over its box hidden, its ancestors at full
|
|
641
|
+
* opacity; a glass element also without its own content, border and shadow (they stay live) */
|
|
642
|
+
prepare(i) {
|
|
643
|
+
restoreStyles();
|
|
644
|
+
const el = hits.get(i);
|
|
645
|
+
if (!el) return null;
|
|
646
|
+
const r = el.getBoundingClientRect();
|
|
647
|
+
const reach = reaches.get(i);
|
|
648
|
+
const box = reach ? {
|
|
649
|
+
x: r.left - reach.l,
|
|
650
|
+
y: r.top - reach.t,
|
|
651
|
+
w: r.width + reach.l + reach.r,
|
|
652
|
+
h: r.height + reach.t + reach.b
|
|
653
|
+
} : {
|
|
654
|
+
x: r.left,
|
|
655
|
+
y: r.top,
|
|
656
|
+
w: r.width,
|
|
657
|
+
h: r.height
|
|
658
|
+
};
|
|
659
|
+
if (el.tagName === "IMG" && (kinds.get(i) ?? "") === "whole") {
|
|
660
|
+
const c = getComputedStyle(el);
|
|
661
|
+
const px = (v) => parseFloat(v) || 0;
|
|
662
|
+
const l = px(c.borderLeftWidth) + px(c.paddingLeft), t = px(c.borderTopWidth) + px(c.paddingTop);
|
|
663
|
+
const rr = px(c.borderRightWidth) + px(c.paddingRight), bb = px(c.borderBottomWidth) + px(c.paddingBottom);
|
|
664
|
+
const k = el.offsetWidth ? r.width / (el.offsetWidth || 1) : 1;
|
|
665
|
+
box.x += l * k;
|
|
666
|
+
box.y += t * k;
|
|
667
|
+
box.w -= (l + rr) * k;
|
|
668
|
+
box.h -= (t + bb) * k;
|
|
669
|
+
}
|
|
670
|
+
const over = (b) => b.left < box.x + box.w && box.x < b.right && b.top < box.y + box.h && box.y < b.bottom;
|
|
671
|
+
for (const o of Array.from(document.body.querySelectorAll("*"))) {
|
|
672
|
+
if (o === el || el.contains(o) || o.contains(el)) continue;
|
|
673
|
+
if (!(el.compareDocumentPosition(o) & Node.DOCUMENT_POSITION_FOLLOWING)) continue;
|
|
674
|
+
if (!(o instanceof HTMLElement || o instanceof SVGElement) || !over(o.getBoundingClientRect())) continue;
|
|
675
|
+
setStyle(o, "opacity", "0");
|
|
676
|
+
setStyle(o, "transition", "none");
|
|
677
|
+
}
|
|
678
|
+
for (let a = el.parentElement; a && a !== document.documentElement; a = a.parentElement) if (getComputedStyle(a).opacity !== "1") setStyle(a, "opacity", "1");
|
|
679
|
+
if (getComputedStyle(el).opacity !== "1") setStyle(el, "opacity", "1");
|
|
680
|
+
if ((kinds.get(i) ?? "") === "glass") {
|
|
681
|
+
for (const c of Array.from(el.children)) if (c instanceof HTMLElement || c instanceof SVGElement) {
|
|
682
|
+
setStyle(c, "opacity", "0");
|
|
683
|
+
setStyle(c, "transition", "none");
|
|
684
|
+
}
|
|
685
|
+
setStyle(el, "color", "transparent");
|
|
686
|
+
setStyle(el, "-webkit-text-fill-color", "transparent");
|
|
687
|
+
setStyle(el, "text-shadow", "none");
|
|
688
|
+
setStyle(el, "border-color", "transparent");
|
|
689
|
+
setStyle(el, "box-shadow", "none");
|
|
690
|
+
setStyle(el, "outline-color", "transparent");
|
|
691
|
+
let ps = document.getElementById("mv-pdf-cap");
|
|
692
|
+
if (!ps) {
|
|
693
|
+
ps = document.createElement("style");
|
|
694
|
+
ps.id = "mv-pdf-cap";
|
|
695
|
+
document.head.appendChild(ps);
|
|
696
|
+
}
|
|
697
|
+
ps.textContent = `[data-mv-pdf="${i}"]::before, [data-mv-pdf="${i}"]::after { opacity: 0 !important; transition: none !important }`;
|
|
698
|
+
}
|
|
699
|
+
return box;
|
|
700
|
+
},
|
|
701
|
+
restore() {
|
|
702
|
+
restoreStyles();
|
|
703
|
+
const ps = document.getElementById("mv-pdf-cap");
|
|
704
|
+
if (ps) ps.textContent = "";
|
|
705
|
+
},
|
|
706
|
+
mark(i, kind) {
|
|
707
|
+
kinds.set(i, kind);
|
|
708
|
+
},
|
|
709
|
+
/** every capture put in place; links inside a whole patch kept as transparent links over it */
|
|
710
|
+
apply(patches) {
|
|
711
|
+
const keep = (el, prop, value) => el.style.setProperty(prop, value, "important");
|
|
712
|
+
let rules = "";
|
|
713
|
+
let layer = document.getElementById("mv-pdf-links");
|
|
714
|
+
for (const p of patches) {
|
|
715
|
+
const el = hits.get(p.i);
|
|
716
|
+
if (!el) continue;
|
|
717
|
+
if (p.kind === "shadow") {
|
|
718
|
+
const fix = shadowFix.get(p.i) ?? {};
|
|
719
|
+
for (const [ps, css] of Object.entries(fix)) if (ps === "self") keep(el, "box-shadow", css);
|
|
720
|
+
else rules += `[data-mv-pdf-sh="${p.i}"]${ps} { box-shadow: ${css} !important }\n`;
|
|
721
|
+
continue;
|
|
722
|
+
}
|
|
723
|
+
const cs = getComputedStyle(el);
|
|
724
|
+
const bg = (e) => {
|
|
725
|
+
keep(e, "background-color", "transparent");
|
|
726
|
+
keep(e, "background-image", `url("${p.url}")`);
|
|
727
|
+
keep(e, "background-size", "100% 100%");
|
|
728
|
+
keep(e, "background-position", "0 0");
|
|
729
|
+
keep(e, "background-repeat", "no-repeat");
|
|
730
|
+
keep(e, "background-origin", "border-box");
|
|
731
|
+
keep(e, "background-clip", "border-box");
|
|
732
|
+
keep(e, "background-attachment", "scroll");
|
|
733
|
+
};
|
|
734
|
+
if (p.kind === "glass") {
|
|
735
|
+
keep(el, "backdrop-filter", "none");
|
|
736
|
+
keep(el, "-webkit-backdrop-filter", "none");
|
|
737
|
+
bg(el);
|
|
738
|
+
continue;
|
|
739
|
+
}
|
|
740
|
+
const r = el.getBoundingClientRect();
|
|
741
|
+
if (el.tagName === "IMG") {
|
|
742
|
+
const img = el;
|
|
743
|
+
keep(img, "width", cs.width);
|
|
744
|
+
keep(img, "height", cs.height);
|
|
745
|
+
if (img.parentElement?.tagName === "PICTURE") for (const so of Array.from(img.parentElement.querySelectorAll("source"))) so.remove();
|
|
746
|
+
img.removeAttribute("srcset");
|
|
747
|
+
img.removeAttribute("sizes");
|
|
748
|
+
img.loading = "eager";
|
|
749
|
+
img.src = p.url;
|
|
750
|
+
keep(img, "object-fit", "fill");
|
|
751
|
+
keep(img, "object-position", "0 0");
|
|
752
|
+
keep(img, "filter", "none");
|
|
753
|
+
keep(img, "mix-blend-mode", "normal");
|
|
754
|
+
keep(img, "box-shadow", "none");
|
|
755
|
+
keep(img, "mask", "none");
|
|
756
|
+
keep(img, "-webkit-mask", "none");
|
|
757
|
+
} else if (REPLACED.has(el.tagName)) {
|
|
758
|
+
const img = document.createElement("img");
|
|
759
|
+
const px = (v) => parseFloat(v) || 0;
|
|
760
|
+
const extra = cs.boxSizing === "border-box" ? [0, 0] : [px(cs.paddingLeft) + px(cs.paddingRight) + px(cs.borderLeftWidth) + px(cs.borderRightWidth), px(cs.paddingTop) + px(cs.paddingBottom) + px(cs.borderTopWidth) + px(cs.borderBottomWidth)];
|
|
761
|
+
const W = px(cs.width) + extra[0], H = px(cs.height) + extra[1];
|
|
762
|
+
const cls = el.getAttribute("class");
|
|
763
|
+
if (cls) img.setAttribute("class", cls);
|
|
764
|
+
const sty = el.getAttribute("style");
|
|
765
|
+
if (sty) img.setAttribute("style", sty);
|
|
766
|
+
img.setAttribute("data-mv-pdf", String(p.i));
|
|
767
|
+
img.alt = el.getAttribute("aria-label") ?? "";
|
|
768
|
+
img.src = p.url;
|
|
769
|
+
keep(img, "display", cs.display === "inline" ? "inline-block" : cs.display);
|
|
770
|
+
keep(img, "box-sizing", "border-box");
|
|
771
|
+
keep(img, "width", `${W || r.width}px`);
|
|
772
|
+
keep(img, "height", `${H || r.height}px`);
|
|
773
|
+
keep(img, "padding", "0");
|
|
774
|
+
keep(img, "border-width", "0");
|
|
775
|
+
keep(img, "object-fit", "fill");
|
|
776
|
+
keep(img, "object-position", "0 0");
|
|
777
|
+
keep(img, "filter", "none");
|
|
778
|
+
keep(img, "mix-blend-mode", "normal");
|
|
779
|
+
keep(img, "box-shadow", "none");
|
|
780
|
+
keep(img, "vertical-align", cs.verticalAlign);
|
|
781
|
+
keep(img, "mask", "none");
|
|
782
|
+
keep(img, "-webkit-mask", "none");
|
|
783
|
+
if (el.pause) try {
|
|
784
|
+
el.pause();
|
|
785
|
+
} catch {}
|
|
786
|
+
el.replaceWith(img);
|
|
787
|
+
hits.set(p.i, img);
|
|
788
|
+
} else {
|
|
789
|
+
keep(el, "filter", "none");
|
|
790
|
+
keep(el, "mix-blend-mode", "normal");
|
|
791
|
+
keep(el, "backdrop-filter", "none");
|
|
792
|
+
keep(el, "-webkit-backdrop-filter", "none");
|
|
793
|
+
keep(el, "mask", "none");
|
|
794
|
+
keep(el, "-webkit-mask", "none");
|
|
795
|
+
keep(el, "isolation", "isolate");
|
|
796
|
+
keep(el, "color", "transparent");
|
|
797
|
+
keep(el, "-webkit-text-fill-color", "transparent");
|
|
798
|
+
keep(el, "text-shadow", "none");
|
|
799
|
+
keep(el, "border-color", "transparent");
|
|
800
|
+
const reach = reaches.get(p.i);
|
|
801
|
+
rules += `[data-mv-pdf="${p.i}"] *, [data-mv-pdf="${p.i}"] *::before, [data-mv-pdf="${p.i}"] *::after, [data-mv-pdf="${p.i}"]::before${reach ? "" : `, [data-mv-pdf="${p.i}"]::after`} { visibility: hidden !important; opacity: 0 !important; filter: none !important; backdrop-filter: none !important; transition: none !important }\n`;
|
|
802
|
+
if (reach) {
|
|
803
|
+
const he = el;
|
|
804
|
+
const k = he.offsetWidth ? r.width / he.offsetWidth : 1;
|
|
805
|
+
const px = (v) => parseFloat(v) || 0;
|
|
806
|
+
if (cs.position === "static") keep(el, "position", "relative");
|
|
807
|
+
keep(el, "box-shadow", "none");
|
|
808
|
+
keep(el, "background", "none");
|
|
809
|
+
const L = -(px(cs.borderLeftWidth) + reach.l / k), T = -(px(cs.borderTopWidth) + reach.t / k);
|
|
810
|
+
const Wd = (r.width + reach.l + reach.r) / k, Hd = (r.height + reach.t + reach.b) / k;
|
|
811
|
+
rules += `[data-mv-pdf="${p.i}"]::after { content: "" !important; display: block !important; position: absolute !important; left: ${L}px !important; top: ${T}px !important; right: auto !important; bottom: auto !important; width: ${Wd}px !important; height: ${Hd}px !important; margin: 0 !important; padding: 0 !important; border: 0 !important; box-sizing: border-box !important; background: url("${p.url}") 0 0 / 100% 100% no-repeat !important; visibility: visible !important; opacity: 1 !important; filter: none !important; mix-blend-mode: normal !important; backdrop-filter: none !important; transform: none !important; clip-path: none !important; mask: none !important; -webkit-mask: none !important; box-shadow: none !important; z-index: auto !important; pointer-events: none !important; animation: none !important; transition: none !important }\n`;
|
|
812
|
+
} else {
|
|
813
|
+
if (/inset/.test(cs.boxShadow)) keep(el, "box-shadow", "none");
|
|
814
|
+
bg(el);
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
if (p.links.length) {
|
|
818
|
+
if (!layer) {
|
|
819
|
+
layer = document.createElement("div");
|
|
820
|
+
layer.id = "mv-pdf-links";
|
|
821
|
+
layer.setAttribute("style", "position:fixed;left:0;top:0;width:0;height:0;overflow:visible;z-index:2147483647;pointer-events:none");
|
|
822
|
+
document.body.appendChild(layer);
|
|
823
|
+
}
|
|
824
|
+
for (const l of p.links) for (const b of l.rects) {
|
|
825
|
+
const a = document.createElement("a");
|
|
826
|
+
a.href = l.href;
|
|
827
|
+
a.setAttribute("style", `position:absolute;display:block;left:${b.x}px;top:${b.y}px;width:${b.w}px;height:${b.h}px;pointer-events:auto`);
|
|
828
|
+
layer.appendChild(a);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
if (rules) {
|
|
833
|
+
const st = document.createElement("style");
|
|
834
|
+
st.id = "mv-pdf-patch";
|
|
835
|
+
st.textContent = rules;
|
|
836
|
+
document.head.appendChild(st);
|
|
837
|
+
}
|
|
838
|
+
return patches.length;
|
|
839
|
+
},
|
|
840
|
+
/** the links inside patch `i`, taken before it is applied */
|
|
841
|
+
linksIn(i) {
|
|
842
|
+
const el = hits.get(i);
|
|
843
|
+
return el ? linksUnder(el) : [];
|
|
844
|
+
}
|
|
845
|
+
};
|
|
846
|
+
return true;
|
|
847
|
+
}
|
|
848
|
+
const PDF_INSTALL = `(${install.toString()})()`;
|
|
849
|
+
/** Runs at document start, before the frame's own code (Page.addScriptToEvaluateOnNewDocument): every finite animation
|
|
850
|
+
* is given `fill: both` as it starts - CSS animations on `animationstart`, script ones through Element.animate - so one
|
|
851
|
+
* that ends before the slide is ready still holds its end pose when it is frozen (#4). */
|
|
852
|
+
function early() {
|
|
853
|
+
const keep = (a) => {
|
|
854
|
+
try {
|
|
855
|
+
const e = a.effect;
|
|
856
|
+
if (!e || e.getComputedTiming().iterations === Infinity) return;
|
|
857
|
+
const f = e.getTiming().fill;
|
|
858
|
+
if (f !== "both" && f !== "forwards") e.updateTiming({ fill: "both" });
|
|
859
|
+
} catch {}
|
|
860
|
+
};
|
|
861
|
+
const sweep = () => {
|
|
862
|
+
try {
|
|
863
|
+
for (const a of document.getAnimations()) keep(a);
|
|
864
|
+
} catch {}
|
|
865
|
+
};
|
|
866
|
+
addEventListener("animationstart", sweep, true);
|
|
867
|
+
addEventListener("transitionrun", sweep, true);
|
|
868
|
+
const animate = Element.prototype.animate;
|
|
869
|
+
Element.prototype.animate = function(...args) {
|
|
870
|
+
const a = animate.apply(this, args);
|
|
871
|
+
keep(a);
|
|
872
|
+
return a;
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
const PDF_EARLY = `(${early.toString()})()`;
|
|
876
|
+
/** Runs in the slide: settled when nothing it loads is still in flight (`marver shot`'s check, #6). */
|
|
877
|
+
const SETTLED = `(() => {
|
|
878
|
+
if (typeof window.__mvLodBusy === 'function' && window.__mvLodBusy() > 0) return false
|
|
879
|
+
if (typeof window.__mvPosterBusy === 'function' && window.__mvPosterBusy() > 0) return false
|
|
880
|
+
const H = window.innerHeight, W = window.innerWidth
|
|
881
|
+
for (const im of document.images) {
|
|
882
|
+
if (im.complete) continue
|
|
883
|
+
const r = im.getBoundingClientRect()
|
|
884
|
+
if (r.bottom < 0 || r.top > H || r.right < 0 || r.left > W) continue
|
|
885
|
+
return false
|
|
886
|
+
}
|
|
887
|
+
for (const c of document.querySelectorAll('.mv-chart')) if (!c.querySelector('svg, canvas')) return false
|
|
888
|
+
for (const d of document.querySelectorAll('.mv-diagram')) if (!d.querySelector('.mv-diagram-svg svg, .mv-diagram-err')) return false
|
|
889
|
+
return true
|
|
890
|
+
})()`;
|
|
891
|
+
/** Runs in the slide: every SVG `<image>` decoded (an export prints them; an undecoded one prints blank). */
|
|
892
|
+
const SVG_IMAGES = `Promise.race([Promise.all(Array.from(document.querySelectorAll('image')).map((el) => { const href = el.getAttribute('href') || el.getAttribute('xlink:href'); if (!href) return 1; const im = new Image(); im.src = new URL(href, location.href).href; return im.decode().catch(() => 1) })), new Promise((r) => setTimeout(r, 3000))]).then(() => true)`;
|
|
893
|
+
const TWO_FRAMES = "new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(true))))";
|
|
894
|
+
/** Runs in the helper tab: cut each box (CSS px) out of one screenshot taken at `dsf`, as PNG and JPEG data URLs (the
|
|
895
|
+
* caller keeps the smaller, preferring PNG). */
|
|
896
|
+
async function crop(shot, dsf, boxes) {
|
|
897
|
+
const im = new Image();
|
|
898
|
+
im.src = "data:image/png;base64," + shot;
|
|
899
|
+
await im.decode();
|
|
900
|
+
return boxes.map((b) => {
|
|
901
|
+
const sx = Math.max(0, Math.round(b.x * dsf)), sy = Math.max(0, Math.round(b.y * dsf));
|
|
902
|
+
const sw = Math.max(1, Math.min(im.width - sx, Math.round((b.x + b.w) * dsf) - sx)), sh = Math.max(1, Math.min(im.height - sy, Math.round((b.y + b.h) * dsf) - sy));
|
|
903
|
+
const c = document.createElement("canvas");
|
|
904
|
+
c.width = sw;
|
|
905
|
+
c.height = sh;
|
|
906
|
+
c.getContext("2d").drawImage(im, sx, sy, sw, sh, 0, 0, sw, sh);
|
|
907
|
+
return {
|
|
908
|
+
png: c.toDataURL("image/png"),
|
|
909
|
+
jpeg: c.toDataURL("image/jpeg", .92)
|
|
910
|
+
};
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
const CROP = crop.toString();
|
|
914
|
+
/**
|
|
915
|
+
* Runs in the helper tab: compare picture `b` with the reference `a` (both base64; `b` scaled to `a`'s size).
|
|
916
|
+
* - inside each box (CSS px at `dsf`): the share of pixels whose largest channel differs by more than `tol`;
|
|
917
|
+
* - outside every box: `marver`'s bake rule - changed pixels beyond 32 levels, and the worst 16x16 block;
|
|
918
|
+
* - `coarse`: the share of the page whose averages over 8 CSS px blocks differ by more than 32 levels - a missing or
|
|
919
|
+
* wrong area differs in its average (print certification);
|
|
920
|
+
* - `fine`: the share of pixels, of either picture, more than 48 levels from every pixel within one pixel of them in the
|
|
921
|
+
* other, and from every blend of two of those - text drawn by another rasteriser differs only at its edges (blends), a
|
|
922
|
+
* changed pattern everywhere.
|
|
923
|
+
*/
|
|
924
|
+
async function compare(a, b, dsf, boxes, tol, atB = false) {
|
|
925
|
+
const load = async (d) => {
|
|
926
|
+
const im = new Image();
|
|
927
|
+
im.src = "data:image/png;base64," + d;
|
|
928
|
+
await im.decode();
|
|
929
|
+
return im;
|
|
930
|
+
};
|
|
931
|
+
const [ia, ib] = await Promise.all([load(a), load(b)]);
|
|
932
|
+
const W = atB ? ib.width : ia.width, H = atB ? ib.height : ia.height;
|
|
933
|
+
dsf = atB ? dsf * (ib.width / ia.width) : dsf;
|
|
934
|
+
const px = (im) => {
|
|
935
|
+
const c = document.createElement("canvas");
|
|
936
|
+
c.width = W;
|
|
937
|
+
c.height = H;
|
|
938
|
+
const g = c.getContext("2d", { willReadFrequently: true });
|
|
939
|
+
g.imageSmoothingQuality = "high";
|
|
940
|
+
g.fillStyle = "#fff";
|
|
941
|
+
g.fillRect(0, 0, W, H);
|
|
942
|
+
g.drawImage(im, 0, 0, W, H);
|
|
943
|
+
return g.getImageData(0, 0, W, H).data;
|
|
944
|
+
};
|
|
945
|
+
const A = px(ia), B = px(ib);
|
|
946
|
+
const d = (p) => {
|
|
947
|
+
const i = p * 4;
|
|
948
|
+
return Math.max(Math.abs(A[i] - B[i]), Math.abs(A[i + 1] - B[i + 1]), Math.abs(A[i + 2] - B[i + 2]));
|
|
949
|
+
};
|
|
950
|
+
/** pixel (x, y) of P is not near Q within one pixel of it: neither within `t` levels of one of those pixels nor of a
|
|
951
|
+
* blend of two of them (the segment between them). A resampled or re-snapped edge is a blend of its neighbours; a
|
|
952
|
+
* line, a box, or a colour no two neighbours mix to (yellow among red and green) is not */
|
|
953
|
+
const near = new Array(27);
|
|
954
|
+
const unmatched = (P, Q, x, y, t) => {
|
|
955
|
+
const i = (y * W + x) * 4;
|
|
956
|
+
const pr = P[i], pg = P[i + 1], pb = P[i + 2];
|
|
957
|
+
let k = 0;
|
|
958
|
+
for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
|
|
959
|
+
const xx = x + dx, yy = y + dy;
|
|
960
|
+
if (xx < 0 || yy < 0 || xx >= W || yy >= H) continue;
|
|
961
|
+
const j = (yy * W + xx) * 4;
|
|
962
|
+
const r = Q[j], g = Q[j + 1], b = Q[j + 2];
|
|
963
|
+
if (Math.max(Math.abs(pr - r), Math.abs(pg - g), Math.abs(pb - b)) <= t) return false;
|
|
964
|
+
near[k * 3] = r;
|
|
965
|
+
near[k * 3 + 1] = g;
|
|
966
|
+
near[k * 3 + 2] = b;
|
|
967
|
+
k++;
|
|
968
|
+
}
|
|
969
|
+
for (let a = 0; a < k; a++) for (let c = a + 1; c < k; c++) {
|
|
970
|
+
const ar = near[a * 3], ag = near[a * 3 + 1], ab = near[a * 3 + 2];
|
|
971
|
+
const vr = near[c * 3] - ar, vg = near[c * 3 + 1] - ag, vb = near[c * 3 + 2] - ab;
|
|
972
|
+
const len = vr * vr + vg * vg + vb * vb;
|
|
973
|
+
if (!len) continue;
|
|
974
|
+
const u = Math.max(0, Math.min(1, ((pr - ar) * vr + (pg - ag) * vg + (pb - ab) * vb) / len));
|
|
975
|
+
if (Math.max(Math.abs(pr - (ar + u * vr)), Math.abs(pg - (ag + u * vg)), Math.abs(pb - (ab + u * vb))) <= t) return false;
|
|
976
|
+
}
|
|
977
|
+
return true;
|
|
978
|
+
};
|
|
979
|
+
const owned = new Uint8Array(W * H);
|
|
980
|
+
const inBoxes = boxes.map((bx) => {
|
|
981
|
+
const x0 = Math.max(0, Math.floor(bx.x * dsf)), y0 = Math.max(0, Math.floor(bx.y * dsf));
|
|
982
|
+
const x1 = Math.min(W, Math.ceil((bx.x + bx.w) * dsf)), y1 = Math.min(H, Math.ceil((bx.y + bx.h) * dsf));
|
|
983
|
+
let bad = 0, n = 0;
|
|
984
|
+
for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) {
|
|
985
|
+
const p = y * W + x;
|
|
986
|
+
owned[p] = 1;
|
|
987
|
+
n++;
|
|
988
|
+
if (d(p) > tol && (unmatched(A, B, x, y, tol) || unmatched(B, A, x, y, tol))) bad++;
|
|
989
|
+
}
|
|
990
|
+
return n ? bad / n : 0;
|
|
991
|
+
});
|
|
992
|
+
const cols = Math.ceil(W / 16), blocks = new Uint16Array(cols * Math.ceil(H / 16));
|
|
993
|
+
let gt32 = 0, n = 0, blockMax = 0;
|
|
994
|
+
for (let p = 0; p < W * H; p++) {
|
|
995
|
+
if (owned[p]) continue;
|
|
996
|
+
n++;
|
|
997
|
+
if (d(p) > 32) {
|
|
998
|
+
gt32++;
|
|
999
|
+
const k = Math.floor(p / W / 16) * cols + Math.floor(p % W / 16);
|
|
1000
|
+
if (++blocks[k] > blockMax) blockMax = blocks[k];
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
const K = Math.max(2, Math.round(8 * dsf)), cw = Math.floor(W / K), ch = Math.floor(H / K);
|
|
1004
|
+
let coarseBad = 0;
|
|
1005
|
+
for (let cy = 0; cy < ch; cy++) for (let cx = 0; cx < cw; cx++) {
|
|
1006
|
+
let ra = 0, ga = 0, ba = 0, rb = 0, gb = 0, bb = 0;
|
|
1007
|
+
for (let y = cy * K; y < cy * K + K; y++) for (let x = cx * K; x < cx * K + K; x++) {
|
|
1008
|
+
const i = (y * W + x) * 4;
|
|
1009
|
+
ra += A[i];
|
|
1010
|
+
ga += A[i + 1];
|
|
1011
|
+
ba += A[i + 2];
|
|
1012
|
+
rb += B[i];
|
|
1013
|
+
gb += B[i + 1];
|
|
1014
|
+
bb += B[i + 2];
|
|
1015
|
+
}
|
|
1016
|
+
const k2 = K * K;
|
|
1017
|
+
if (Math.max(Math.abs(ra - rb), Math.abs(ga - gb), Math.abs(ba - bb)) / k2 > 32) coarseBad++;
|
|
1018
|
+
}
|
|
1019
|
+
let fineBad = 0;
|
|
1020
|
+
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
|
|
1021
|
+
if (d(y * W + x) <= 48) continue;
|
|
1022
|
+
if (unmatched(A, B, x, y, 48) || unmatched(B, A, x, y, 48)) fineBad++;
|
|
1023
|
+
}
|
|
1024
|
+
return {
|
|
1025
|
+
boxes: inBoxes,
|
|
1026
|
+
outside: {
|
|
1027
|
+
gt32,
|
|
1028
|
+
n,
|
|
1029
|
+
blockMax
|
|
1030
|
+
},
|
|
1031
|
+
coarse: cw * ch ? coarseBad / (cw * ch) : 0,
|
|
1032
|
+
fine: fineBad / (W * H)
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
const COMPARE = compare.toString();
|
|
1036
|
+
/** Runs in the helper tab: a PNG re-encoded as JPEG (a raster page, a handout picture), optionally scaled. */
|
|
1037
|
+
async function toJpeg(png, quality, scale) {
|
|
1038
|
+
const im = new Image();
|
|
1039
|
+
im.src = "data:image/png;base64," + png;
|
|
1040
|
+
await im.decode();
|
|
1041
|
+
const c = document.createElement("canvas");
|
|
1042
|
+
c.width = Math.max(1, Math.round(im.width * scale));
|
|
1043
|
+
c.height = Math.max(1, Math.round(im.height * scale));
|
|
1044
|
+
const g = c.getContext("2d");
|
|
1045
|
+
g.imageSmoothingQuality = "high";
|
|
1046
|
+
g.drawImage(im, 0, 0, c.width, c.height);
|
|
1047
|
+
return c.toDataURL("image/jpeg", quality).slice(23);
|
|
1048
|
+
}
|
|
1049
|
+
const TO_JPEG = toJpeg.toString();
|
|
1050
|
+
//#endregion
|
|
1051
|
+
//#region src/shared/auto-place.ts
|
|
1052
|
+
/** Append a node for every frame in `frames` not on `nodes` yet, in `frames`' order. Mutates and returns `nodes`. */
|
|
1053
|
+
function placeNewcomers(nodes, frames, size, make) {
|
|
1054
|
+
const placed = new Set(nodes.map((n) => n.frame));
|
|
1055
|
+
const groupOf = new Map(frames.map((f) => [f.id, f.variantGroup]));
|
|
1056
|
+
let maxX = nodes.reduce((a, n) => Math.max(a, n.x + n.w), 0);
|
|
1057
|
+
for (const f of frames) {
|
|
1058
|
+
if (placed.has(f.id)) continue;
|
|
1059
|
+
placed.add(f.id);
|
|
1060
|
+
const { w, h } = size(f);
|
|
1061
|
+
const sibling = f.variantGroup ? nodes.filter((n) => groupOf.get(n.frame) === f.variantGroup).reduce((a, n) => !a || n.x + n.w > a.x + a.w ? n : a, null) : null;
|
|
1062
|
+
const x = sibling ? sibling.x + sibling.w + Math.max(140, sibling.w * .12) : nodes.length ? maxX + 96 : 0;
|
|
1063
|
+
const y = sibling ? sibling.y : 0;
|
|
1064
|
+
nodes.push(make(f, x, y, w, h));
|
|
1065
|
+
maxX = Math.max(maxX, x + w);
|
|
1066
|
+
}
|
|
1067
|
+
return nodes;
|
|
1068
|
+
}
|
|
1069
|
+
//#endregion
|
|
1070
|
+
//#region src/server/pdf.ts
|
|
1071
|
+
/**
|
|
1072
|
+
* Deck PDFs (spec 31 Part A) - a board printed by the system's own Chrome, one page per slide, exactly what the stage
|
|
1073
|
+
* shows, vector where Chrome can print it and certified where it cannot.
|
|
1074
|
+
*
|
|
1075
|
+
* One job per canvas, one Chrome per job (cdp.ts), four slides at a time. Each slide:
|
|
1076
|
+
* 1. renders in a tab of its own, its window sized to the capture (a screenshot of exactly the native view never comes
|
|
1077
|
+
* back tiled - shot.ts #14), at the page size, screen media, without `data-sl-play` (entrances show their end);
|
|
1078
|
+
* 2. is ready when `marver shot` calls a frame ready (root children, fonts, images, charts and diagrams, two frames),
|
|
1079
|
+
* 10 s at most - past that it prints anyway and is named "unsettled";
|
|
1080
|
+
* 3. is frozen deterministically (finite animations finished with `fill: both`, infinite ones paused at time 0, SMIL
|
|
1081
|
+
* paused, videos at their first frame), then staged: `@page` at the stage size, the stage clipped, breaks off;
|
|
1082
|
+
* 4. has its effects patched element by element - the glass a backdrop-filter draws becomes the element's own
|
|
1083
|
+
* background, a filtered or blended box, a canvas or a video becomes a picture of itself - and the patched page is
|
|
1084
|
+
* certified against the unpatched screenshot; a wrong patch makes the whole page a 3x raster;
|
|
1085
|
+
* 5. is printed to a one-page PDF, which must be one page ("spilled" otherwise, page 1 kept), and, where macOS `sips`
|
|
1086
|
+
* can rasterise it, certified again against the screenshot - a print-only failure makes it a raster too.
|
|
1087
|
+
* Then the pages are merged in plan order with pdf-lib, a bookmark per page, the metadata set, written whole.
|
|
1088
|
+
*
|
|
1089
|
+
* `--notes` prints a handout instead: one document (`/__mv/handout/?job=`), each slide's picture, its title and its
|
|
1090
|
+
* notes, paginated by Chrome on Letter or A4 landscape.
|
|
1091
|
+
*
|
|
1092
|
+
* Not promised (said in docs/pdf.md): a tagged PDF (pdf-lib copies pages, not Chrome's structure tree) and links
|
|
1093
|
+
* between slides.
|
|
1094
|
+
*/
|
|
1095
|
+
/** Budgets (spec 31 How): refused with a message, never silently. */
|
|
1096
|
+
const PDF_BUDGET = {
|
|
1097
|
+
side: 4096,
|
|
1098
|
+
pages: 300,
|
|
1099
|
+
ms: 9e5,
|
|
1100
|
+
bytes: 500 * 2 ** 20,
|
|
1101
|
+
slideMs: 1e4,
|
|
1102
|
+
keepMs: 36e5
|
|
1103
|
+
};
|
|
1104
|
+
/** A job id: 128 random bits, base64url. */
|
|
1105
|
+
const JOB_ID = /^[A-Za-z0-9_-]{22}$/;
|
|
1106
|
+
/** The share of a patch box allowed to differ (screen certification); of the page in 8 CSS px blocks, and pixel by pixel
|
|
1107
|
+
* within one pixel (print certification). Measured on the five real decks' good pages: at most 0.06 % and 0.19 %. */
|
|
1108
|
+
const CERTIFY = {
|
|
1109
|
+
box: .01,
|
|
1110
|
+
tol: 24,
|
|
1111
|
+
page: .0025,
|
|
1112
|
+
fine: .01
|
|
1113
|
+
};
|
|
1114
|
+
/** Does the board play as slides? Its publish policy says `type: slides` or `open: slides` (Play's rule). */
|
|
1115
|
+
function playsAsSlides(root, board) {
|
|
1116
|
+
try {
|
|
1117
|
+
const p = JSON.parse(readFileSync(join(root, "design", "publish.json"), "utf8"))?.boards?.[board];
|
|
1118
|
+
return !!p && typeof p === "object" && (p.type === "slides" || p.open === "slides");
|
|
1119
|
+
} catch {
|
|
1120
|
+
return false;
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
/** The board file's nodes with the positions the canvas would give them: its own, else its layout's (a board an agent
|
|
1124
|
+
* wrote as a frame list is laid out by the canvas when it opens - the same pure layout). */
|
|
1125
|
+
async function boardNodes(root, board, frames, viewports, themes, scenes = []) {
|
|
1126
|
+
if (!BOARD_NAME.test(board) || board.length > 64) return null;
|
|
1127
|
+
const { checkBoardsDir, isRegularFile } = await import("./boards-Cim1GTKc.mjs").then((n) => n.a);
|
|
1128
|
+
const dir = join(root, "design", "boards"), file = join(dir, `${board}.json`);
|
|
1129
|
+
if (checkBoardsDir(root, dir) || !isRegularFile(file)) return null;
|
|
1130
|
+
let b;
|
|
1131
|
+
try {
|
|
1132
|
+
b = JSON.parse(readFileSync(file, "utf8"));
|
|
1133
|
+
} catch {
|
|
1134
|
+
return null;
|
|
1135
|
+
}
|
|
1136
|
+
if (!b || typeof b !== "object") return null;
|
|
1137
|
+
const byId = new Map(frames.map((f) => [f.id, f]));
|
|
1138
|
+
const auto = b.auto === true;
|
|
1139
|
+
const num = (v) => typeof v === "number" && Number.isFinite(v);
|
|
1140
|
+
const saved = (Array.isArray(b.nodes) ? b.nodes : []).filter((n) => !!n && typeof n.frame === "string");
|
|
1141
|
+
const needTidy = saved.some((n) => !num(n.x) || !num(n.y));
|
|
1142
|
+
const raw = auto ? saved.filter((n) => byId.has(n.frame)) : saved;
|
|
1143
|
+
const first = themes[0] ?? "light";
|
|
1144
|
+
const themeOf = (n) => {
|
|
1145
|
+
if (typeof n.themeUser === "string" && themes.includes(n.themeUser)) return n.themeUser;
|
|
1146
|
+
const f = byId.get(n.frame);
|
|
1147
|
+
return typeof n.theme === "string" && themes.includes(n.theme) && n.theme !== (f?.theme ?? first) ? n.theme : void 0;
|
|
1148
|
+
};
|
|
1149
|
+
const { autoWidthOf, keptSizes, measuringFrames, readSizes } = await import("./sizes-BckcL4Zz.mjs").then((n) => n.u);
|
|
1150
|
+
const heights = keptSizes(readSizes(root), autoWidthOf(frames, viewports), measuringFrames(root, frames));
|
|
1151
|
+
const def = (f) => {
|
|
1152
|
+
if (!f) return {
|
|
1153
|
+
w: 390,
|
|
1154
|
+
h: 844
|
|
1155
|
+
};
|
|
1156
|
+
const sl = slideSize(f, viewports);
|
|
1157
|
+
if (sl) return {
|
|
1158
|
+
w: sl.width,
|
|
1159
|
+
h: sl.height
|
|
1160
|
+
};
|
|
1161
|
+
if (f.contentWidth) {
|
|
1162
|
+
const vp = viewports[f.viewport ?? ""];
|
|
1163
|
+
const w = vp?.width ?? f.contentWidth;
|
|
1164
|
+
return {
|
|
1165
|
+
w,
|
|
1166
|
+
h: heights[`${f.id}@${w}`] ?? vp?.height ?? Math.round(w * .75)
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
const vp = viewports[f.viewport ?? ""] ?? viewports.mobile ?? {
|
|
1170
|
+
width: 390,
|
|
1171
|
+
height: 844
|
|
1172
|
+
};
|
|
1173
|
+
return {
|
|
1174
|
+
w: vp.width,
|
|
1175
|
+
h: vp.height
|
|
1176
|
+
};
|
|
1177
|
+
};
|
|
1178
|
+
const size = (n) => {
|
|
1179
|
+
const f = byId.get(n.frame);
|
|
1180
|
+
const d = def(f);
|
|
1181
|
+
const own = !!f?.contentWidth && n.sizeMode !== "manual" && n.sizeMode !== "device" && heights[`${f.id}@${d.w}`] !== void 0;
|
|
1182
|
+
return {
|
|
1183
|
+
w: !own && num(n.w) ? n.w : d.w,
|
|
1184
|
+
h: !own && num(n.h) ? n.h : d.h
|
|
1185
|
+
};
|
|
1186
|
+
};
|
|
1187
|
+
const nodes = raw.map((n) => ({
|
|
1188
|
+
frame: n.frame,
|
|
1189
|
+
x: num(n.x) ? n.x : 0,
|
|
1190
|
+
y: num(n.y) ? n.y : 0,
|
|
1191
|
+
w: size(n).w,
|
|
1192
|
+
...themeOf(n) ? { theme: themeOf(n) } : {},
|
|
1193
|
+
...byId.has(n.frame) ? {} : { missing: true }
|
|
1194
|
+
}));
|
|
1195
|
+
if (auto) {
|
|
1196
|
+
const dv = typeof b.deviceView === "string" ? viewports[b.deviceView] : void 0;
|
|
1197
|
+
placeNewcomers(nodes, frames, (f) => {
|
|
1198
|
+
const d = def(f);
|
|
1199
|
+
return {
|
|
1200
|
+
w: dv?.width ?? d.w,
|
|
1201
|
+
h: dv?.height ?? d.h
|
|
1202
|
+
};
|
|
1203
|
+
}, (f, x, y, w, h) => {
|
|
1204
|
+
raw.push({
|
|
1205
|
+
frame: f.id,
|
|
1206
|
+
w,
|
|
1207
|
+
h,
|
|
1208
|
+
sizeMode: dv ? "device" : "auto"
|
|
1209
|
+
});
|
|
1210
|
+
return {
|
|
1211
|
+
frame: f.id,
|
|
1212
|
+
x,
|
|
1213
|
+
y,
|
|
1214
|
+
w
|
|
1215
|
+
};
|
|
1216
|
+
});
|
|
1217
|
+
}
|
|
1218
|
+
const { boardLayoutOf } = await import("./boards-Cim1GTKc.mjs").then((n) => n.a);
|
|
1219
|
+
const { notesCramped, tidyNodes } = await import("./notes-CRAX4wgk.mjs");
|
|
1220
|
+
const { composed, flow } = boardLayoutOf(b);
|
|
1221
|
+
const manifest = {
|
|
1222
|
+
frames: frames.map((f) => ({
|
|
1223
|
+
...f,
|
|
1224
|
+
scene: f.scene ?? f.id.split("/")[0]
|
|
1225
|
+
})),
|
|
1226
|
+
scenes: [...scenes]
|
|
1227
|
+
};
|
|
1228
|
+
const keyed = nodes.map((n, i) => ({
|
|
1229
|
+
key: String(i),
|
|
1230
|
+
frame: n.frame,
|
|
1231
|
+
x: n.x,
|
|
1232
|
+
y: n.y,
|
|
1233
|
+
...size(raw[i]),
|
|
1234
|
+
...n.missing ? { missing: true } : {}
|
|
1235
|
+
}));
|
|
1236
|
+
const cramped = !needTidy && composed && notesCramped(keyed, manifest, () => 0);
|
|
1237
|
+
if ((needTidy || cramped) && nodes.length) {
|
|
1238
|
+
const { tidy } = await import("./boards-Cim1GTKc.mjs").then((n) => n.b);
|
|
1239
|
+
const placed = tidy(tidyNodes(keyed, manifest, () => 0), flow, () => {}, new Set(scenes.map((sc) => sc.name)));
|
|
1240
|
+
for (const p of placed) {
|
|
1241
|
+
const n = nodes[Number(p.key)];
|
|
1242
|
+
if (n) {
|
|
1243
|
+
n.x = p.x;
|
|
1244
|
+
n.y = p.y;
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
const title = typeof b.title === "string" && b.title.trim() ? b.title.trim().slice(0, 200) : void 0;
|
|
1249
|
+
return {
|
|
1250
|
+
nodes,
|
|
1251
|
+
...title ? { title } : {}
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
/** The board's plan with its budgets checked: 404 for a board that is not there, 400 for one that cannot print. */
|
|
1255
|
+
async function planFor(ctx, board, theme) {
|
|
1256
|
+
const frames = ctx.frames();
|
|
1257
|
+
const b = await boardNodes(ctx.root, board, frames, ctx.viewports, ctx.themes, ctx.scenes?.() ?? []);
|
|
1258
|
+
if (!b) return {
|
|
1259
|
+
ok: false,
|
|
1260
|
+
status: 404,
|
|
1261
|
+
error: `no board "${board}" - boards are in design/boards/`
|
|
1262
|
+
};
|
|
1263
|
+
const plan = exportPlan({
|
|
1264
|
+
slides: playsAsSlides(ctx.root, board),
|
|
1265
|
+
nodes: b.nodes,
|
|
1266
|
+
frames,
|
|
1267
|
+
viewports: ctx.viewports,
|
|
1268
|
+
theme
|
|
1269
|
+
});
|
|
1270
|
+
if (!plan.pages.length) return {
|
|
1271
|
+
ok: false,
|
|
1272
|
+
status: 400,
|
|
1273
|
+
error: `nothing to print on "${board}"${plan.skipped.length ? ` (${plan.skipped.length} frame(s) skipped: ${plan.skipped.slice(0, 3).map((s) => `${s.frame} - ${s.why}`).join(", ")})` : ""}`
|
|
1274
|
+
};
|
|
1275
|
+
if (plan.pages.length > PDF_BUDGET.pages) return {
|
|
1276
|
+
ok: false,
|
|
1277
|
+
status: 400,
|
|
1278
|
+
error: `"${board}" has ${plan.pages.length} pages - a PDF takes ${PDF_BUDGET.pages} at most`
|
|
1279
|
+
};
|
|
1280
|
+
const big = plan.pages.find((p) => p.width > PDF_BUDGET.side || p.height > PDF_BUDGET.side);
|
|
1281
|
+
if (big) return {
|
|
1282
|
+
ok: false,
|
|
1283
|
+
status: 400,
|
|
1284
|
+
error: `${big.frame} is ${big.width}x${big.height} - a page side is ${PDF_BUDGET.side} CSS px at most`
|
|
1285
|
+
};
|
|
1286
|
+
return {
|
|
1287
|
+
ok: true,
|
|
1288
|
+
plan,
|
|
1289
|
+
title: b.title ?? board.replace(/-/g, " ")
|
|
1290
|
+
};
|
|
1291
|
+
}
|
|
1292
|
+
/** Device pixels per CSS px for a page's captures: 3x, lowered (in quarter steps) so one capture stays under 16 MP. */
|
|
1293
|
+
const captureScale = (w, h) => Math.max(1, Math.min(3, Math.floor(Math.sqrt(16e6 / (w * h)) * 4) / 4));
|
|
1294
|
+
/** The URL a page renders at: the frame host (or an html frame's own file) with `export=1` - images at full resolution. */
|
|
1295
|
+
const exportUrl = (origin, page, file) => page.kind === "html" && file ? `${origin}/${file.split("/").map(encodeURIComponent).join("/")}?theme=${encodeURIComponent(page.theme)}&export=1` : `${origin}${ROUTE}/frame/?id=${encodeURIComponent(page.frame)}&theme=${encodeURIComponent(page.theme)}&export=1`;
|
|
1296
|
+
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1297
|
+
/** The job's helper tab: an about:blank page that crops and compares pictures (never a slide's document). */
|
|
1298
|
+
var Helper = class Helper {
|
|
1299
|
+
b;
|
|
1300
|
+
sid;
|
|
1301
|
+
owner;
|
|
1302
|
+
constructor(b, sid, owner) {
|
|
1303
|
+
this.b = b;
|
|
1304
|
+
this.sid = sid;
|
|
1305
|
+
this.owner = owner;
|
|
1306
|
+
}
|
|
1307
|
+
static async open(b, owner) {
|
|
1308
|
+
const { targetId } = await b.send("Target.createTarget", { url: "about:blank" }, void 0, owner);
|
|
1309
|
+
const { sessionId } = await b.send("Target.attachToTarget", {
|
|
1310
|
+
targetId,
|
|
1311
|
+
flatten: true
|
|
1312
|
+
}, void 0, owner);
|
|
1313
|
+
return new Helper(b, sessionId, owner);
|
|
1314
|
+
}
|
|
1315
|
+
async call(fn, args) {
|
|
1316
|
+
const r = await this.b.send("Runtime.evaluate", {
|
|
1317
|
+
expression: `(${fn})(...${JSON.stringify(args)})`,
|
|
1318
|
+
awaitPromise: true,
|
|
1319
|
+
returnByValue: true
|
|
1320
|
+
}, this.sid, this.owner);
|
|
1321
|
+
if (r.exceptionDetails) throw new Error(`helper: ${r.exceptionDetails.exception?.description ?? r.exceptionDetails.text}`);
|
|
1322
|
+
return r.result.value;
|
|
1323
|
+
}
|
|
1324
|
+
crop(shot, dsf, boxes) {
|
|
1325
|
+
return this.call(CROP, [
|
|
1326
|
+
shot,
|
|
1327
|
+
dsf,
|
|
1328
|
+
boxes
|
|
1329
|
+
]);
|
|
1330
|
+
}
|
|
1331
|
+
compare(a, b, dsf, boxes, tol, atB = false) {
|
|
1332
|
+
return this.call(COMPARE, [
|
|
1333
|
+
a,
|
|
1334
|
+
b,
|
|
1335
|
+
dsf,
|
|
1336
|
+
boxes,
|
|
1337
|
+
tol,
|
|
1338
|
+
atB
|
|
1339
|
+
]);
|
|
1340
|
+
}
|
|
1341
|
+
jpeg(png, quality, scale) {
|
|
1342
|
+
return this.call(TO_JPEG, [
|
|
1343
|
+
png,
|
|
1344
|
+
quality,
|
|
1345
|
+
scale
|
|
1346
|
+
]);
|
|
1347
|
+
}
|
|
1348
|
+
};
|
|
1349
|
+
/** `marver`'s bake rule for "nothing else changed": at most 0.05 % of the pixels beyond 32 levels outside every box, and
|
|
1350
|
+
* no 16x16 block more than a quarter changed. */
|
|
1351
|
+
const untouched = (o) => o.gt32 <= o.n * 5e-4 && o.blockMax <= 64;
|
|
1352
|
+
/** Is macOS `sips` here to rasterise a printed page (print certification)? */
|
|
1353
|
+
let sipsHere;
|
|
1354
|
+
function hasSips() {
|
|
1355
|
+
if (sipsHere === void 0) sipsHere = process.platform === "darwin" && existsSync("/usr/bin/sips") && existsSync("/System/Library/ColorSync/Profiles/sRGB Profile.icc");
|
|
1356
|
+
return sipsHere;
|
|
1357
|
+
}
|
|
1358
|
+
/** A one-page PDF rasterised by sips at `side` px on its long side, in sRGB (sips renders in the display's profile
|
|
1359
|
+
* otherwise, and Display P3 values read as sRGB look like a colour shift). */
|
|
1360
|
+
function sipsRaster(pdfPath, side) {
|
|
1361
|
+
const out = `${pdfPath}.sips.png`;
|
|
1362
|
+
return new Promise((resolve) => {
|
|
1363
|
+
execFile("/usr/bin/sips", [
|
|
1364
|
+
"-s",
|
|
1365
|
+
"format",
|
|
1366
|
+
"png",
|
|
1367
|
+
"-Z",
|
|
1368
|
+
String(Math.round(side)),
|
|
1369
|
+
"-m",
|
|
1370
|
+
"/System/Library/ColorSync/Profiles/sRGB Profile.icc",
|
|
1371
|
+
pdfPath,
|
|
1372
|
+
"--out",
|
|
1373
|
+
out
|
|
1374
|
+
], { timeout: 2e4 }, (err) => {
|
|
1375
|
+
if (err) return resolve(null);
|
|
1376
|
+
try {
|
|
1377
|
+
const b = readFileSync(out);
|
|
1378
|
+
rmSync(out, { force: true });
|
|
1379
|
+
resolve(b);
|
|
1380
|
+
} catch {
|
|
1381
|
+
resolve(null);
|
|
1382
|
+
}
|
|
1383
|
+
});
|
|
1384
|
+
});
|
|
1385
|
+
}
|
|
1386
|
+
/** Render, patch, certify and print one page. Throws only when the browser itself is gone. */
|
|
1387
|
+
async function renderSlide(b, helper, page, o) {
|
|
1388
|
+
const W = page.width, H = page.height;
|
|
1389
|
+
const dsf = captureScale(W, H);
|
|
1390
|
+
const owner = {};
|
|
1391
|
+
let targetId;
|
|
1392
|
+
const send = (m, p = {}, sid) => b.send(m, p, sid, owner);
|
|
1393
|
+
const abort = () => b.abort(owner, "the export was cancelled");
|
|
1394
|
+
o.signal.addEventListener("abort", abort);
|
|
1395
|
+
try {
|
|
1396
|
+
targetId = (await send("Target.createTarget", {
|
|
1397
|
+
url: "about:blank",
|
|
1398
|
+
newWindow: true
|
|
1399
|
+
})).targetId;
|
|
1400
|
+
const sid = (await send("Target.attachToTarget", {
|
|
1401
|
+
targetId,
|
|
1402
|
+
flatten: true
|
|
1403
|
+
})).sessionId;
|
|
1404
|
+
const ev = async (expression, awaitPromise = false) => {
|
|
1405
|
+
const r = await send("Runtime.evaluate", {
|
|
1406
|
+
expression,
|
|
1407
|
+
returnByValue: true,
|
|
1408
|
+
awaitPromise
|
|
1409
|
+
}, sid);
|
|
1410
|
+
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description?.split("\n")[0] ?? r.exceptionDetails.text);
|
|
1411
|
+
return r.result?.value;
|
|
1412
|
+
};
|
|
1413
|
+
const bounded = (p, ms) => {
|
|
1414
|
+
let t;
|
|
1415
|
+
return Promise.race([p.catch(() => null), new Promise((r) => {
|
|
1416
|
+
t = setTimeout(() => r(null), Math.max(1, ms));
|
|
1417
|
+
})]).finally(() => clearTimeout(t));
|
|
1418
|
+
};
|
|
1419
|
+
let view = null;
|
|
1420
|
+
const win = await bounded(send("Browser.getWindowForTarget", { targetId }), 1e3);
|
|
1421
|
+
const v0 = await bounded(ev("[innerWidth, innerHeight, devicePixelRatio]"), 1e3);
|
|
1422
|
+
if (win?.windowId !== void 0 && v0 && typeof win.bounds?.width === "number" && typeof win.bounds?.height === "number") {
|
|
1423
|
+
const decoW = win.bounds.width - v0[0], decoH = win.bounds.height - v0[1];
|
|
1424
|
+
const cw = Math.round(W * dsf / v0[2]), ch = Math.round(H * dsf / v0[2]);
|
|
1425
|
+
if (await bounded(send("Browser.setWindowBounds", {
|
|
1426
|
+
windowId: win.windowId,
|
|
1427
|
+
bounds: {
|
|
1428
|
+
width: cw + decoW,
|
|
1429
|
+
height: ch + decoH
|
|
1430
|
+
}
|
|
1431
|
+
}).then(() => true), 1e3)) view = {
|
|
1432
|
+
w: Math.round(cw * v0[2]),
|
|
1433
|
+
h: Math.round(ch * v0[2])
|
|
1434
|
+
};
|
|
1435
|
+
}
|
|
1436
|
+
await send("Emulation.setDeviceMetricsOverride", {
|
|
1437
|
+
width: W,
|
|
1438
|
+
height: H,
|
|
1439
|
+
deviceScaleFactor: dsf,
|
|
1440
|
+
mobile: false
|
|
1441
|
+
}, sid);
|
|
1442
|
+
await send("Emulation.setEmulatedMedia", { media: "screen" }, sid);
|
|
1443
|
+
await send("Page.enable", {}, sid);
|
|
1444
|
+
let lastException = "";
|
|
1445
|
+
const off = b.on((m) => {
|
|
1446
|
+
if (m.sessionId === sid && m.method === "Runtime.exceptionThrown") lastException = String(m.params?.exceptionDetails?.exception?.description ?? m.params?.exceptionDetails?.text ?? "").split("\n")[0];
|
|
1447
|
+
});
|
|
1448
|
+
await send("Runtime.enable", {}, sid);
|
|
1449
|
+
await send("Page.addScriptToEvaluateOnNewDocument", { source: PDF_EARLY }, sid);
|
|
1450
|
+
try {
|
|
1451
|
+
const nav = await send("Page.navigate", { url: o.url }, sid);
|
|
1452
|
+
if (nav?.errorText && nav.errorText !== "net::ERR_ABORTED") return {
|
|
1453
|
+
status: "failed",
|
|
1454
|
+
error: `could not load the frame (${nav.errorText})`
|
|
1455
|
+
};
|
|
1456
|
+
const by = Date.now() + (o.slideMs ?? PDF_BUDGET.slideMs);
|
|
1457
|
+
let mounted = false;
|
|
1458
|
+
while (Date.now() < by) {
|
|
1459
|
+
mounted = await bounded(ev(`(() => { const el = document.getElementById('root') ?? document.body; return !!el && el.childElementCount > 0 && document.readyState !== 'loading' })()`), 1500) === true;
|
|
1460
|
+
if (mounted) break;
|
|
1461
|
+
await wait(100);
|
|
1462
|
+
}
|
|
1463
|
+
if (!mounted) return {
|
|
1464
|
+
status: "failed",
|
|
1465
|
+
error: `the frame never rendered${lastException ? ` - the page threw: ${lastException}` : ""}`
|
|
1466
|
+
};
|
|
1467
|
+
const left = () => Math.max(1, by - Date.now());
|
|
1468
|
+
await bounded(ev(`window.postMessage({type:'sh:camera',moving:false,scale:1}, location.origin)`), left());
|
|
1469
|
+
await bounded(ev("document.fonts.ready.then(() => true)", true), left());
|
|
1470
|
+
let settled = false;
|
|
1471
|
+
while (Date.now() < by) {
|
|
1472
|
+
if (await bounded(ev(SETTLED), left()) === true) {
|
|
1473
|
+
settled = true;
|
|
1474
|
+
break;
|
|
1475
|
+
}
|
|
1476
|
+
await wait(100);
|
|
1477
|
+
}
|
|
1478
|
+
await bounded(ev(SVG_IMAGES, true), Math.min(3e3, left()));
|
|
1479
|
+
await bounded(ev(TWO_FRAMES, true), 1e3);
|
|
1480
|
+
const frameError = await bounded(ev(`window.__mvFrameError || ''`), 1e3);
|
|
1481
|
+
if (frameError) return {
|
|
1482
|
+
status: "failed",
|
|
1483
|
+
error: `the frame rendered an error - ${frameError}`
|
|
1484
|
+
};
|
|
1485
|
+
await ev(PDF_INSTALL);
|
|
1486
|
+
await ev("window.__mvPdf.freeze()");
|
|
1487
|
+
await bounded(ev(TWO_FRAMES, true), 1e3);
|
|
1488
|
+
await ev("window.__mvPdf.freeze()");
|
|
1489
|
+
await bounded(ev(TWO_FRAMES, true), 1e3);
|
|
1490
|
+
const out = {
|
|
1491
|
+
status: "vector",
|
|
1492
|
+
...settled ? {} : { unsettled: true }
|
|
1493
|
+
};
|
|
1494
|
+
if (await ev(`window.__mvPdf.clipped(${W}, ${H})`)) out.clipped = true;
|
|
1495
|
+
out.assets = await bounded(ev(`[...new Set(performance.getEntriesByType('resource').map((e) => { try { return decodeURIComponent(new URL(e.name).pathname) } catch { return '' } }).filter((p) => p.startsWith('/design/assets/')).map((p) => p.slice(1)))]`), 1e3) ?? [];
|
|
1496
|
+
const shoot = async () => {
|
|
1497
|
+
for (let k = 0;; k++) {
|
|
1498
|
+
const r = await send("Page.captureScreenshot", {
|
|
1499
|
+
format: "png",
|
|
1500
|
+
fromSurface: true
|
|
1501
|
+
}, sid);
|
|
1502
|
+
const png = String(r.data);
|
|
1503
|
+
if (!view || k >= 2 || await staleSurface(Buffer.from(png, "base64"), view.w, view.h, Date.now() + 2e3) !== "stale") return png;
|
|
1504
|
+
await bounded(ev(TWO_FRAMES, true), 1e3);
|
|
1505
|
+
}
|
|
1506
|
+
};
|
|
1507
|
+
const ref = await shoot();
|
|
1508
|
+
await ev(`window.__mvPdf.stage(${W}, ${H})`);
|
|
1509
|
+
await bounded(ev(TWO_FRAMES, true), 1e3);
|
|
1510
|
+
const debug = (name, data) => {
|
|
1511
|
+
const d = process.env.MARVER_PDF_DEBUG;
|
|
1512
|
+
if (d) try {
|
|
1513
|
+
mkdirSync(d, { recursive: true });
|
|
1514
|
+
writeFileSync(join(d, `${String(o.n + 1).padStart(3, "0")}-${page.frame.replace(/\//g, "__")}.${name}`), typeof data === "string" ? Buffer.from(data, "base64") : data);
|
|
1515
|
+
} catch {}
|
|
1516
|
+
};
|
|
1517
|
+
debug("screen.png", ref);
|
|
1518
|
+
if (o.notes) {
|
|
1519
|
+
out.picture = Buffer.from(await helper.jpeg(ref, .9, 2 / dsf), "base64");
|
|
1520
|
+
return out;
|
|
1521
|
+
}
|
|
1522
|
+
const links = await ev("window.__mvPdf.links()");
|
|
1523
|
+
const toRaster = async (why) => ({
|
|
1524
|
+
...out,
|
|
1525
|
+
status: "raster",
|
|
1526
|
+
rasterWhy: why,
|
|
1527
|
+
raster: {
|
|
1528
|
+
jpeg: Buffer.from(await helper.jpeg(ref, .9, 1), "base64"),
|
|
1529
|
+
dsf,
|
|
1530
|
+
links
|
|
1531
|
+
}
|
|
1532
|
+
});
|
|
1533
|
+
if (o.mode === "raster") return toRaster("--raster");
|
|
1534
|
+
const hits = o.mode === "vector" ? [] : await ev(`window.__mvPdf.detect(${W}, ${H}, true)`);
|
|
1535
|
+
const rootFx = hits.find((h) => h.kind === "root");
|
|
1536
|
+
if (rootFx) return toRaster(`an effect on the page itself (${rootFx.why}) - nothing to patch it into`);
|
|
1537
|
+
if (hits.some((h) => h.transformed)) return toRaster(`an effect under a transform (${hits.find((h) => h.transformed).why})`);
|
|
1538
|
+
if (hits.length) {
|
|
1539
|
+
const patches = [];
|
|
1540
|
+
for (const h of hits) await ev(`window.__mvPdf.mark(${h.i}, ${JSON.stringify(h.kind)})`);
|
|
1541
|
+
for (const h of hits) {
|
|
1542
|
+
if (h.kind === "shadow") {
|
|
1543
|
+
patches.push({
|
|
1544
|
+
i: h.i,
|
|
1545
|
+
kind: "shadow",
|
|
1546
|
+
url: "",
|
|
1547
|
+
links: []
|
|
1548
|
+
});
|
|
1549
|
+
continue;
|
|
1550
|
+
}
|
|
1551
|
+
const box = await ev(`window.__mvPdf.prepare(${h.i})`);
|
|
1552
|
+
if (!box) continue;
|
|
1553
|
+
await bounded(ev(TWO_FRAMES, true), 1e3);
|
|
1554
|
+
const shot = await shoot();
|
|
1555
|
+
await ev("window.__mvPdf.restore()");
|
|
1556
|
+
const [c] = await helper.crop(shot, dsf, [box]);
|
|
1557
|
+
const url = c.png.length <= c.jpeg.length * 1.25 ? c.png : c.jpeg;
|
|
1558
|
+
patches.push({
|
|
1559
|
+
i: h.i,
|
|
1560
|
+
kind: h.kind,
|
|
1561
|
+
url,
|
|
1562
|
+
links: h.kind === "whole" ? await ev(`window.__mvPdf.linksIn(${h.i})`) : []
|
|
1563
|
+
});
|
|
1564
|
+
}
|
|
1565
|
+
await ev(`window.__mvPdf.apply(${JSON.stringify(patches)})`);
|
|
1566
|
+
await bounded(ev(`Promise.all(Array.from(document.images).map((im) => im.decode().catch(() => 1))).then(() => true)`, true), 3e3);
|
|
1567
|
+
await bounded(ev(TWO_FRAMES, true), 1e3);
|
|
1568
|
+
await wait(50);
|
|
1569
|
+
const patched = await shoot();
|
|
1570
|
+
debug("patched.png", patched);
|
|
1571
|
+
const v = await helper.compare(ref, patched, dsf, hits.map((h) => h.rect), CERTIFY.tol);
|
|
1572
|
+
const worst = Math.max(0, ...v.boxes);
|
|
1573
|
+
if (worst > CERTIFY.box) return toRaster(`a patch differed from the screen (${(worst * 100).toFixed(1)} % of its box)`);
|
|
1574
|
+
if (!untouched(v.outside)) return toRaster("a patch changed the slide outside its box");
|
|
1575
|
+
out.status = "patched";
|
|
1576
|
+
out.patches = hits.map((h) => h.why);
|
|
1577
|
+
}
|
|
1578
|
+
const pr = await send("Page.printToPDF", {
|
|
1579
|
+
paperWidth: W / 96,
|
|
1580
|
+
paperHeight: H / 96,
|
|
1581
|
+
marginTop: 0,
|
|
1582
|
+
marginBottom: 0,
|
|
1583
|
+
marginLeft: 0,
|
|
1584
|
+
marginRight: 0,
|
|
1585
|
+
printBackground: true,
|
|
1586
|
+
preferCSSPageSize: false,
|
|
1587
|
+
scale: 1,
|
|
1588
|
+
generateTaggedPDF: false,
|
|
1589
|
+
generateDocumentOutline: false,
|
|
1590
|
+
transferMode: "ReturnAsBase64"
|
|
1591
|
+
}, sid);
|
|
1592
|
+
let pdf = Buffer.from(String(pr.data), "base64");
|
|
1593
|
+
debug("raw.pdf", pdf);
|
|
1594
|
+
const doc = await PDFDocument.load(pdf, { updateMetadata: false });
|
|
1595
|
+
if (doc.getPageCount() > 1) {
|
|
1596
|
+
if (!out.clipped) out.spilled = true;
|
|
1597
|
+
const one = await PDFDocument.create();
|
|
1598
|
+
const [p] = await one.copyPages(doc, [0]);
|
|
1599
|
+
one.addPage(p);
|
|
1600
|
+
pdf = Buffer.from(await one.save());
|
|
1601
|
+
}
|
|
1602
|
+
if (hasSips()) {
|
|
1603
|
+
const tmp = mkdtempSync(join(tmpdir(), "mv-pdf-sips-"));
|
|
1604
|
+
const file = join(tmp, "page.pdf");
|
|
1605
|
+
let png = null;
|
|
1606
|
+
try {
|
|
1607
|
+
writeFileSync(file, pdf);
|
|
1608
|
+
png = await sipsRaster(file, Math.max(W, H) * 2);
|
|
1609
|
+
} finally {
|
|
1610
|
+
rmSync(tmp, {
|
|
1611
|
+
recursive: true,
|
|
1612
|
+
force: true
|
|
1613
|
+
});
|
|
1614
|
+
}
|
|
1615
|
+
if (png) {
|
|
1616
|
+
debug("print.png", png);
|
|
1617
|
+
out.printChecked = true;
|
|
1618
|
+
const c = await helper.compare(ref, png.toString("base64"), dsf, [], CERTIFY.tol, true);
|
|
1619
|
+
if (c.coarse > CERTIFY.page || c.fine > CERTIFY.fine) {
|
|
1620
|
+
if (o.mode === "vector") out.printDiffers = true;
|
|
1621
|
+
else return toRaster(`the printed page differed from the screen (${(Math.max(c.coarse, c.fine) * 100).toFixed(2)} % of it)`);
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
return {
|
|
1626
|
+
...out,
|
|
1627
|
+
pdf
|
|
1628
|
+
};
|
|
1629
|
+
} finally {
|
|
1630
|
+
off();
|
|
1631
|
+
}
|
|
1632
|
+
} catch (err) {
|
|
1633
|
+
if (o.signal.aborted) throw new Error("the export was cancelled");
|
|
1634
|
+
if (b.dead) throw err;
|
|
1635
|
+
return {
|
|
1636
|
+
status: "failed",
|
|
1637
|
+
error: err.message
|
|
1638
|
+
};
|
|
1639
|
+
} finally {
|
|
1640
|
+
o.signal.removeEventListener("abort", abort);
|
|
1641
|
+
if (targetId && !b.dead) {
|
|
1642
|
+
let t;
|
|
1643
|
+
await Promise.race([b.send("Target.closeTarget", { targetId }).catch(() => {}), new Promise((r) => {
|
|
1644
|
+
t = setTimeout(r, 2e3);
|
|
1645
|
+
})]);
|
|
1646
|
+
clearTimeout(t);
|
|
1647
|
+
}
|
|
1648
|
+
b.abort(owner, "the slide finished");
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
/** One bookmark per page, named by its title, each pointing at its page (pdf-lib's low-level outline objects). */
|
|
1652
|
+
function writeOutline(doc, titles) {
|
|
1653
|
+
const pages = doc.getPages();
|
|
1654
|
+
const n = Math.min(pages.length, titles.length);
|
|
1655
|
+
if (!n) return;
|
|
1656
|
+
const ctx = doc.context;
|
|
1657
|
+
const root = ctx.nextRef();
|
|
1658
|
+
const refs = Array.from({ length: n }, () => ctx.nextRef());
|
|
1659
|
+
for (let i = 0; i < n; i++) {
|
|
1660
|
+
const item = ctx.obj({});
|
|
1661
|
+
item.set(PDFName.of("Title"), PDFHexString.fromText(titles[i]));
|
|
1662
|
+
item.set(PDFName.of("Parent"), root);
|
|
1663
|
+
if (i > 0) item.set(PDFName.of("Prev"), refs[i - 1]);
|
|
1664
|
+
if (i < n - 1) item.set(PDFName.of("Next"), refs[i + 1]);
|
|
1665
|
+
item.set(PDFName.of("Dest"), ctx.obj([pages[i].ref, PDFName.of("Fit")]));
|
|
1666
|
+
ctx.assign(refs[i], item);
|
|
1667
|
+
}
|
|
1668
|
+
const outlines = ctx.obj({});
|
|
1669
|
+
outlines.set(PDFName.of("Type"), PDFName.of("Outlines"));
|
|
1670
|
+
outlines.set(PDFName.of("First"), refs[0]);
|
|
1671
|
+
outlines.set(PDFName.of("Last"), refs[n - 1]);
|
|
1672
|
+
outlines.set(PDFName.of("Count"), PDFNumber.of(n));
|
|
1673
|
+
ctx.assign(root, outlines);
|
|
1674
|
+
doc.catalog.set(PDFName.of("Outlines"), root);
|
|
1675
|
+
doc.catalog.set(PDFName.of("PageMode"), PDFName.of("UseOutlines"));
|
|
1676
|
+
}
|
|
1677
|
+
/** A raster page: the picture filling a page of the slide's size, its links kept as link annotations. */
|
|
1678
|
+
async function addRaster(doc, page, r) {
|
|
1679
|
+
const k = .75;
|
|
1680
|
+
const p = doc.addPage([page.width * k, page.height * k]);
|
|
1681
|
+
const img = await doc.embedJpg(new Uint8Array(r.jpeg));
|
|
1682
|
+
p.drawImage(img, {
|
|
1683
|
+
x: 0,
|
|
1684
|
+
y: 0,
|
|
1685
|
+
width: page.width * k,
|
|
1686
|
+
height: page.height * k
|
|
1687
|
+
});
|
|
1688
|
+
const annots = [];
|
|
1689
|
+
for (const l of r.links) for (const b of l.rects) {
|
|
1690
|
+
const x0 = Math.max(0, b.x) * k, x1 = Math.min(page.width, b.x + b.w) * k;
|
|
1691
|
+
const y1 = (page.height - Math.max(0, b.y)) * k, y0 = (page.height - Math.min(page.height, b.y + b.h)) * k;
|
|
1692
|
+
if (x1 - x0 < .5 || y1 - y0 < .5) continue;
|
|
1693
|
+
annots.push(doc.context.register(doc.context.obj({
|
|
1694
|
+
Type: "Annot",
|
|
1695
|
+
Subtype: "Link",
|
|
1696
|
+
Rect: [
|
|
1697
|
+
x0,
|
|
1698
|
+
y0,
|
|
1699
|
+
x1,
|
|
1700
|
+
y1
|
|
1701
|
+
],
|
|
1702
|
+
Border: [
|
|
1703
|
+
0,
|
|
1704
|
+
0,
|
|
1705
|
+
0
|
|
1706
|
+
],
|
|
1707
|
+
A: {
|
|
1708
|
+
Type: "Action",
|
|
1709
|
+
S: "URI",
|
|
1710
|
+
URI: PDFString.of(l.href)
|
|
1711
|
+
}
|
|
1712
|
+
})));
|
|
1713
|
+
}
|
|
1714
|
+
if (annots.length) p.node.set(PDFName.of("Annots"), doc.context.obj(annots));
|
|
1715
|
+
}
|
|
1716
|
+
/** Merge the pages in plan order; failed pages (with --keep-going) blank at their size. */
|
|
1717
|
+
async function mergePages(pages, meta) {
|
|
1718
|
+
const doc = await PDFDocument.create({ updateMetadata: false });
|
|
1719
|
+
for (const { page, out } of pages) if (out.pdf) {
|
|
1720
|
+
const src = await PDFDocument.load(out.pdf, { updateMetadata: false });
|
|
1721
|
+
const [p] = await doc.copyPages(src, [0]);
|
|
1722
|
+
doc.addPage(p);
|
|
1723
|
+
} else if (out.raster) await addRaster(doc, page, out.raster);
|
|
1724
|
+
else doc.addPage([page.width * .75, page.height * .75]);
|
|
1725
|
+
writeOutline(doc, pages.map((p) => p.page.title));
|
|
1726
|
+
doc.setTitle(meta.title, { showInWindowTitleBar: true });
|
|
1727
|
+
doc.setAuthor(meta.author);
|
|
1728
|
+
doc.setCreator(`Marver ${meta.version}`);
|
|
1729
|
+
doc.setProducer(`Marver ${meta.version} (Chrome ${meta.chrome}, pdf-lib)`);
|
|
1730
|
+
const now = /* @__PURE__ */ new Date();
|
|
1731
|
+
doc.setCreationDate(now);
|
|
1732
|
+
doc.setModificationDate(now);
|
|
1733
|
+
return doc.save();
|
|
1734
|
+
}
|
|
1735
|
+
/** Write `bytes` to `file` whole: a temp file beside it, then a rename. */
|
|
1736
|
+
function writeWhole(file, bytes) {
|
|
1737
|
+
const tmp = `${file}.${randomBytes(6).toString("hex")}.tmp`;
|
|
1738
|
+
writeFileSync(tmp, bytes);
|
|
1739
|
+
try {
|
|
1740
|
+
renameSync(tmp, file);
|
|
1741
|
+
} catch (err) {
|
|
1742
|
+
rmSync(tmp, { force: true });
|
|
1743
|
+
throw err;
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
/** The abort reason of a cancel (a deadline aborts with its Error). */
|
|
1747
|
+
const CANCELLED = "cancelled";
|
|
1748
|
+
const jobs = /* @__PURE__ */ new Map();
|
|
1749
|
+
const running = /* @__PURE__ */ new Map();
|
|
1750
|
+
const jobsDir = (root) => join(root, "design", ".local", "pdf");
|
|
1751
|
+
/** The job folder may be made, written and removed only when design/.local and design/.local/pdf are real folders (or
|
|
1752
|
+
* absent) inside the project - never through a symlink to somewhere else. */
|
|
1753
|
+
function jobsDirSafe(root) {
|
|
1754
|
+
return !checkRealDirs(root, [
|
|
1755
|
+
[join(root, "design"), "design"],
|
|
1756
|
+
[join(root, "design", ".local"), "design/.local"],
|
|
1757
|
+
[jobsDir(root), "design/.local/pdf"]
|
|
1758
|
+
]);
|
|
1759
|
+
}
|
|
1760
|
+
/** Remove a path inside the job folder - only while the folder is a real one inside the project, and the path in it. */
|
|
1761
|
+
function rmInJobs(root, path) {
|
|
1762
|
+
if (!jobsDirSafe(root)) return;
|
|
1763
|
+
const base = jobsDir(root);
|
|
1764
|
+
if (!path.startsWith(base + sep)) return;
|
|
1765
|
+
const parts = path.slice(base.length + 1).split(sep);
|
|
1766
|
+
let at = base;
|
|
1767
|
+
for (const part of parts.slice(0, -1)) {
|
|
1768
|
+
at = join(at, part);
|
|
1769
|
+
try {
|
|
1770
|
+
if (!lstatSync(at).isDirectory()) return;
|
|
1771
|
+
} catch {
|
|
1772
|
+
return;
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
try {
|
|
1776
|
+
if (lstatSync(path).isSymbolicLink()) {
|
|
1777
|
+
rmSync(path, { force: true });
|
|
1778
|
+
return;
|
|
1779
|
+
}
|
|
1780
|
+
} catch {
|
|
1781
|
+
return;
|
|
1782
|
+
}
|
|
1783
|
+
try {
|
|
1784
|
+
rmSync(path, {
|
|
1785
|
+
recursive: true,
|
|
1786
|
+
force: true
|
|
1787
|
+
});
|
|
1788
|
+
} catch {}
|
|
1789
|
+
}
|
|
1790
|
+
/** A job's own folder is still a real folder inside the project (not swapped for a link): its files may be written. */
|
|
1791
|
+
const jobDirReal = (root, dir) => {
|
|
1792
|
+
if (!jobsDirSafe(root) || !dir.startsWith(jobsDir(root) + sep)) return false;
|
|
1793
|
+
try {
|
|
1794
|
+
return lstatSync(dir).isDirectory();
|
|
1795
|
+
} catch {
|
|
1796
|
+
return false;
|
|
1797
|
+
}
|
|
1798
|
+
};
|
|
1799
|
+
/** `marver dev` start: no job survives a server (their browsers did not), so the folder starts empty. */
|
|
1800
|
+
function clearPdfJobs(root) {
|
|
1801
|
+
for (const [id, j] of jobs) if (j.root === root) {
|
|
1802
|
+
if (j.state === "running") j.abort.abort(CANCELLED);
|
|
1803
|
+
jobs.delete(id);
|
|
1804
|
+
}
|
|
1805
|
+
running.delete(root);
|
|
1806
|
+
if (jobsDirSafe(root)) try {
|
|
1807
|
+
rmSync(jobsDir(root), {
|
|
1808
|
+
recursive: true,
|
|
1809
|
+
force: true
|
|
1810
|
+
});
|
|
1811
|
+
} catch {}
|
|
1812
|
+
}
|
|
1813
|
+
onPdfReset(clearPdfJobs);
|
|
1814
|
+
/** Jobs past their hour: their folders removed, their ids forgotten. Run at every job request and on a timer. */
|
|
1815
|
+
function sweepPdfJobs(root, now = Date.now()) {
|
|
1816
|
+
for (const [id, j] of jobs) {
|
|
1817
|
+
if (j.root !== root || j.state === "running") continue;
|
|
1818
|
+
if (now - (j.ended ?? j.created) > PDF_BUDGET.keepMs) {
|
|
1819
|
+
jobs.delete(id);
|
|
1820
|
+
rmInJobs(root, j.dir);
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
if (jobsDirSafe(root)) try {
|
|
1824
|
+
for (const n of readdirSync(jobsDir(root))) {
|
|
1825
|
+
if (jobs.has(n)) continue;
|
|
1826
|
+
const p = join(jobsDir(root), n);
|
|
1827
|
+
try {
|
|
1828
|
+
if (now - statSync(p).mtimeMs > PDF_BUDGET.keepMs) rmInJobs(root, p);
|
|
1829
|
+
} catch {}
|
|
1830
|
+
}
|
|
1831
|
+
} catch {}
|
|
1832
|
+
}
|
|
1833
|
+
let sweeper;
|
|
1834
|
+
const roots = /* @__PURE__ */ new Set();
|
|
1835
|
+
const getJob = (id) => JOB_ID.test(id) ? jobs.get(id) : void 0;
|
|
1836
|
+
const runningJob = (root) => {
|
|
1837
|
+
const id = running.get(root);
|
|
1838
|
+
return id ? jobs.get(id) : void 0;
|
|
1839
|
+
};
|
|
1840
|
+
/** What a status request answers. */
|
|
1841
|
+
const jobStatus = (j) => ({
|
|
1842
|
+
job: j.id,
|
|
1843
|
+
board: j.board,
|
|
1844
|
+
state: j.state,
|
|
1845
|
+
phase: j.phase,
|
|
1846
|
+
page: j.page,
|
|
1847
|
+
pages: j.pages,
|
|
1848
|
+
notes: !!j.ask.notes,
|
|
1849
|
+
filename: j.filename,
|
|
1850
|
+
...j.report ? { report: j.report } : {},
|
|
1851
|
+
...j.error ? { error: j.error } : {}
|
|
1852
|
+
});
|
|
1853
|
+
/** Validate and start a job: one per canvas (409 with the running one's id), the plan and its budgets checked first. */
|
|
1854
|
+
async function startPdfJob(ctx, ask, seams = {}) {
|
|
1855
|
+
sweepPdfJobs(ctx.root);
|
|
1856
|
+
const busy = runningJob(ctx.root);
|
|
1857
|
+
if (busy) return {
|
|
1858
|
+
ok: false,
|
|
1859
|
+
status: 409,
|
|
1860
|
+
error: `a PDF of "${busy.board}" is being made - wait for it, or cancel it`,
|
|
1861
|
+
job: busy.id
|
|
1862
|
+
};
|
|
1863
|
+
if (ask.theme !== void 0 && !/^[a-z0-9-]{1,32}$/i.test(ask.theme)) return {
|
|
1864
|
+
ok: false,
|
|
1865
|
+
status: 400,
|
|
1866
|
+
error: "invalid theme"
|
|
1867
|
+
};
|
|
1868
|
+
const p = await planFor(ctx, ask.board, ask.theme);
|
|
1869
|
+
if (!p.ok) return p;
|
|
1870
|
+
const again = runningJob(ctx.root);
|
|
1871
|
+
if (again) return {
|
|
1872
|
+
ok: false,
|
|
1873
|
+
status: 409,
|
|
1874
|
+
error: `a PDF of "${again.board}" is being made - wait for it, or cancel it`,
|
|
1875
|
+
job: again.id
|
|
1876
|
+
};
|
|
1877
|
+
if (!jobsDirSafe(ctx.root)) return {
|
|
1878
|
+
ok: false,
|
|
1879
|
+
status: 422,
|
|
1880
|
+
error: "design/.local is a link out of this project - the PDF has nowhere safe to go"
|
|
1881
|
+
};
|
|
1882
|
+
const id = randomBytes(16).toString("base64url");
|
|
1883
|
+
const dir = join(jobsDir(ctx.root), id);
|
|
1884
|
+
mkdirSync(dir, { recursive: true });
|
|
1885
|
+
const job = {
|
|
1886
|
+
id,
|
|
1887
|
+
root: ctx.root,
|
|
1888
|
+
board: ask.board,
|
|
1889
|
+
ask,
|
|
1890
|
+
state: "running",
|
|
1891
|
+
page: 0,
|
|
1892
|
+
pages: p.plan.pages.length,
|
|
1893
|
+
phase: "starting",
|
|
1894
|
+
created: Date.now(),
|
|
1895
|
+
dir,
|
|
1896
|
+
filename: `${ask.board}${ask.notes ? "-notes" : ""}.pdf`,
|
|
1897
|
+
abort: new AbortController()
|
|
1898
|
+
};
|
|
1899
|
+
jobs.set(id, job);
|
|
1900
|
+
running.set(ctx.root, id);
|
|
1901
|
+
roots.add(ctx.root);
|
|
1902
|
+
if (!sweeper) {
|
|
1903
|
+
sweeper = setInterval(() => {
|
|
1904
|
+
for (const r of roots) sweepPdfJobs(r);
|
|
1905
|
+
}, 6e5);
|
|
1906
|
+
sweeper.unref?.();
|
|
1907
|
+
}
|
|
1908
|
+
const deadline = setTimeout(() => job.abort.abort(/* @__PURE__ */ new Error(`the export took longer than ${PDF_BUDGET.ms / 6e4} minutes`)), PDF_BUDGET.ms);
|
|
1909
|
+
deadline.unref?.();
|
|
1910
|
+
(seams.run ?? ((j, plan, title) => runJob(ctx, j, plan, title)))(job, p.plan, p.title).then(() => {
|
|
1911
|
+
if (job.state !== "running") return;
|
|
1912
|
+
const reason = job.abort.signal.aborted ? job.abort.signal.reason : void 0;
|
|
1913
|
+
if (reason === CANCELLED) job.state = "cancelled";
|
|
1914
|
+
else if (reason instanceof Error) {
|
|
1915
|
+
job.state = "failed";
|
|
1916
|
+
job.error = reason.message;
|
|
1917
|
+
} else {
|
|
1918
|
+
job.state = "done";
|
|
1919
|
+
job.phase = "done";
|
|
1920
|
+
}
|
|
1921
|
+
}).catch((err) => {
|
|
1922
|
+
if (job.state !== "running") return;
|
|
1923
|
+
const reason = job.abort.signal.aborted ? job.abort.signal.reason : void 0;
|
|
1924
|
+
job.state = reason === CANCELLED ? "cancelled" : "failed";
|
|
1925
|
+
job.error = reason instanceof Error ? reason.message : err.message;
|
|
1926
|
+
}).finally(() => {
|
|
1927
|
+
clearTimeout(deadline);
|
|
1928
|
+
job.ended = Date.now();
|
|
1929
|
+
if (running.get(ctx.root) === id) running.delete(ctx.root);
|
|
1930
|
+
if (jobDirReal(ctx.root, dir)) try {
|
|
1931
|
+
for (const n of readdirSync(dir)) if (job.state !== "done" || join(dir, n) !== job.file) rmInJobs(ctx.root, join(dir, n));
|
|
1932
|
+
} catch {}
|
|
1933
|
+
if (job.state === "cancelled") {
|
|
1934
|
+
jobs.delete(id);
|
|
1935
|
+
rmInJobs(ctx.root, dir);
|
|
1936
|
+
}
|
|
1937
|
+
});
|
|
1938
|
+
return {
|
|
1939
|
+
ok: true,
|
|
1940
|
+
job
|
|
1941
|
+
};
|
|
1942
|
+
}
|
|
1943
|
+
/** Cancel a running job (its browser closes; nothing of it stays). */
|
|
1944
|
+
function cancelPdfJob(id) {
|
|
1945
|
+
const j = getJob(id);
|
|
1946
|
+
if (!j) return false;
|
|
1947
|
+
if (j.state === "running") j.abort.abort(CANCELLED);
|
|
1948
|
+
else {
|
|
1949
|
+
jobs.delete(id);
|
|
1950
|
+
rmInJobs(j.root, j.dir);
|
|
1951
|
+
}
|
|
1952
|
+
return true;
|
|
1953
|
+
}
|
|
1954
|
+
/** The source revisions a render prints against: its frame's document, and the canvas-wide inputs. */
|
|
1955
|
+
function revisions(ctx, frames) {
|
|
1956
|
+
const doc = new Map(frames.map((f) => [f, ctx.docRev(f)]));
|
|
1957
|
+
const mt = (p) => {
|
|
1958
|
+
try {
|
|
1959
|
+
return String(statSync(join(ctx.root, p)).mtimeMs);
|
|
1960
|
+
} catch {
|
|
1961
|
+
return "-";
|
|
1962
|
+
}
|
|
1963
|
+
};
|
|
1964
|
+
return {
|
|
1965
|
+
doc,
|
|
1966
|
+
global: [
|
|
1967
|
+
"design/config.ts",
|
|
1968
|
+
"design/theme.css",
|
|
1969
|
+
"design/providers.tsx"
|
|
1970
|
+
].map(mt).join("|")
|
|
1971
|
+
};
|
|
1972
|
+
}
|
|
1973
|
+
/** Was any of these asset files (root-relative, inside design/assets) written at or after `since`, or removed? */
|
|
1974
|
+
function assetsChanged(root, assets, since) {
|
|
1975
|
+
for (const a of assets) {
|
|
1976
|
+
if (!a.startsWith("design/assets/") || a.split("/").includes("..")) continue;
|
|
1977
|
+
try {
|
|
1978
|
+
if (statSync(join(root, a)).mtimeMs >= since - 1) return true;
|
|
1979
|
+
} catch {
|
|
1980
|
+
return true;
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
return false;
|
|
1984
|
+
}
|
|
1985
|
+
async function runJob(ctx, job, plan, title) {
|
|
1986
|
+
const t0 = Date.now();
|
|
1987
|
+
const signal = job.abort.signal;
|
|
1988
|
+
for (const by = Date.now() + 1e4; !ctx.settled() && Date.now() < by && !signal.aborted;) await wait(100);
|
|
1989
|
+
const pages = plan.pages;
|
|
1990
|
+
const frames = new Map(ctx.frames().map((f) => [f.id, f]));
|
|
1991
|
+
if (signal.aborted) throw new Error("the export was cancelled");
|
|
1992
|
+
const b = await Browser.launch("mv-shot-");
|
|
1993
|
+
const owner = {};
|
|
1994
|
+
const kill = () => {
|
|
1995
|
+
b.close();
|
|
1996
|
+
};
|
|
1997
|
+
signal.addEventListener("abort", kill);
|
|
1998
|
+
try {
|
|
1999
|
+
if (signal.aborted) throw new Error("the export was cancelled");
|
|
2000
|
+
const chrome = String((await b.send("Browser.getVersion")).product ?? "").replace(/^[^/]*\//, "");
|
|
2001
|
+
const helper = await Helper.open(b, owner);
|
|
2002
|
+
job.phase = "rendering";
|
|
2003
|
+
let bytes = 0;
|
|
2004
|
+
const outs = await pool(4, pages, async (planned, n) => {
|
|
2005
|
+
let page = planned;
|
|
2006
|
+
if (signal.aborted) throw new Error("the export was cancelled");
|
|
2007
|
+
const t = Date.now();
|
|
2008
|
+
let url = "";
|
|
2009
|
+
const attempt = async () => {
|
|
2010
|
+
for (const by = Date.now() + 5e3; !ctx.settled() && Date.now() < by;) await wait(100);
|
|
2011
|
+
const fresh = await planFor(ctx, job.board, job.ask.theme).catch((e) => ({
|
|
2012
|
+
ok: false,
|
|
2013
|
+
status: 500,
|
|
2014
|
+
error: e.message
|
|
2015
|
+
}));
|
|
2016
|
+
if (!fresh.ok) throw new Error(`the board changed while printing - ${fresh.error}`);
|
|
2017
|
+
const p2 = fresh.plan.pages.find((x) => x.frame === page.frame);
|
|
2018
|
+
if (!p2) left = true;
|
|
2019
|
+
else page = p2;
|
|
2020
|
+
url = exportUrl(ctx.origin, page, ctx.frames().find((f) => f.id === page.frame)?.file);
|
|
2021
|
+
const base = revisions(ctx, [page.frame]), since = Date.now();
|
|
2022
|
+
const out = await renderSlide(b, helper, page, {
|
|
2023
|
+
url,
|
|
2024
|
+
dir: job.dir,
|
|
2025
|
+
n,
|
|
2026
|
+
mode: job.ask.mode ?? "auto",
|
|
2027
|
+
notes: !!job.ask.notes,
|
|
2028
|
+
signal
|
|
2029
|
+
});
|
|
2030
|
+
const now = revisions(ctx, [page.frame]);
|
|
2031
|
+
return {
|
|
2032
|
+
out,
|
|
2033
|
+
moved: !ctx.settled() || now.doc.get(page.frame) !== base.doc.get(page.frame) || now.global !== base.global || assetsChanged(ctx.root, out.assets ?? [], since)
|
|
2034
|
+
};
|
|
2035
|
+
};
|
|
2036
|
+
let left = false;
|
|
2037
|
+
let { out, moved } = await attempt();
|
|
2038
|
+
let changed = false;
|
|
2039
|
+
if (out.status !== "failed" && moved) {
|
|
2040
|
+
({out, moved} = await attempt());
|
|
2041
|
+
changed = moved;
|
|
2042
|
+
}
|
|
2043
|
+
if (left) changed = true;
|
|
2044
|
+
if (out.status === "failed" && !job.ask.keepGoing) throw new Error(`${page.frame}: ${out.error}`);
|
|
2045
|
+
bytes += out.pdf?.length ?? out.raster?.jpeg.length ?? out.picture?.length ?? 0;
|
|
2046
|
+
if (bytes > PDF_BUDGET.bytes) throw new Error(`the PDF passed ${PDF_BUDGET.bytes / 2 ** 20} MB - export fewer slides, or with --vector`);
|
|
2047
|
+
job.page++;
|
|
2048
|
+
return {
|
|
2049
|
+
page,
|
|
2050
|
+
out,
|
|
2051
|
+
ms: Date.now() - t,
|
|
2052
|
+
changed
|
|
2053
|
+
};
|
|
2054
|
+
});
|
|
2055
|
+
if (signal.aborted) throw signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("the export was cancelled");
|
|
2056
|
+
let pdf;
|
|
2057
|
+
let pageCount = outs.length;
|
|
2058
|
+
if (job.ask.notes) {
|
|
2059
|
+
job.phase = "handout";
|
|
2060
|
+
const h = await printHandout(b, ctx, job, outs.map((o) => ({
|
|
2061
|
+
page: o.page,
|
|
2062
|
+
picture: o.out.picture,
|
|
2063
|
+
note: frames.get(o.page.frame)?.note
|
|
2064
|
+
})));
|
|
2065
|
+
pdf = h.pdf;
|
|
2066
|
+
pageCount = h.pages;
|
|
2067
|
+
if (pageCount > PDF_BUDGET.pages) throw new Error(`the handout is ${pageCount} pages - a PDF takes ${PDF_BUDGET.pages} at most (shorten the notes, or export fewer slides)`);
|
|
2068
|
+
} else {
|
|
2069
|
+
job.phase = "merging";
|
|
2070
|
+
pdf = await mergePages(outs, {
|
|
2071
|
+
title,
|
|
2072
|
+
author: ctx.canvasName,
|
|
2073
|
+
version: ctx.version,
|
|
2074
|
+
chrome
|
|
2075
|
+
});
|
|
2076
|
+
}
|
|
2077
|
+
if (signal.aborted) throw signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("the export was cancelled");
|
|
2078
|
+
if (pdf.length > PDF_BUDGET.bytes) throw new Error(`the PDF is ${Math.round(pdf.length / 2 ** 20)} MB - ${PDF_BUDGET.bytes / 2 ** 20} MB at most`);
|
|
2079
|
+
const file = join(job.dir, job.filename);
|
|
2080
|
+
if (!jobDirReal(ctx.root, job.dir)) throw new Error("the job folder is no longer a folder of this project - export again");
|
|
2081
|
+
writeWhole(file, pdf);
|
|
2082
|
+
job.file = file;
|
|
2083
|
+
job.report = {
|
|
2084
|
+
board: job.board,
|
|
2085
|
+
notes: !!job.ask.notes,
|
|
2086
|
+
pages: pageCount,
|
|
2087
|
+
bytes: pdf.length,
|
|
2088
|
+
ms: Date.now() - t0,
|
|
2089
|
+
chrome,
|
|
2090
|
+
certified: !job.ask.notes && outs.every((o) => !o.out.pdf || o.out.printChecked && !o.out.printDiffers) && outs.some((o) => o.out.printChecked) ? "print" : "screen",
|
|
2091
|
+
skipped: plan.skipped,
|
|
2092
|
+
slides: outs.map(({ page, out, ms, changed }, i) => ({
|
|
2093
|
+
page: i + 1,
|
|
2094
|
+
frame: page.frame,
|
|
2095
|
+
title: page.title,
|
|
2096
|
+
width: page.width,
|
|
2097
|
+
height: page.height,
|
|
2098
|
+
theme: page.theme,
|
|
2099
|
+
status: out.status,
|
|
2100
|
+
ms,
|
|
2101
|
+
...out.patches?.length ? { patches: out.patches } : {},
|
|
2102
|
+
...out.rasterWhy ? { raster: out.rasterWhy } : {},
|
|
2103
|
+
...out.unsettled ? { unsettled: true } : {},
|
|
2104
|
+
...out.clipped ? { clipped: true } : {},
|
|
2105
|
+
...out.spilled ? { spilled: true } : {},
|
|
2106
|
+
...changed ? { changed: true } : {},
|
|
2107
|
+
...out.error ? { error: out.error } : {},
|
|
2108
|
+
...out.printDiffers ? { printDiffers: true } : {},
|
|
2109
|
+
bytes: out.pdf?.length ?? out.raster?.jpeg.length ?? out.picture?.length ?? 0
|
|
2110
|
+
}))
|
|
2111
|
+
};
|
|
2112
|
+
} finally {
|
|
2113
|
+
signal.removeEventListener("abort", kill);
|
|
2114
|
+
await b.close();
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
/** What the handout page shows, held for its document (`/__mv/handout/?job=`) while it prints. */
|
|
2118
|
+
const handouts = /* @__PURE__ */ new Map();
|
|
2119
|
+
const PAPER = {
|
|
2120
|
+
letter: {
|
|
2121
|
+
w: 11,
|
|
2122
|
+
h: 8.5
|
|
2123
|
+
},
|
|
2124
|
+
a4: {
|
|
2125
|
+
w: 11.69,
|
|
2126
|
+
h: 8.27
|
|
2127
|
+
}
|
|
2128
|
+
};
|
|
2129
|
+
const esc = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
2130
|
+
/** The handout document: per slide its picture, its title as an h2, its notes as Markdown (11 pt at least), or "No
|
|
2131
|
+
* notes". Inert by construction (md.ts escapes raw HTML; the page is served with a CSP that runs no script). */
|
|
2132
|
+
function handoutHtml(h, pictureUrl) {
|
|
2133
|
+
const p = PAPER[h.paper];
|
|
2134
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${esc(h.title)}</title><style>
|
|
2135
|
+
@page { size: ${p.w}in ${p.h}in; margin: 0.45in 0.5in 0.6in }
|
|
2136
|
+
html { -webkit-print-color-adjust: exact; print-color-adjust: exact; background: #fff }
|
|
2137
|
+
body { margin: 0; background: #fff; font: 11pt/1.45 -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Arial, sans-serif; color: #1d1d1f }
|
|
2138
|
+
.slide { display: grid; grid-template-columns: 58% 1fr; column-gap: 0.35in; align-items: start }
|
|
2139
|
+
.slide + .slide { break-before: page }
|
|
2140
|
+
.slide > .pic { break-inside: avoid; margin: 0 }
|
|
2141
|
+
.slide > .pic img { display: block; width: 100%; height: auto; border: 0.5pt solid #d2d2d7; border-radius: 4pt }
|
|
2142
|
+
.slide > .pic .n { margin-top: 6pt; font-size: 9pt; color: #86868b }
|
|
2143
|
+
.side h2 { margin: 0 0 8pt; font-size: 15pt; line-height: 1.25; font-weight: 600; break-after: avoid }
|
|
2144
|
+
.notes { font-size: 11pt }
|
|
2145
|
+
.notes :first-child { margin-top: 0 }
|
|
2146
|
+
.notes h1, .notes h2, .notes h3, .notes h4 { font-size: 12pt; margin: 10pt 0 4pt; break-after: avoid }
|
|
2147
|
+
.notes p, .notes ul, .notes ol, .notes blockquote, .notes pre, .notes table { margin: 0 0 7pt }
|
|
2148
|
+
.notes ul, .notes ol { padding-left: 16pt }
|
|
2149
|
+
.notes code { font: 10.5pt ui-monospace, SFMono-Regular, Menlo, monospace; background: #f2f2f4; padding: 0 2pt; border-radius: 2pt }
|
|
2150
|
+
.notes pre { background: #f5f5f7; padding: 6pt 8pt; border-radius: 4pt; white-space: pre-wrap; word-break: break-word; font-size: 11pt }
|
|
2151
|
+
.notes pre code { background: none; padding: 0; font-size: 11pt }
|
|
2152
|
+
.notes table { border-collapse: collapse; font-size: 11pt }
|
|
2153
|
+
.notes th, .notes td { border: 0.5pt solid #d2d2d7; padding: 3pt 6pt; text-align: left; vertical-align: top }
|
|
2154
|
+
.notes blockquote { border-left: 2pt solid #d2d2d7; padding-left: 8pt; color: #515154 }
|
|
2155
|
+
.notes img { max-width: 100%; height: auto }
|
|
2156
|
+
.notes a { color: #0066cc; text-decoration: none }
|
|
2157
|
+
.notes .goto { color: #0066cc }
|
|
2158
|
+
.none { color: #86868b; font-style: italic }
|
|
2159
|
+
</style></head><body>
|
|
2160
|
+
${h.slides.map((s, i) => `<section class="slide"><figure class="pic">${s.picture ? `<img src="${esc(pictureUrl(i))}" alt="${esc(s.title)}">` : ""}<figcaption class="n">${i + 1} / ${h.slides.length}</figcaption></figure><div class="side"><h2>${esc(s.title)}</h2>${s.html ? `<div class="notes">${s.html}</div>` : "<p class=\"none\">No notes</p>"}</div></section>`).join("\n")}
|
|
2161
|
+
</body></html>`;
|
|
2162
|
+
}
|
|
2163
|
+
/** md.ts writes a `goto:` link as `<a href="#" data-goto="...">`: on paper it is its text. */
|
|
2164
|
+
const unlinkGotos = (html) => html.replace(/<a href="#" data-goto="[^"]*">([\s\S]*?)<\/a>/g, "<span class=\"goto\">$1</span>");
|
|
2165
|
+
async function printHandout(b, ctx, job, slides) {
|
|
2166
|
+
const { renderMarkdown } = await import("./md-B9_13Q0R.mjs");
|
|
2167
|
+
if (!jobDirReal(ctx.root, job.dir)) throw new Error("the job folder is no longer a folder of this project - export again");
|
|
2168
|
+
slides.forEach((s, i) => {
|
|
2169
|
+
if (s.picture) writeFileSync(join(job.dir, `${i}.jpg`), s.picture);
|
|
2170
|
+
});
|
|
2171
|
+
handouts.set(job.id, {
|
|
2172
|
+
title: `${job.board.replace(/-/g, " ")} - notes`,
|
|
2173
|
+
canvas: ctx.canvasName,
|
|
2174
|
+
paper: job.ask.paper ?? "letter",
|
|
2175
|
+
slides: slides.map((s, i) => ({
|
|
2176
|
+
title: s.page.title,
|
|
2177
|
+
...s.picture ? { picture: `${i}.jpg` } : {},
|
|
2178
|
+
html: s.note ? unlinkGotos(renderMarkdown(s.note)) : ""
|
|
2179
|
+
}))
|
|
2180
|
+
});
|
|
2181
|
+
const owner = {};
|
|
2182
|
+
let targetId;
|
|
2183
|
+
try {
|
|
2184
|
+
targetId = (await b.send("Target.createTarget", { url: "about:blank" }, void 0, owner)).targetId;
|
|
2185
|
+
const sid = (await b.send("Target.attachToTarget", {
|
|
2186
|
+
targetId,
|
|
2187
|
+
flatten: true
|
|
2188
|
+
}, void 0, owner)).sessionId;
|
|
2189
|
+
const send = (m, p = {}) => b.send(m, p, sid, owner);
|
|
2190
|
+
const { readDevInfo } = await import("./work-B4tydWnf.mjs").then((n) => n.c);
|
|
2191
|
+
const token = readDevInfo(ctx.root)?.token;
|
|
2192
|
+
if (!token) throw new Error("marver dev has no session token (design/.local/dev.json) - restart it");
|
|
2193
|
+
await send("Network.enable");
|
|
2194
|
+
await send("Network.setExtraHTTPHeaders", { headers: { "x-mv-work": token } });
|
|
2195
|
+
await send("Page.enable");
|
|
2196
|
+
await send("Page.navigate", { url: `${ctx.origin}${ROUTE}/handout/?job=${job.id}` });
|
|
2197
|
+
for (const by = Date.now() + 3e4; Date.now() < by;) {
|
|
2198
|
+
if ((await send("Runtime.evaluate", {
|
|
2199
|
+
expression: `document.readyState === 'complete' && Array.from(document.images).every((i) => i.complete)`,
|
|
2200
|
+
returnByValue: true
|
|
2201
|
+
})).result?.value === true) break;
|
|
2202
|
+
await wait(100);
|
|
2203
|
+
}
|
|
2204
|
+
await send("Runtime.evaluate", {
|
|
2205
|
+
expression: "document.fonts.ready.then(() => true)",
|
|
2206
|
+
awaitPromise: true,
|
|
2207
|
+
returnByValue: true
|
|
2208
|
+
});
|
|
2209
|
+
const p = PAPER[job.ask.paper ?? "letter"];
|
|
2210
|
+
const pr = await send("Page.printToPDF", {
|
|
2211
|
+
paperWidth: p.w,
|
|
2212
|
+
paperHeight: p.h,
|
|
2213
|
+
marginTop: .45,
|
|
2214
|
+
marginBottom: .6,
|
|
2215
|
+
marginLeft: .5,
|
|
2216
|
+
marginRight: .5,
|
|
2217
|
+
printBackground: true,
|
|
2218
|
+
preferCSSPageSize: true,
|
|
2219
|
+
displayHeaderFooter: true,
|
|
2220
|
+
headerTemplate: "<span></span>",
|
|
2221
|
+
footerTemplate: `<div style="width:100%;font:8px -apple-system,Helvetica,Arial,sans-serif;color:#86868b;padding:0 0.5in;display:flex;justify-content:space-between"><span>${esc(ctx.canvasName)} · ${esc(job.board)}</span><span><span class="pageNumber"></span> / <span class="totalPages"></span></span></div>`,
|
|
2222
|
+
generateDocumentOutline: true,
|
|
2223
|
+
generateTaggedPDF: true,
|
|
2224
|
+
transferMode: "ReturnAsBase64"
|
|
2225
|
+
});
|
|
2226
|
+
const doc = await PDFDocument.load(Buffer.from(String(pr.data), "base64"), { updateMetadata: false });
|
|
2227
|
+
doc.setTitle(`${job.board.replace(/-/g, " ")} - notes`, { showInWindowTitleBar: true });
|
|
2228
|
+
doc.setAuthor(ctx.canvasName);
|
|
2229
|
+
doc.setCreator(`Marver ${ctx.version}`);
|
|
2230
|
+
doc.setProducer(`Marver ${ctx.version} (Chrome, pdf-lib)`);
|
|
2231
|
+
return {
|
|
2232
|
+
pdf: await doc.save(),
|
|
2233
|
+
pages: doc.getPageCount()
|
|
2234
|
+
};
|
|
2235
|
+
} finally {
|
|
2236
|
+
handouts.delete(job.id);
|
|
2237
|
+
if (targetId && !b.dead) await b.send("Target.closeTarget", { targetId }).catch(() => {});
|
|
2238
|
+
b.abort(owner, "the handout finished");
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
/** The handout's gate: the canvas's dev token (the renderer's tab sends it on every request), as the CLI's routes. */
|
|
2242
|
+
function handoutAllowed(headers, root) {
|
|
2243
|
+
const token = readDevToken(root);
|
|
2244
|
+
return !!token && headers["x-mv-work"] === token;
|
|
2245
|
+
}
|
|
2246
|
+
const readDevToken = (root) => {
|
|
2247
|
+
try {
|
|
2248
|
+
const t = JSON.parse(readFileSync(join(root, "design", ".local", "dev.json"), "utf8")).token;
|
|
2249
|
+
return typeof t === "string" && t ? t : null;
|
|
2250
|
+
} catch {
|
|
2251
|
+
return null;
|
|
2252
|
+
}
|
|
2253
|
+
};
|
|
2254
|
+
/** `/__mv/handout/?job=` and its pictures: served only while that job's handout prints, to its own browser. */
|
|
2255
|
+
function handoutMiddleware() {
|
|
2256
|
+
return (req, res, next) => {
|
|
2257
|
+
const url = new URL(req.url ?? "/", "http://x");
|
|
2258
|
+
if (!url.pathname.startsWith(`/__mv/handout/`)) return next();
|
|
2259
|
+
const job = url.searchParams.get("job") ?? "";
|
|
2260
|
+
const h = JOB_ID.test(job) ? handouts.get(job) : void 0;
|
|
2261
|
+
const j = h ? jobs.get(job) : void 0;
|
|
2262
|
+
if (!h || !j || req.method !== "GET") {
|
|
2263
|
+
res.statusCode = 404;
|
|
2264
|
+
return res.end("not found");
|
|
2265
|
+
}
|
|
2266
|
+
if (!handoutAllowed(req.headers ?? {}, j.root)) {
|
|
2267
|
+
res.statusCode = 403;
|
|
2268
|
+
return res.end("forbidden");
|
|
2269
|
+
}
|
|
2270
|
+
res.setHeader("cache-control", "no-store");
|
|
2271
|
+
res.setHeader("x-content-type-options", "nosniff");
|
|
2272
|
+
const pic = /^\/handout\/(\d{1,3})\.jpg$/.exec(url.pathname.slice(ROUTE.length));
|
|
2273
|
+
if (pic) {
|
|
2274
|
+
const n = Number(pic[1]);
|
|
2275
|
+
if (!h.slides[n]?.picture) {
|
|
2276
|
+
res.statusCode = 404;
|
|
2277
|
+
return res.end("not found");
|
|
2278
|
+
}
|
|
2279
|
+
try {
|
|
2280
|
+
const buf = readFileSync(join(j.dir, `${n}.jpg`));
|
|
2281
|
+
res.setHeader("content-type", "image/jpeg");
|
|
2282
|
+
res.setHeader("content-length", buf.length);
|
|
2283
|
+
return res.end(buf);
|
|
2284
|
+
} catch {
|
|
2285
|
+
res.statusCode = 404;
|
|
2286
|
+
return res.end("not found");
|
|
2287
|
+
}
|
|
2288
|
+
}
|
|
2289
|
+
if (url.pathname !== `/__mv/handout/`) {
|
|
2290
|
+
res.statusCode = 404;
|
|
2291
|
+
return res.end("not found");
|
|
2292
|
+
}
|
|
2293
|
+
res.setHeader("content-type", "text/html; charset=utf-8");
|
|
2294
|
+
res.setHeader("content-security-policy", "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; font-src 'self' data:");
|
|
2295
|
+
return res.end(handoutHtml(h, (n) => `${ROUTE}/handout/${n}.jpg?job=${job}`));
|
|
2296
|
+
};
|
|
2297
|
+
}
|
|
2298
|
+
//#endregion
|
|
2299
|
+
export { cancelPdfJob, getJob, handoutMiddleware, jobStatus, startPdfJob };
|