@particle-academy/last-word-ui 0.1.1 → 0.3.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/dist/index.cjs CHANGED
@@ -4,56 +4,9 @@ var react = require('react');
4
4
  var reactFancy = require('@particle-academy/react-fancy');
5
5
  var jsxRuntime = require('react/jsx-runtime');
6
6
 
7
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
7
8
  // src/DocViewer.tsx
8
9
 
9
- // src/footnotes.ts
10
- function numberFootnotes(doc) {
11
- const marks = /* @__PURE__ */ new Map();
12
- const notes = [];
13
- const runs = (list) => {
14
- if (!Array.isArray(list)) return;
15
- for (const run of list) {
16
- const fn = run?.footnote;
17
- if (fn && typeof fn === "object" && Array.isArray(fn.blocks)) {
18
- const id = notes.length + 1;
19
- marks.set(run, id);
20
- notes.push({ id, footnote: fn });
21
- }
22
- }
23
- };
24
- const items = (list) => {
25
- if (!Array.isArray(list)) return;
26
- for (const item of list) {
27
- runs(item?.runs);
28
- items(item?.children);
29
- }
30
- };
31
- const blocks = (list) => {
32
- if (!Array.isArray(list)) return;
33
- for (const block of list) {
34
- switch (block?.type) {
35
- case "heading":
36
- case "paragraph":
37
- runs(block.runs);
38
- break;
39
- case "list":
40
- items(block.items);
41
- break;
42
- case "quote":
43
- blocks(block.blocks);
44
- break;
45
- case "table":
46
- for (const row of Array.isArray(block.rows) ? block.rows : []) {
47
- for (const cell of Array.isArray(row?.cells) ? row.cells : []) blocks(cell?.blocks);
48
- }
49
- break;
50
- }
51
- }
52
- };
53
- blocks(doc.blocks);
54
- return { marks, notes };
55
- }
56
-
57
10
  // src/geometry.ts
58
11
  var PAGE_SIZES_PT = {
59
12
  letter: [612, 792],
@@ -101,6 +54,343 @@ function bodyBox(g, headerHeight, footerHeight) {
101
54
  return { top, bottom, height: Math.max(1, g.height - top - bottom) };
102
55
  }
103
56
 
57
+ // src/fields.ts
58
+ var FIELD = /\{(?:(page|pages|section|sectionpages|author|title|filename)|(date|time)(?::([^{}"\\]+))?)\}/g;
59
+ var str = (v) => typeof v === "string" ? v : "";
60
+ function substituteFields(text, fields) {
61
+ return text.replace(FIELD, (_m, name, dt, format) => {
62
+ switch (name) {
63
+ case "page":
64
+ return String(fields.page);
65
+ case "pages":
66
+ return String(fields.pages);
67
+ case "section":
68
+ return String(fields.section ?? 1);
69
+ case "sectionpages":
70
+ return String(fields.sectionPages ?? fields.pages);
71
+ case "author":
72
+ return str(fields.author);
73
+ case "title":
74
+ return str(fields.title);
75
+ case "filename":
76
+ return str(fields.filename);
77
+ }
78
+ const now = fields.now instanceof Date && Number.isFinite(fields.now.getTime()) ? fields.now : /* @__PURE__ */ new Date();
79
+ if (format !== void 0) return formatDatePicture(now, format);
80
+ return dt === "time" ? now.toLocaleTimeString() : now.toLocaleDateString();
81
+ });
82
+ }
83
+ function resolveNow(now) {
84
+ if (now instanceof Date) return Number.isFinite(now.getTime()) ? new Date(now.getTime()) : /* @__PURE__ */ new Date();
85
+ if (typeof now === "string") {
86
+ const d = new Date(now);
87
+ if (Number.isFinite(d.getTime())) return d;
88
+ }
89
+ return /* @__PURE__ */ new Date();
90
+ }
91
+ var MONTHS = [
92
+ "January",
93
+ "February",
94
+ "March",
95
+ "April",
96
+ "May",
97
+ "June",
98
+ "July",
99
+ "August",
100
+ "September",
101
+ "October",
102
+ "November",
103
+ "December"
104
+ ];
105
+ var DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
106
+ var PICTURE = [
107
+ "AM/PM",
108
+ "am/pm",
109
+ "dddd",
110
+ "MMMM",
111
+ "yyyy",
112
+ "ddd",
113
+ "MMM",
114
+ "dd",
115
+ "MM",
116
+ "yy",
117
+ "HH",
118
+ "hh",
119
+ "mm",
120
+ "ss",
121
+ "d",
122
+ "M",
123
+ "H",
124
+ "h",
125
+ "m",
126
+ "s"
127
+ ];
128
+ var two = (n) => String(n).padStart(2, "0");
129
+ function formatDatePicture(date, picture) {
130
+ const h12 = date.getHours() % 12 === 0 ? 12 : date.getHours() % 12;
131
+ const value = (token) => {
132
+ switch (token) {
133
+ case "d":
134
+ return String(date.getDate());
135
+ case "dd":
136
+ return two(date.getDate());
137
+ case "ddd":
138
+ return DAYS[date.getDay()].slice(0, 3);
139
+ case "dddd":
140
+ return DAYS[date.getDay()];
141
+ case "M":
142
+ return String(date.getMonth() + 1);
143
+ case "MM":
144
+ return two(date.getMonth() + 1);
145
+ case "MMM":
146
+ return MONTHS[date.getMonth()].slice(0, 3);
147
+ case "MMMM":
148
+ return MONTHS[date.getMonth()];
149
+ case "yy":
150
+ return two(date.getFullYear() % 100);
151
+ case "yyyy":
152
+ return String(date.getFullYear()).padStart(4, "0");
153
+ case "h":
154
+ return String(h12);
155
+ case "hh":
156
+ return two(h12);
157
+ case "H":
158
+ return String(date.getHours());
159
+ case "HH":
160
+ return two(date.getHours());
161
+ case "m":
162
+ return String(date.getMinutes());
163
+ case "mm":
164
+ return two(date.getMinutes());
165
+ case "s":
166
+ return String(date.getSeconds());
167
+ case "ss":
168
+ return two(date.getSeconds());
169
+ case "am/pm":
170
+ return date.getHours() < 12 ? "am" : "pm";
171
+ case "AM/PM":
172
+ return date.getHours() < 12 ? "AM" : "PM";
173
+ }
174
+ };
175
+ let out = "";
176
+ let i = 0;
177
+ while (i < picture.length) {
178
+ if (picture[i] === "'") {
179
+ const end = picture.indexOf("'", i + 1);
180
+ if (end < 0) {
181
+ out += picture.slice(i + 1);
182
+ break;
183
+ }
184
+ out += picture.slice(i + 1, end);
185
+ i = end + 1;
186
+ continue;
187
+ }
188
+ const token = PICTURE.find((t) => picture.startsWith(t, i));
189
+ if (token) {
190
+ out += value(token);
191
+ i += token.length;
192
+ continue;
193
+ }
194
+ out += picture[i];
195
+ i++;
196
+ }
197
+ return out;
198
+ }
199
+
200
+ // src/image-size.ts
201
+ var DATA_URL = /^data:image\/(png|jpe?g);base64,([A-Za-z0-9+/=\s]+)$/i;
202
+ function decodeHead(b64, bytes) {
203
+ try {
204
+ const take = Math.ceil(bytes / 3) * 4;
205
+ const bin = atob(b64.replace(/\s+/g, "").slice(0, take));
206
+ const out = new Uint8Array(bin.length);
207
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
208
+ return out;
209
+ } catch {
210
+ return null;
211
+ }
212
+ }
213
+ function pngSize(b) {
214
+ if (b.length < 24 || b[0] !== 137 || b[1] !== 80 || b[2] !== 78 || b[3] !== 71) return null;
215
+ const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);
216
+ const width = dv.getUint32(16);
217
+ const height2 = dv.getUint32(20);
218
+ return width > 0 && height2 > 0 ? { width, height: height2 } : null;
219
+ }
220
+ function jpegSize(b) {
221
+ if (b.length < 4 || b[0] !== 255 || b[1] !== 216) return null;
222
+ let i = 2;
223
+ while (i + 9 < b.length) {
224
+ if (b[i] !== 255) return null;
225
+ const marker = b[i + 1];
226
+ const len = b[i + 2] << 8 | b[i + 3];
227
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
228
+ const height2 = b[i + 5] << 8 | b[i + 6];
229
+ const width = b[i + 7] << 8 | b[i + 8];
230
+ return width > 0 && height2 > 0 ? { width, height: height2 } : null;
231
+ }
232
+ i += 2 + len;
233
+ }
234
+ return null;
235
+ }
236
+ function imageSizeFromDataUrl(src) {
237
+ const m = DATA_URL.exec(src);
238
+ if (!m) return null;
239
+ const isPng = m[1].toLowerCase() === "png";
240
+ const head = decodeHead(m[2], isPng ? 32 : 65536);
241
+ if (!head) return null;
242
+ return isPng ? pngSize(head) : jpegSize(head);
243
+ }
244
+ function resolveImageSize(block, maxWidthPx) {
245
+ const intrinsic = imageSizeFromDataUrl(block.src);
246
+ const given = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
247
+ let width = given(block.widthPx);
248
+ let height2 = given(block.heightPx);
249
+ const aspect = intrinsic ? intrinsic.width / intrinsic.height : 1.5;
250
+ if (width === void 0 && height2 === void 0) {
251
+ width = intrinsic?.width ?? 300;
252
+ height2 = intrinsic?.height ?? 200;
253
+ } else if (width === void 0) {
254
+ width = height2 * aspect;
255
+ } else if (height2 === void 0) {
256
+ height2 = width / aspect;
257
+ }
258
+ if (width > maxWidthPx) {
259
+ height2 = height2 * maxWidthPx / width;
260
+ width = maxWidthPx;
261
+ }
262
+ return { width: Math.max(1, Math.round(width)), height: Math.max(1, Math.round(height2)) };
263
+ }
264
+
265
+ // src/links.ts
266
+ var ALLOWED = /* @__PURE__ */ new Set(["http:", "https:", "mailto:", "tel:"]);
267
+ function safeHref(url) {
268
+ if (typeof url !== "string" || url === "") return void 0;
269
+ if (/^#[^\s]*$/.test(url)) return url;
270
+ let parsed;
271
+ try {
272
+ parsed = new URL(url);
273
+ } catch {
274
+ return void 0;
275
+ }
276
+ return ALLOWED.has(parsed.protocol) ? url : void 0;
277
+ }
278
+
279
+ // src/style.ts
280
+ var pt = (n) => `${Math.round(n * 1e3) / 1e3}pt`;
281
+ var px = (n) => `${Math.round(n * 1e3) / 1e3}px`;
282
+ var SINGLE_LINE = 1.17;
283
+ var DEFAULT_LINE_MULTIPLE = 259 / 240;
284
+ var DEFAULT_SPACE_AFTER = 8;
285
+ var DEFAULT_FONT = "Calibri";
286
+ var DEFAULT_SIZE = 11;
287
+ var HEADING_SIZES = [20, 16, 14, 13, 12, 11];
288
+ var HEADER_FILL = "#E7E7E7";
289
+ var CODE_FILL = "#F2F2F2";
290
+ var LINK_COLOR = "#0563C1";
291
+ var QUOTE_COLOR = "#595959";
292
+ var BAND_SIZE = 9;
293
+ var BAND_COLOR = "#6B7280";
294
+ var FOOTNOTE_SIZE = 10;
295
+ var FOOTNOTE_SEPARATOR_PT = 12;
296
+ function hex(v) {
297
+ return typeof v === "string" && /^#[0-9a-fA-F]{6}$/.test(v) ? v : void 0;
298
+ }
299
+ var finite2 = (v) => typeof v === "number" && Number.isFinite(v);
300
+ var num = (v, fallback) => finite2(v) ? v : fallback;
301
+ var FALLBACKS = {
302
+ calibri: 'Carlito, "Segoe UI", Arial, sans-serif',
303
+ cambria: "Caladea, Georgia, serif",
304
+ arial: '"Liberation Sans", Arimo, Helvetica, sans-serif',
305
+ "times new roman": '"Liberation Serif", Tinos, Times, serif',
306
+ "courier new": '"Liberation Mono", Cousine, monospace',
307
+ consolas: '"Liberation Mono", Menlo, monospace'
308
+ };
309
+ var CARLITO_FAMILY = "LW Carlito";
310
+ function fontStack(name) {
311
+ const clean2 = typeof name === "string" ? name.replace(/[^A-Za-z0-9 _-]/g, "").trim() : "";
312
+ const font = clean2 === "" ? DEFAULT_FONT : clean2;
313
+ const fallback = FALLBACKS[font.toLowerCase()] ?? 'Carlito, "Segoe UI", Arial, sans-serif';
314
+ const first = font.toLowerCase() === "calibri" ? `"${CARLITO_FAMILY}", ` : "";
315
+ return `${first}"${font}", ${fallback}`;
316
+ }
317
+ function typography(defaultFont, size) {
318
+ return {
319
+ fontFamily: fontStack(defaultFont),
320
+ fontSize: pt(size),
321
+ lineHeight: SINGLE_LINE,
322
+ color: "#000000",
323
+ textAlign: "left",
324
+ fontKerning: "none",
325
+ fontVariantLigatures: "none",
326
+ textRendering: "geometricPrecision"
327
+ };
328
+ }
329
+ var MONO = fontStack("Consolas");
330
+ var CSS_STYLE = {
331
+ single: "solid",
332
+ double: "double",
333
+ dashed: "dashed",
334
+ dotted: "dotted"
335
+ };
336
+ function borderCss(b) {
337
+ if (!b || typeof b !== "object") return void 0;
338
+ const style = CSS_STYLE[b.style ?? "single"];
339
+ if (!style) return "none";
340
+ const width = Math.max(style === "double" ? 2.25 : 0.25, num(b.width, 0.5));
341
+ return `${pt(width)} ${style} ${hex(b.color) ?? "#000000"}`;
342
+ }
343
+ function paragraphStyle(p, size) {
344
+ const s = {
345
+ margin: 0,
346
+ marginLeft: pt(num(p.indentLeft, 0)),
347
+ marginRight: pt(num(p.indentRight, 0)),
348
+ fontSize: pt(size),
349
+ lineHeight: num(p.lineHeight, DEFAULT_LINE_MULTIPLE) * SINGLE_LINE,
350
+ color: "inherit",
351
+ fontWeight: "inherit",
352
+ whiteSpace: "pre-wrap",
353
+ overflowWrap: "break-word"
354
+ };
355
+ if (p.align === "left" || p.align === "center" || p.align === "right" || p.align === "justify") s.textAlign = p.align;
356
+ const fill = hex(p.shading);
357
+ if (fill) s.backgroundColor = fill;
358
+ Object.assign(s, boxBorders(p.borders));
359
+ return s;
360
+ }
361
+ function boxBorders(b) {
362
+ if (!b || typeof b !== "object") return {};
363
+ const s = {};
364
+ const top = borderCss(b.top);
365
+ const right = borderCss(b.right);
366
+ const bottom = borderCss(b.bottom);
367
+ const left = borderCss(b.left);
368
+ if (top) {
369
+ s.borderTop = top;
370
+ if (top !== "none") s.paddingTop = pt(1);
371
+ }
372
+ if (bottom) {
373
+ s.borderBottom = bottom;
374
+ if (bottom !== "none") s.paddingBottom = pt(1);
375
+ }
376
+ if (left) {
377
+ s.borderLeft = left;
378
+ if (left !== "none") s.paddingLeft = pt(4);
379
+ }
380
+ if (right) {
381
+ s.borderRight = right;
382
+ if (right !== "none") s.paddingRight = pt(4);
383
+ }
384
+ return s;
385
+ }
386
+ function spacingStyle(p, defaultAfter, defaultBefore = 0) {
387
+ return {
388
+ display: "flow-root",
389
+ paddingTop: pt(Math.max(0, num(p.spaceBefore, defaultBefore))),
390
+ paddingBottom: pt(Math.max(0, num(p.spaceAfter, defaultAfter)))
391
+ };
392
+ }
393
+
104
394
  // src/table-grid.ts
105
395
  var span = (v) => typeof v === "number" && Number.isInteger(v) && v > 1 ? v : 1;
106
396
  function tableGrid(rows) {
@@ -137,781 +427,784 @@ function columnPercents(colCount, widths) {
137
427
  if (total <= 0) return even;
138
428
  return w.map((x) => Math.round(x / total * 100 * 1e6) / 1e6);
139
429
  }
140
-
141
- // src/measure.ts
142
- var SPLITTABLE = /* @__PURE__ */ new Set(["paragraph", "heading", "list", "quote", "code"]);
143
- var blockId = (index) => `b${index}`;
144
- function height(el) {
145
- return el ? el.getBoundingClientRect().height : 0;
146
- }
147
- function lineBreakpoints(el) {
148
- if (typeof document === "undefined" || typeof document.createRange !== "function") return [];
149
- const top = el.getBoundingClientRect().top;
150
- const total = el.getBoundingClientRect().height;
151
- const range = document.createRange();
152
- if (typeof range.getClientRects !== "function") return [];
153
- const spans = [];
154
- const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
155
- for (let node = walker.nextNode(); node; node = walker.nextNode()) {
156
- if (!node.nodeValue) continue;
157
- range.selectNodeContents(node);
158
- for (const r of Array.from(range.getClientRects())) {
159
- if (r.height > 0) spans.push([r.top - top, r.bottom - top]);
160
- }
430
+ var EMPTY_MARKS = /* @__PURE__ */ new Map();
431
+ var ZWSP = String.fromCharCode(8203);
432
+ var RenderCtx = react.createContext({
433
+ marks: EMPTY_MARKS,
434
+ size: 11,
435
+ spaceAfter: DEFAULT_SPACE_AFTER,
436
+ contentWidth: 468
437
+ });
438
+ function WithContext({ value, children }) {
439
+ const parent = react.useContext(RenderCtx);
440
+ return /* @__PURE__ */ jsxRuntime.jsx(RenderCtx.Provider, { value: { ...parent, ...value }, children });
441
+ }
442
+ function RunView({ run }) {
443
+ const ctx = react.useContext(RenderCtx);
444
+ const mark = ctx.marks.get(run);
445
+ let text = typeof run.text === "string" ? run.text : "";
446
+ if (ctx.fields) text = substituteFields(text, ctx.fields);
447
+ const s = {};
448
+ if (run.bold || ctx.bold) s.fontWeight = 700;
449
+ if (run.italic) s.fontStyle = "italic";
450
+ const deco = [run.underline ? "underline" : "", run.strike ? "line-through" : ""].filter(Boolean).join(" ");
451
+ if (run.smallCaps) s.fontVariant = "small-caps";
452
+ if (typeof run.size === "number" && run.size > 0) s.fontSize = pt(run.size);
453
+ if (typeof run.font === "string" && run.font !== "") s.fontFamily = fontStack(run.font);
454
+ if (typeof run.letterSpacing === "number" && Number.isFinite(run.letterSpacing)) s.letterSpacing = pt(run.letterSpacing);
455
+ if (run.code) {
456
+ s.fontFamily = MONO;
457
+ s.backgroundColor = CODE_FILL;
161
458
  }
162
- spans.sort((a, b) => a[0] - b[0]);
163
- const lines = [];
164
- for (const s of spans) {
165
- const last = lines[lines.length - 1];
166
- if (last && s[0] < last[1] - 0.5) last[1] = Math.max(last[1], s[1]);
167
- else lines.push([s[0], s[1]]);
459
+ const highlight = hex(run.highlight);
460
+ if (highlight) s.backgroundColor = highlight;
461
+ const color = hex(run.color);
462
+ if (color) s.color = color;
463
+ const href = safeHref(run.link);
464
+ let body = text;
465
+ if (href) {
466
+ body = /* @__PURE__ */ jsxRuntime.jsx(
467
+ "a",
468
+ {
469
+ href,
470
+ target: "_blank",
471
+ rel: "noopener noreferrer",
472
+ style: { color: color ?? LINK_COLOR, textDecoration: "underline" },
473
+ children: text
474
+ }
475
+ );
476
+ } else if (deco) {
477
+ s.textDecoration = deco;
168
478
  }
169
- return lines.slice(0, -1).map((l) => l[1]).filter((b) => b > 0 && b < total - 0.5);
479
+ if (href && deco.includes("line-through")) s.textDecoration = "line-through";
480
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
481
+ text !== "" && /* @__PURE__ */ jsxRuntime.jsx("span", { style: s, children: body }),
482
+ mark !== void 0 && /* @__PURE__ */ jsxRuntime.jsx("sup", { "data-lw-footnote-ref": mark, style: { fontSize: "0.65em", lineHeight: 0 }, children: mark })
483
+ ] });
170
484
  }
171
- function measure(root, blocks) {
172
- const noteHeights = /* @__PURE__ */ new Map();
173
- root.querySelectorAll("[data-lw-measure-footnote]").forEach((el) => {
174
- noteHeights.set(Number(el.dataset.lwMeasureFootnote), height(el));
175
- });
176
- const marksIn = (el) => Array.from(el.querySelectorAll("[data-lw-footnote-ref]")).map((m) => {
177
- const id = Number(m.dataset.lwFootnoteRef);
178
- return { id, el: m, height: noteHeights.get(id) ?? 0 };
179
- });
180
- const items = blocks.map((block, i) => {
181
- if (block?.type === "pageBreak") return { type: "break" };
182
- const wrap = root.querySelector(`[data-lw-measure-block="${i}"]`);
183
- if (!wrap) return { type: "block", id: blockId(i), height: 0 };
184
- if (block.type === "table") {
185
- const grid = tableGrid(Array.isArray(block.rows) ? block.rows : []);
186
- const rows = Array.from(wrap.querySelectorAll("tr[data-lw-row]")).map((tr) => {
187
- const r = Number(tr.dataset.lwRow);
188
- const notes2 = marksIn(tr).map(({ id, height: h2 }) => ({ id, height: h2 }));
189
- return {
190
- height: height(tr),
191
- ...grid.joinPrevious[r] ? { joinPrevious: true } : {},
192
- ...notes2.length ? { footnotes: notes2 } : {}
193
- };
194
- });
195
- return { type: "table", id: blockId(i), rows, headerRows: grid.headerRows };
485
+ function Runs({ runs }) {
486
+ const list = Array.isArray(runs) ? runs : [];
487
+ const visible = list.some((r) => typeof r?.text === "string" && r.text !== "" || r?.footnote);
488
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
489
+ list.map((run, i) => run && typeof run === "object" ? /* @__PURE__ */ jsxRuntime.jsx(RunView, { run }, i) : null),
490
+ !visible && ZWSP
491
+ ] });
492
+ }
493
+ function BlockView({ block }) {
494
+ const ctx = react.useContext(RenderCtx);
495
+ switch (block?.type) {
496
+ case "paragraph":
497
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "paragraph", style: spacingStyle(block, ctx.spaceAfter), children: /* @__PURE__ */ jsxRuntime.jsx(reactFancy.Text, { as: "p", style: paragraphStyle(block, ctx.size), children: /* @__PURE__ */ jsxRuntime.jsx(Runs, { runs: block.runs }) }) });
498
+ case "heading": {
499
+ const level = [1, 2, 3, 4, 5, 6].includes(block.level) ? block.level : 1;
500
+ const Tag = `h${level}`;
501
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "heading", style: spacingStyle(block, 6, 12), children: /* @__PURE__ */ jsxRuntime.jsx(reactFancy.Heading, { as: Tag, weight: "bold", style: { ...paragraphStyle(block, HEADING_SIZES[level - 1]), fontWeight: 700 }, children: /* @__PURE__ */ jsxRuntime.jsx(Runs, { runs: block.runs }) }) });
502
+ }
503
+ case "list":
504
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "list", style: { display: "flow-root" }, children: /* @__PURE__ */ jsxRuntime.jsx(ListLevel, { items: block.items, ordered: block.ordered === true }) });
505
+ case "table":
506
+ return /* @__PURE__ */ jsxRuntime.jsx(TableView, { block });
507
+ case "code":
508
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "code", style: { display: "flow-root" }, children: /* @__PURE__ */ jsxRuntime.jsx(
509
+ reactFancy.Text,
510
+ {
511
+ as: "div",
512
+ style: {
513
+ margin: 0,
514
+ fontFamily: MONO,
515
+ fontSize: pt(10),
516
+ lineHeight: SINGLE_LINE,
517
+ backgroundColor: CODE_FILL,
518
+ color: "inherit",
519
+ whiteSpace: "pre-wrap",
520
+ overflowWrap: "break-word"
521
+ },
522
+ children: typeof block.text === "string" && block.text !== "" ? block.text : ZWSP
523
+ }
524
+ ) });
525
+ case "quote":
526
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "quote", style: { display: "flow-root", marginLeft: pt(36), fontStyle: "italic", color: QUOTE_COLOR }, children: /* @__PURE__ */ jsxRuntime.jsx(WithContext, { value: { contentWidth: ctx.contentWidth - 36 }, children: (Array.isArray(block.blocks) ? block.blocks : []).map((b, i) => /* @__PURE__ */ jsxRuntime.jsx(BlockView, { block: b }, i)) }) });
527
+ case "image":
528
+ return /* @__PURE__ */ jsxRuntime.jsx(ImageView, { block });
529
+ case "chart":
530
+ return /* @__PURE__ */ jsxRuntime.jsx(ChartPlaceholder, { block });
531
+ case "hr":
532
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "hr", style: { display: "flow-root", paddingBottom: pt(ctx.spaceAfter) }, children: /* @__PURE__ */ jsxRuntime.jsx("div", { style: { height: pt(ctx.size * SINGLE_LINE), display: "flex", alignItems: "flex-end" }, children: /* @__PURE__ */ jsxRuntime.jsx(reactFancy.Separator, { className: "w-full" }) }) });
533
+ case "pageBreak":
534
+ return null;
535
+ default:
536
+ return null;
537
+ }
538
+ }
539
+ function ListLevel({ items, ordered }) {
540
+ const ctx = react.useContext(RenderCtx);
541
+ const list = Array.isArray(items) ? items : [];
542
+ const style = {
543
+ margin: 0,
544
+ paddingLeft: pt(36),
545
+ listStyleType: ordered ? "decimal" : "disc",
546
+ fontSize: pt(ctx.size)
547
+ };
548
+ const children = list.map((item, i) => /* @__PURE__ */ jsxRuntime.jsxs("li", { style: { paddingLeft: pt(0) }, children: [
549
+ /* @__PURE__ */ jsxRuntime.jsx("div", { style: spacingStyle(item, ctx.spaceAfter), children: /* @__PURE__ */ jsxRuntime.jsx(reactFancy.Text, { as: "div", style: paragraphStyle({ ...item, indentLeft: 0 }, ctx.size), children: /* @__PURE__ */ jsxRuntime.jsx(Runs, { runs: item?.runs }) }) }),
550
+ Array.isArray(item?.children) && item.children.length > 0 && /* @__PURE__ */ jsxRuntime.jsx(ListLevel, { items: item.children, ordered })
551
+ ] }, i));
552
+ return ordered ? /* @__PURE__ */ jsxRuntime.jsx("ol", { style, children }) : /* @__PURE__ */ jsxRuntime.jsx("ul", { style, children });
553
+ }
554
+ var IMAGE_SRC = /^data:image\/(png|jpe?g|gif|webp|bmp);base64,/i;
555
+ function ImageView({ block }) {
556
+ const ctx = react.useContext(RenderCtx);
557
+ const maxPx = ctx.contentWidth * PX_PER_PT;
558
+ const size = resolveImageSize({ src: String(block.src ?? ""), widthPx: block.widthPx, heightPx: block.heightPx }, maxPx);
559
+ const src = typeof block.src === "string" && IMAGE_SRC.test(block.src) ? block.src : null;
560
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "image", style: { display: "flow-root", paddingBottom: pt(ctx.spaceAfter) }, children: src ? /* @__PURE__ */ jsxRuntime.jsx(
561
+ reactFancy.ImageViewer,
562
+ {
563
+ src,
564
+ alt: typeof block.alt === "string" ? block.alt : "",
565
+ fit: "contain",
566
+ zoomable: false,
567
+ pannable: false,
568
+ controls: false,
569
+ checkerboard: false,
570
+ className: "rounded-none bg-transparent dark:bg-transparent",
571
+ style: { width: size.width, height: size.height, background: "transparent", borderRadius: 0 }
572
+ }
573
+ ) : /* @__PURE__ */ jsxRuntime.jsx(
574
+ "div",
575
+ {
576
+ "data-lw-image-missing": "",
577
+ style: { width: size.width, height: size.height, border: "0.75pt dashed #9CA3AF", color: "#6B7280", fontSize: pt(9), padding: pt(4), boxSizing: "border-box" },
578
+ children: typeof block.alt === "string" && block.alt !== "" ? block.alt : "Image"
579
+ }
580
+ ) });
581
+ }
582
+ function ChartPlaceholder({ block }) {
583
+ const ctx = react.useContext(RenderCtx);
584
+ const maxPx = ctx.contentWidth * PX_PER_PT;
585
+ const width = Math.min(
586
+ maxPx,
587
+ num(block.widthPx, typeof block.width === "number" && block.width > 0 ? maxPx * Math.min(100, block.width) / 100 : maxPx)
588
+ );
589
+ const height2 = num(block.heightPx, width * 0.6);
590
+ const option = block.option ?? {};
591
+ const title = typeof option.title === "string" ? option.title : option.title && typeof option.title.text === "string" ? option.title.text : typeof block.alt === "string" ? block.alt : "";
592
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "chart", style: { display: "flow-root", paddingBottom: pt(ctx.spaceAfter) }, children: /* @__PURE__ */ jsxRuntime.jsx(
593
+ "div",
594
+ {
595
+ "data-lw-chart-placeholder": "",
596
+ style: {
597
+ width,
598
+ height: height2,
599
+ border: "0.75pt dashed #9CA3AF",
600
+ color: "#6B7280",
601
+ fontSize: pt(9),
602
+ display: "flex",
603
+ alignItems: "center",
604
+ justifyContent: "center",
605
+ boxSizing: "border-box"
606
+ },
607
+ children: title ? `Chart: ${title}` : "Chart"
608
+ }
609
+ ) });
610
+ }
611
+ var DEFAULT_TABLE_BORDER = { style: "single", width: 0.5 };
612
+ var DEFAULT_CELL_PADDING = { top: 3, right: 5.4, bottom: 3, left: 5.4 };
613
+ var WORD_CELL_PADDING = { top: 0, right: 5.4, bottom: 0, left: 5.4 };
614
+ function sides(base, over) {
615
+ if (!over || typeof over !== "object") return base;
616
+ const o = over;
617
+ return {
618
+ top: num(o.top, base.top),
619
+ right: num(o.right, base.right),
620
+ bottom: num(o.bottom, base.bottom),
621
+ left: num(o.left, base.left)
622
+ };
623
+ }
624
+ function TableView({ block, rows }) {
625
+ const ctx = react.useContext(RenderCtx);
626
+ const all = Array.isArray(block.rows) ? block.rows : [];
627
+ const grid = tableGrid(all);
628
+ const pct = columnPercents(grid.colCount, block.widths);
629
+ const tb = block.borders && typeof block.borders === "object" ? block.borders : {
630
+ top: DEFAULT_TABLE_BORDER,
631
+ right: DEFAULT_TABLE_BORDER,
632
+ bottom: DEFAULT_TABLE_BORDER,
633
+ left: DEFAULT_TABLE_BORDER,
634
+ insideH: DEFAULT_TABLE_BORDER,
635
+ insideV: DEFAULT_TABLE_BORDER
636
+ };
637
+ const basePad = block.cellPadding && typeof block.cellPadding === "object" ? sides(WORD_CELL_PADDING, block.cellPadding) : DEFAULT_CELL_PADDING;
638
+ const widthPct = typeof block.width === "number" && block.width > 0 ? Math.min(100, block.width) : 100;
639
+ const show = rows ?? all.map((_, i) => i);
640
+ return /* @__PURE__ */ jsxRuntime.jsx(
641
+ "div",
642
+ {
643
+ "data-lw-kind": "table",
644
+ style: {
645
+ width: `${widthPct}%`,
646
+ marginLeft: block.align === "center" || block.align === "right" ? "auto" : void 0,
647
+ marginRight: block.align === "center" ? "auto" : void 0
648
+ },
649
+ children: /* @__PURE__ */ jsxRuntime.jsx(reactFancy.Table, { "data-lw-table": "", className: "rounded-none border-0 overflow-visible", children: /* @__PURE__ */ jsxRuntime.jsxs(reactFancy.Table.Body, { className: "divide-y-0", children: [
650
+ /* @__PURE__ */ jsxRuntime.jsx("tr", { "data-lw-sizer": "", "aria-hidden": "true", children: pct.map((p, i) => /* @__PURE__ */ jsxRuntime.jsx("td", { style: { width: `${p}%`, padding: 0, border: "none", height: 0 } }, i)) }),
651
+ show.map((r) => {
652
+ const row = all[r];
653
+ if (!row) return null;
654
+ const header = row.header === true;
655
+ return /* @__PURE__ */ jsxRuntime.jsx(reactFancy.Table.Row, { "data-lw-row": r, className: "hover:bg-transparent dark:hover:bg-transparent", children: (grid.rows[r] ?? []).map((gc) => {
656
+ const cell = row.cells[gc.cell];
657
+ const cb = cell.borders && typeof cell.borders === "object" ? cell.borders : {};
658
+ const edge = (own, outer, inner, isOuter) => borderCss(own ?? (isOuter ? outer : inner)) ?? "none";
659
+ const pad = sides(basePad, cell.padding);
660
+ const fill = hex(cell.shading) ?? (header ? HEADER_FILL : void 0);
661
+ const style = {
662
+ borderTop: edge(cb.top, tb.top, tb.insideH, gc.row === 0),
663
+ borderBottom: edge(cb.bottom, tb.bottom, tb.insideH, gc.row + gc.rowSpan >= all.length),
664
+ borderLeft: edge(cb.left, tb.left, tb.insideV, gc.col === 0),
665
+ borderRight: edge(cb.right, tb.right, tb.insideV, gc.col + gc.colSpan >= grid.colCount),
666
+ padding: `${pt(pad.top)} ${pt(pad.right)} ${pt(pad.bottom)} ${pt(pad.left)}`,
667
+ verticalAlign: cell.valign === "center" ? "middle" : cell.valign === "bottom" ? "bottom" : "top",
668
+ backgroundColor: fill ?? "transparent",
669
+ color: "inherit",
670
+ fontSize: "inherit",
671
+ fontWeight: "inherit",
672
+ textAlign: "left",
673
+ overflowWrap: "break-word"
674
+ };
675
+ return /* @__PURE__ */ jsxRuntime.jsx(
676
+ reactFancy.Table.Cell,
677
+ {
678
+ header,
679
+ colSpan: gc.colSpan > 1 ? gc.colSpan : void 0,
680
+ rowSpan: gc.rowSpan > 1 ? gc.rowSpan : void 0,
681
+ "data-lw-cell": `${r}:${gc.cell}`,
682
+ style,
683
+ children: /* @__PURE__ */ jsxRuntime.jsx(
684
+ WithContext,
685
+ {
686
+ value: {
687
+ bold: header || ctx.bold,
688
+ contentWidth: ctx.contentWidth * widthPct * (pct.slice(gc.col, gc.col + gc.colSpan).reduce((a, b) => a + b, 0) / 100) / 100
689
+ },
690
+ children: (Array.isArray(cell.blocks) ? cell.blocks : []).map((b, i) => /* @__PURE__ */ jsxRuntime.jsx(BlockView, { block: b }, i))
691
+ }
692
+ )
693
+ },
694
+ gc.cell
695
+ );
696
+ }) }, r);
697
+ })
698
+ ] }) })
699
+ }
700
+ );
701
+ }
702
+ function isBlocksBand(band) {
703
+ return !!band && typeof band === "object" && Array.isArray(band.blocks);
704
+ }
705
+ function hasBand(band) {
706
+ if (isBlocksBand(band)) return band.blocks.length > 0;
707
+ if (!band || typeof band !== "object") return false;
708
+ const b = band;
709
+ return [b.left, b.center, b.right].some((s) => typeof s === "string" && s !== "");
710
+ }
711
+ function BandView({ band }) {
712
+ const ctx = react.useContext(RenderCtx);
713
+ if (isBlocksBand(band)) {
714
+ return /* @__PURE__ */ jsxRuntime.jsx(WithContext, { value: { marks: EMPTY_MARKS }, children: band.blocks.map((b, i) => b?.type === "pageBreak" || b?.type === "chart" ? null : /* @__PURE__ */ jsxRuntime.jsx(BlockView, { block: b }, i)) });
715
+ }
716
+ const slot = (v) => typeof v === "string" ? ctx.fields ? substituteFields(v, ctx.fields) : v : "";
717
+ return /* @__PURE__ */ jsxRuntime.jsxs(
718
+ reactFancy.Text,
719
+ {
720
+ as: "div",
721
+ style: {
722
+ display: "grid",
723
+ gridTemplateColumns: "1fr auto 1fr",
724
+ fontSize: pt(num(band.size, BAND_SIZE)),
725
+ lineHeight: SINGLE_LINE,
726
+ color: hex(band.color) ?? BAND_COLOR,
727
+ whiteSpace: "pre"
728
+ },
729
+ children: [
730
+ /* @__PURE__ */ jsxRuntime.jsx("span", { "data-lw-slot": "left", style: { textAlign: "left" }, children: slot(band.left) }),
731
+ /* @__PURE__ */ jsxRuntime.jsx("span", { "data-lw-slot": "center", style: { textAlign: "center" }, children: slot(band.center) }),
732
+ /* @__PURE__ */ jsxRuntime.jsx("span", { "data-lw-slot": "right", style: { textAlign: "right", justifySelf: "end" }, children: slot(band.right) })
733
+ ]
196
734
  }
197
- const top = wrap.getBoundingClientRect().top;
198
- const h = height(wrap);
199
- let breakpoints = SPLITTABLE.has(block.type) ? lineBreakpoints(wrap) : [];
200
- if (block.type === "paragraph" || block.type === "heading") breakpoints = breakpoints.slice(1, -1);
201
- const notes = marksIn(wrap).map(({ id, el, height: nh }) => {
202
- const r = el.getBoundingClientRect();
203
- return { id, at: Math.min(h, Math.max(0, (r.top + r.bottom) / 2 - top)), height: nh };
204
- });
205
- const keepNext = block.type === "heading" || block.keepNext === true;
206
- return {
207
- type: "block",
208
- id: blockId(i),
209
- height: h,
210
- ...breakpoints.length ? { breakpoints } : {},
211
- ...keepNext ? { keepNext: true } : {},
212
- ...notes.length ? { footnotes: notes } : {}
213
- };
214
- });
215
- return {
216
- items,
217
- headerHeight: height(root.querySelector("[data-lw-measure-header]")),
218
- footerHeight: height(root.querySelector("[data-lw-measure-footer]")),
219
- footnoteSeparator: height(root.querySelector("[data-lw-measure-separator]"))
220
- };
735
+ );
736
+ }
737
+ function FootnoteView({ id, footnote }) {
738
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { "data-footnote": id, style: { display: "flex", gap: pt(3) }, children: [
739
+ /* @__PURE__ */ jsxRuntime.jsx("sup", { style: { fontSize: pt(FOOTNOTE_SIZE * 0.65), lineHeight: 1, paddingTop: pt(2) }, children: id }),
740
+ /* @__PURE__ */ jsxRuntime.jsx("div", { style: { flex: 1, minWidth: 0 }, children: /* @__PURE__ */ jsxRuntime.jsx(WithContext, { value: { marks: EMPTY_MARKS, size: FOOTNOTE_SIZE, spaceAfter: 0 }, children: (Array.isArray(footnote.blocks) ? footnote.blocks : []).map((b, i) => /* @__PURE__ */ jsxRuntime.jsx(BlockView, { block: b }, i)) }) })
741
+ ] });
742
+ }
743
+ function FootnoteSeparator({ height: height2 }) {
744
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-footnote-separator": "", style: { height: height2, display: "flex", alignItems: "center" }, children: /* @__PURE__ */ jsxRuntime.jsx("div", { style: { width: pt(144), borderTop: `${pt(0.5)} solid #000000` } }) });
221
745
  }
222
746
 
223
- // src/paginate.ts
224
- var EPS = 1e-6;
225
- function paginate(items, options) {
226
- const cap = Math.max(1, options.pageHeight);
227
- const sep = Math.max(0, options.footnoteSeparator ?? 0);
228
- const pages = [];
229
- let page;
230
- let content = 0;
231
- let noteHeights = 0;
232
- const newPage = () => {
233
- page = { index: pages.length, fragments: [], footnotes: [], used: 0 };
234
- pages.push(page);
235
- content = 0;
236
- noteHeights = 0;
237
- };
238
- const noteCost = (extraCount, extraHeight) => {
239
- const count = page.footnotes.length + extraCount;
240
- return count > 0 ? noteHeights + extraHeight + sep : 0;
241
- };
242
- const fits = (h, notes) => content + h + noteCost(notes.length, sum(notes)) <= cap + EPS;
243
- const commit = (h, notes) => {
244
- content += h;
245
- for (const n of notes) {
246
- page.footnotes.push(n.id);
247
- noteHeights += n.height;
248
- }
249
- page.used = content + noteCost(0, 0);
747
+ // src/bands.ts
748
+ var BAND_SLOTS = ["default", "first", "even"];
749
+ var VARIANT_KEY = {
750
+ header: { first: "firstHeader", even: "evenHeader" },
751
+ footer: { first: "firstFooter", even: "evenFooter" }
752
+ };
753
+ function pageClass(index) {
754
+ if (index === 0) return "first";
755
+ return index % 2 === 1 ? "even" : "odd";
756
+ }
757
+ var isBandObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
758
+ function slotBand(page, kind, slot) {
759
+ if (!page || typeof page !== "object") return void 0;
760
+ const key = slot === "default" ? kind : VARIANT_KEY[kind][slot];
761
+ const v = page[key];
762
+ return isBandObject(v) ? v : void 0;
763
+ }
764
+ function bandSlot(page, kind, cls) {
765
+ if (cls === "first" && slotBand(page, kind, "first") !== void 0) return "first";
766
+ if (cls === "even" && slotBand(page, kind, "even") !== void 0) return "even";
767
+ return "default";
768
+ }
769
+ function pageBand(page, kind, index) {
770
+ const band = slotBand(page, kind, bandSlot(page, kind, pageClass(index)));
771
+ return hasBand(band) ? band : null;
772
+ }
773
+ function pageBodyBoxes(g, page, heights) {
774
+ const height2 = (kind, cls) => {
775
+ const slot = bandSlot(page, kind, cls);
776
+ return hasBand(slotBand(page, kind, slot)) ? Math.max(0, heights[kind][slot] || 0) : 0;
250
777
  };
251
- const empty = () => page.fragments.length === 0;
252
- newPage();
253
- items.forEach((item, index) => {
254
- if (item.type === "break") {
255
- newPage();
256
- return;
257
- }
258
- if (item.type === "table") {
259
- placeTable(item, index);
260
- return;
261
- }
262
- placeBlock(item, index);
263
- });
264
- return pages;
265
- function notesIn(item, start, end, last) {
266
- const h = Math.max(0, item.height);
267
- return (item.footnotes ?? []).filter((n) => {
268
- const at = Math.min(h, Math.max(0, n.at));
269
- return at >= start - EPS && (last ? at <= end + EPS : at < end - EPS);
270
- });
271
- }
272
- function firstPiece(item) {
273
- if (!item || item.type === "break") return 0;
274
- if (item.type === "block") {
275
- const bp = (item.breakpoints ?? []).find((b) => b > EPS && b < item.height - EPS);
276
- return bp ?? item.height;
277
- }
278
- const header = item.rows.slice(0, headerCount(item)).reduce((a, r) => a + r.height, 0);
279
- const units = tableUnits(item);
280
- return header + (units[0] ? units[0].height : 0);
281
- }
282
- function keepChainHeight(from) {
283
- let total = 0;
284
- let i = from;
285
- while (i < items.length) {
286
- const it = items[i];
287
- if (it.type === "block" && it.keepNext) {
288
- total += it.height;
289
- i++;
290
- continue;
778
+ const box = (cls) => bodyBox(g, height2("header", cls), height2("footer", cls));
779
+ return { first: box("first"), even: box("even"), odd: box("odd") };
780
+ }
781
+
782
+ // src/footnotes.ts
783
+ function numberFootnotes(doc) {
784
+ const marks = /* @__PURE__ */ new Map();
785
+ const notes = [];
786
+ const runs = (list) => {
787
+ if (!Array.isArray(list)) return;
788
+ for (const run of list) {
789
+ const fn = run?.footnote;
790
+ if (fn && typeof fn === "object" && Array.isArray(fn.blocks)) {
791
+ const id = notes.length + 1;
792
+ marks.set(run, id);
793
+ notes.push({ id, footnote: fn });
291
794
  }
292
- total += firstPiece(it);
293
- break;
294
795
  }
295
- return total;
296
- }
297
- function placeBlock(item, index) {
298
- const height2 = Math.max(0, item.height);
299
- if (item.keepNext && !empty()) {
300
- const chain = keepChainHeight(index);
301
- const next = items[index + 1];
302
- const meaningful = next !== void 0 && next.type !== "break";
303
- if (meaningful && chain <= cap + EPS && !fits(chain, notesIn(item, 0, height2, true))) newPage();
796
+ };
797
+ const items = (list) => {
798
+ if (!Array.isArray(list)) return;
799
+ for (const item of list) {
800
+ runs(item?.runs);
801
+ items(item?.children);
304
802
  }
305
- let start = 0;
306
- for (let guard = 0; guard < 1e5; guard++) {
307
- const restNotes = notesIn(item, start, height2, true);
308
- if (fits(height2 - start, restNotes)) {
309
- page.fragments.push({ type: "block", id: item.id, item: index, start, end: height2 });
310
- commit(height2 - start, restNotes);
311
- return;
312
- }
313
- const bps = (item.breakpoints ?? []).filter((b) => b > start + EPS && b < height2 - EPS).sort((a, b) => b - a);
314
- let cut;
315
- for (const bp of bps) {
316
- if (fits(bp - start, notesIn(item, start, bp, false))) {
317
- cut = bp;
803
+ };
804
+ const blocks = (list) => {
805
+ if (!Array.isArray(list)) return;
806
+ for (const block of list) {
807
+ switch (block?.type) {
808
+ case "heading":
809
+ case "paragraph":
810
+ runs(block.runs);
811
+ break;
812
+ case "list":
813
+ items(block.items);
814
+ break;
815
+ case "quote":
816
+ blocks(block.blocks);
817
+ break;
818
+ case "table":
819
+ for (const row of Array.isArray(block.rows) ? block.rows : []) {
820
+ for (const cell of Array.isArray(row?.cells) ? row.cells : []) blocks(cell?.blocks);
821
+ }
318
822
  break;
319
- }
320
- }
321
- if (cut !== void 0) {
322
- page.fragments.push({ type: "block", id: item.id, item: index, start, end: cut });
323
- commit(cut - start, notesIn(item, start, cut, false));
324
- newPage();
325
- start = cut;
326
- continue;
327
- }
328
- if (!empty()) {
329
- newPage();
330
- continue;
331
- }
332
- let room = cap;
333
- let end = Math.min(height2, start + room);
334
- let notes = notesIn(item, start, end, false);
335
- room = cap - noteCost(notes.length, sum(notes));
336
- if (room <= EPS) room = cap;
337
- end = Math.min(height2, start + room);
338
- notes = notesIn(item, start, end, end >= height2 - EPS);
339
- const forced = end < height2 - EPS;
340
- page.fragments.push({ type: "block", id: item.id, item: index, start, end, ...forced ? { forced: true } : {} });
341
- commit(end - start, notes);
342
- if (!forced) return;
343
- newPage();
344
- start = end;
345
- }
346
- }
347
- function headerCount(item) {
348
- return Math.max(0, Math.min(item.headerRows ?? 0, item.rows.length));
349
- }
350
- function tableUnits(item) {
351
- const units = [];
352
- for (let r = headerCount(item); r < item.rows.length; r++) {
353
- const row = item.rows[r];
354
- const last = units[units.length - 1];
355
- if (row.joinPrevious && last) {
356
- last.rows.push(r);
357
- last.height += row.height;
358
- last.notes.push(...row.footnotes ?? []);
359
- } else {
360
- units.push({ rows: [r], height: row.height, notes: [...row.footnotes ?? []] });
361
- }
362
- }
363
- return units;
364
- }
365
- function placeTable(item, index) {
366
- const h = headerCount(item);
367
- const headerIdx = Array.from({ length: h }, (_, i) => i);
368
- const headerHeight = item.rows.slice(0, h).reduce((a, r) => a + r.height, 0);
369
- const headerNotes = item.rows.slice(0, h).flatMap((r) => r.footnotes ?? []);
370
- const units = tableUnits(item);
371
- if (units.length === 0 && h === 0) return;
372
- if (units.length === 0) units.push({ rows: [], height: 0, notes: [] });
373
- let frag = null;
374
- let first = true;
375
- for (let u = 0; u < units.length; ) {
376
- const unit = units[u];
377
- if (frag === null) {
378
- const notes = first ? [...headerNotes, ...unit.notes] : unit.notes;
379
- const need = headerHeight + unit.height;
380
- if (!fits(need, notes) && !empty()) {
381
- newPage();
382
- continue;
383
- }
384
- const overflow = !fits(need, notes);
385
- frag = {
386
- type: "table",
387
- id: item.id,
388
- item: index,
389
- rows: [...headerIdx, ...unit.rows],
390
- repeatedHeader: !first && h > 0,
391
- ...overflow ? { overflow: true } : {}
392
- };
393
- page.fragments.push(frag);
394
- commit(need, notes);
395
- first = false;
396
- u++;
397
- continue;
398
- }
399
- if (fits(unit.height, unit.notes)) {
400
- frag.rows.push(...unit.rows);
401
- commit(unit.height, unit.notes);
402
- u++;
403
- continue;
404
823
  }
405
- newPage();
406
- frag = null;
407
824
  }
408
- }
409
- }
410
- function sum(notes) {
411
- return notes.reduce((a, n) => a + n.height, 0);
412
- }
413
-
414
- // src/fields.ts
415
- var FIELD = /\{page\}|\{pages\}/g;
416
- function substituteFields(text, fields) {
417
- return text.replace(FIELD, (m) => String(m === "{page}" ? fields.page : fields.pages));
825
+ };
826
+ blocks(doc.blocks);
827
+ return { marks, notes };
418
828
  }
419
829
 
420
- // src/image-size.ts
421
- var DATA_URL = /^data:image\/(png|jpe?g);base64,([A-Za-z0-9+/=\s]+)$/i;
422
- function decodeHead(b64, bytes) {
423
- try {
424
- const take = Math.ceil(bytes / 3) * 4;
425
- const bin = atob(b64.replace(/\s+/g, "").slice(0, take));
426
- const out = new Uint8Array(bin.length);
427
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
428
- return out;
429
- } catch {
430
- return null;
431
- }
432
- }
433
- function pngSize(b) {
434
- if (b.length < 24 || b[0] !== 137 || b[1] !== 80 || b[2] !== 78 || b[3] !== 71) return null;
435
- const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);
436
- const width = dv.getUint32(16);
437
- const height2 = dv.getUint32(20);
438
- return width > 0 && height2 > 0 ? { width, height: height2 } : null;
830
+ // src/measure.ts
831
+ var SPLITTABLE = /* @__PURE__ */ new Set(["paragraph", "heading", "list", "quote", "code"]);
832
+ var blockId = (index) => `b${index}`;
833
+ function height(el) {
834
+ return el ? el.getBoundingClientRect().height : 0;
439
835
  }
440
- function jpegSize(b) {
441
- if (b.length < 4 || b[0] !== 255 || b[1] !== 216) return null;
442
- let i = 2;
443
- while (i + 9 < b.length) {
444
- if (b[i] !== 255) return null;
445
- const marker = b[i + 1];
446
- const len = b[i + 2] << 8 | b[i + 3];
447
- if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
448
- const height2 = b[i + 5] << 8 | b[i + 6];
449
- const width = b[i + 7] << 8 | b[i + 8];
450
- return width > 0 && height2 > 0 ? { width, height: height2 } : null;
836
+ function lineBreakpoints(el) {
837
+ if (typeof document === "undefined" || typeof document.createRange !== "function") return [];
838
+ const top = el.getBoundingClientRect().top;
839
+ const total = el.getBoundingClientRect().height;
840
+ const range = document.createRange();
841
+ if (typeof range.getClientRects !== "function") return [];
842
+ const spans = [];
843
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
844
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
845
+ if (!node.nodeValue) continue;
846
+ range.selectNodeContents(node);
847
+ for (const r of Array.from(range.getClientRects())) {
848
+ if (r.height > 0) spans.push([r.top - top, r.bottom - top]);
451
849
  }
452
- i += 2 + len;
453
- }
454
- return null;
455
- }
456
- function imageSizeFromDataUrl(src) {
457
- const m = DATA_URL.exec(src);
458
- if (!m) return null;
459
- const isPng = m[1].toLowerCase() === "png";
460
- const head = decodeHead(m[2], isPng ? 32 : 65536);
461
- if (!head) return null;
462
- return isPng ? pngSize(head) : jpegSize(head);
463
- }
464
- function resolveImageSize(block, maxWidthPx) {
465
- const intrinsic = imageSizeFromDataUrl(block.src);
466
- const given = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
467
- let width = given(block.widthPx);
468
- let height2 = given(block.heightPx);
469
- const aspect = intrinsic ? intrinsic.width / intrinsic.height : 1.5;
470
- if (width === void 0 && height2 === void 0) {
471
- width = intrinsic?.width ?? 300;
472
- height2 = intrinsic?.height ?? 200;
473
- } else if (width === void 0) {
474
- width = height2 * aspect;
475
- } else if (height2 === void 0) {
476
- height2 = width / aspect;
477
850
  }
478
- if (width > maxWidthPx) {
479
- height2 = height2 * maxWidthPx / width;
480
- width = maxWidthPx;
851
+ spans.sort((a, b) => a[0] - b[0]);
852
+ const lines = [];
853
+ for (const s of spans) {
854
+ const last = lines[lines.length - 1];
855
+ if (last && s[0] < last[1] - 0.5) last[1] = Math.max(last[1], s[1]);
856
+ else lines.push([s[0], s[1]]);
481
857
  }
482
- return { width: Math.max(1, Math.round(width)), height: Math.max(1, Math.round(height2)) };
858
+ return lines.slice(0, -1).map((l) => l[1]).filter((b) => b > 0 && b < total - 0.5);
483
859
  }
484
-
485
- // src/links.ts
486
- var ALLOWED = /* @__PURE__ */ new Set(["http:", "https:", "mailto:", "tel:"]);
487
- function safeHref(url) {
488
- if (typeof url !== "string" || url === "") return void 0;
489
- if (/^#[^\s]*$/.test(url)) return url;
490
- let parsed;
491
- try {
492
- parsed = new URL(url);
493
- } catch {
494
- return void 0;
860
+ function measure(root, blocks) {
861
+ const noteHeights = /* @__PURE__ */ new Map();
862
+ root.querySelectorAll("[data-lw-measure-footnote]").forEach((el) => {
863
+ noteHeights.set(Number(el.dataset.lwMeasureFootnote), height(el));
864
+ });
865
+ const marksIn = (el) => Array.from(el.querySelectorAll("[data-lw-footnote-ref]")).map((m) => {
866
+ const id = Number(m.dataset.lwFootnoteRef);
867
+ return { id, el: m, height: noteHeights.get(id) ?? 0 };
868
+ });
869
+ const items = blocks.map((block, i) => {
870
+ if (block?.type === "pageBreak") return { type: "break" };
871
+ const wrap = root.querySelector(`[data-lw-measure-block="${i}"]`);
872
+ if (!wrap) return { type: "block", id: blockId(i), height: 0 };
873
+ if (block.type === "table") {
874
+ const grid = tableGrid(Array.isArray(block.rows) ? block.rows : []);
875
+ const rows = Array.from(wrap.querySelectorAll("tr[data-lw-row]")).map((tr) => {
876
+ const r = Number(tr.dataset.lwRow);
877
+ const notes2 = marksIn(tr).map(({ id, height: h2 }) => ({ id, height: h2 }));
878
+ return {
879
+ height: height(tr),
880
+ ...grid.joinPrevious[r] ? { joinPrevious: true } : {},
881
+ ...notes2.length ? { footnotes: notes2 } : {}
882
+ };
883
+ });
884
+ return { type: "table", id: blockId(i), rows, headerRows: grid.headerRows };
885
+ }
886
+ const top = wrap.getBoundingClientRect().top;
887
+ const h = height(wrap);
888
+ let breakpoints = SPLITTABLE.has(block.type) ? lineBreakpoints(wrap) : [];
889
+ if (block.type === "paragraph" || block.type === "heading") breakpoints = breakpoints.slice(1, -1);
890
+ const notes = marksIn(wrap).map(({ id, el, height: nh }) => {
891
+ const r = el.getBoundingClientRect();
892
+ return { id, at: Math.min(h, Math.max(0, (r.top + r.bottom) / 2 - top)), height: nh };
893
+ });
894
+ const keepNext = block.type === "heading" || block.keepNext === true;
895
+ return {
896
+ type: "block",
897
+ id: blockId(i),
898
+ height: h,
899
+ ...breakpoints.length ? { breakpoints } : {},
900
+ ...keepNext ? { keepNext: true } : {},
901
+ ...notes.length ? { footnotes: notes } : {}
902
+ };
903
+ });
904
+ const bands = { header: {}, footer: {} };
905
+ for (const kind of ["header", "footer"]) {
906
+ for (const slot of BAND_SLOTS) {
907
+ bands[kind][slot] = height(root.querySelector(`[data-lw-measure-band="${kind}:${slot}"]`));
908
+ }
495
909
  }
496
- return ALLOWED.has(parsed.protocol) ? url : void 0;
910
+ return {
911
+ items,
912
+ headerHeight: bands.header.default,
913
+ footerHeight: bands.footer.default,
914
+ bands,
915
+ footnoteSeparator: height(root.querySelector("[data-lw-measure-separator]"))
916
+ };
497
917
  }
498
918
 
499
- // src/style.ts
500
- var pt = (n) => `${Math.round(n * 1e3) / 1e3}pt`;
501
- var px = (n) => `${Math.round(n * 1e3) / 1e3}px`;
502
- var SINGLE_LINE = 1.17;
503
- var DEFAULT_LINE_MULTIPLE = 259 / 240;
504
- var DEFAULT_SPACE_AFTER = 8;
505
- var DEFAULT_FONT = "Calibri";
506
- var DEFAULT_SIZE = 11;
507
- var HEADING_SIZES = [20, 16, 14, 13, 12, 11];
508
- var HEADER_FILL = "#E7E7E7";
509
- var CODE_FILL = "#F2F2F2";
510
- var LINK_COLOR = "#0563C1";
511
- var QUOTE_COLOR = "#595959";
512
- var BAND_SIZE = 9;
513
- var BAND_COLOR = "#6B7280";
514
- var FOOTNOTE_SIZE = 10;
515
- var FOOTNOTE_SEPARATOR_PT = 12;
516
- function hex(v) {
517
- return typeof v === "string" && /^#[0-9a-fA-F]{6}$/.test(v) ? v : void 0;
518
- }
519
- var finite2 = (v) => typeof v === "number" && Number.isFinite(v);
520
- var num = (v, fallback) => finite2(v) ? v : fallback;
521
- var FALLBACKS = {
522
- calibri: 'Carlito, "Segoe UI", Arial, sans-serif',
523
- cambria: "Caladea, Georgia, serif",
524
- arial: '"Liberation Sans", Arimo, Helvetica, sans-serif',
525
- "times new roman": '"Liberation Serif", Tinos, Times, serif',
526
- "courier new": '"Liberation Mono", Cousine, monospace',
527
- consolas: '"Liberation Mono", Menlo, monospace'
528
- };
529
- function fontStack(name) {
530
- const clean = typeof name === "string" ? name.replace(/[^A-Za-z0-9 _-]/g, "").trim() : "";
531
- const font = clean === "" ? DEFAULT_FONT : clean;
532
- const fallback = FALLBACKS[font.toLowerCase()] ?? 'Carlito, "Segoe UI", Arial, sans-serif';
533
- return `"${font}", ${fallback}`;
534
- }
535
- var MONO = fontStack("Consolas");
536
- var CSS_STYLE = {
537
- single: "solid",
538
- double: "double",
539
- dashed: "dashed",
540
- dotted: "dotted"
541
- };
542
- function borderCss(b) {
543
- if (!b || typeof b !== "object") return void 0;
544
- const style = CSS_STYLE[b.style ?? "single"];
545
- if (!style) return "none";
546
- const width = Math.max(style === "double" ? 2.25 : 0.25, num(b.width, 0.5));
547
- return `${pt(width)} ${style} ${hex(b.color) ?? "#000000"}`;
919
+ // src/paginate.ts
920
+ var EPS = 1e-6;
921
+ var positive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
922
+ function pageCapacity(options, index) {
923
+ const base = Math.max(1, positive(options.pageHeight) ? options.pageHeight : 1);
924
+ if (index === 0) return positive(options.firstPageHeight) ? Math.max(1, options.firstPageHeight) : base;
925
+ if (index % 2 === 1) return positive(options.evenPageHeight) ? Math.max(1, options.evenPageHeight) : base;
926
+ return base;
548
927
  }
549
- function paragraphStyle(p, size) {
550
- const s = {
551
- margin: 0,
552
- marginLeft: pt(num(p.indentLeft, 0)),
553
- marginRight: pt(num(p.indentRight, 0)),
554
- fontSize: pt(size),
555
- lineHeight: num(p.lineHeight, DEFAULT_LINE_MULTIPLE) * SINGLE_LINE,
556
- color: "inherit",
557
- fontWeight: "inherit",
558
- whiteSpace: "pre-wrap",
559
- overflowWrap: "break-word"
928
+ function paginate(items, options) {
929
+ let cap = pageCapacity(options, 0);
930
+ const sep = Math.max(0, options.footnoteSeparator ?? 0);
931
+ const pages = [];
932
+ let page;
933
+ let content = 0;
934
+ let noteHeights = 0;
935
+ const newPage = () => {
936
+ cap = pageCapacity(options, pages.length);
937
+ page = { index: pages.length, fragments: [], footnotes: [], used: 0, capacity: cap };
938
+ pages.push(page);
939
+ content = 0;
940
+ noteHeights = 0;
560
941
  };
561
- if (p.align === "left" || p.align === "center" || p.align === "right" || p.align === "justify") s.textAlign = p.align;
562
- const fill = hex(p.shading);
563
- if (fill) s.backgroundColor = fill;
564
- Object.assign(s, boxBorders(p.borders));
565
- return s;
566
- }
567
- function boxBorders(b) {
568
- if (!b || typeof b !== "object") return {};
569
- const s = {};
570
- const top = borderCss(b.top);
571
- const right = borderCss(b.right);
572
- const bottom = borderCss(b.bottom);
573
- const left = borderCss(b.left);
574
- if (top) {
575
- s.borderTop = top;
576
- if (top !== "none") s.paddingTop = pt(1);
942
+ const noteCost = (extraCount, extraHeight) => {
943
+ const count = page.footnotes.length + extraCount;
944
+ return count > 0 ? noteHeights + extraHeight + sep : 0;
945
+ };
946
+ const fits = (h, notes) => content + h + noteCost(notes.length, sum(notes)) <= cap + EPS;
947
+ const commit = (h, notes) => {
948
+ content += h;
949
+ for (const n of notes) {
950
+ page.footnotes.push(n.id);
951
+ noteHeights += n.height;
952
+ }
953
+ page.used = content + noteCost(0, 0);
954
+ };
955
+ const empty = () => page.fragments.length === 0;
956
+ newPage();
957
+ items.forEach((item, index) => {
958
+ if (item.type === "break") {
959
+ newPage();
960
+ return;
961
+ }
962
+ if (item.type === "table") {
963
+ placeTable(item, index);
964
+ return;
965
+ }
966
+ placeBlock(item, index);
967
+ });
968
+ return pages;
969
+ function notesIn(item, start, end, last) {
970
+ const h = Math.max(0, item.height);
971
+ return (item.footnotes ?? []).filter((n) => {
972
+ const at = Math.min(h, Math.max(0, n.at));
973
+ return at >= start - EPS && (last ? at <= end + EPS : at < end - EPS);
974
+ });
577
975
  }
578
- if (bottom) {
579
- s.borderBottom = bottom;
580
- if (bottom !== "none") s.paddingBottom = pt(1);
976
+ function firstPiece(item) {
977
+ if (!item || item.type === "break") return 0;
978
+ if (item.type === "block") {
979
+ const bp = (item.breakpoints ?? []).find((b) => b > EPS && b < item.height - EPS);
980
+ return bp ?? item.height;
981
+ }
982
+ const header = item.rows.slice(0, headerCount(item)).reduce((a, r) => a + r.height, 0);
983
+ const units = tableUnits(item);
984
+ return header + (units[0] ? units[0].height : 0);
581
985
  }
582
- if (left) {
583
- s.borderLeft = left;
584
- if (left !== "none") s.paddingLeft = pt(4);
986
+ function keepChainHeight(from) {
987
+ let total = 0;
988
+ let i = from;
989
+ while (i < items.length) {
990
+ const it = items[i];
991
+ if (it.type === "block" && it.keepNext) {
992
+ total += it.height;
993
+ i++;
994
+ continue;
995
+ }
996
+ total += firstPiece(it);
997
+ break;
998
+ }
999
+ return total;
585
1000
  }
586
- if (right) {
587
- s.borderRight = right;
588
- if (right !== "none") s.paddingRight = pt(4);
1001
+ function placeBlock(item, index) {
1002
+ const height2 = Math.max(0, item.height);
1003
+ if (item.keepNext && !empty()) {
1004
+ const chain = keepChainHeight(index);
1005
+ const next = items[index + 1];
1006
+ const meaningful = next !== void 0 && next.type !== "break";
1007
+ const nextCap = pageCapacity(options, page.index + 1);
1008
+ if (meaningful && chain <= nextCap + EPS && !fits(chain, notesIn(item, 0, height2, true))) newPage();
1009
+ }
1010
+ let start = 0;
1011
+ for (let guard = 0; guard < 1e5; guard++) {
1012
+ const restNotes = notesIn(item, start, height2, true);
1013
+ if (fits(height2 - start, restNotes)) {
1014
+ page.fragments.push({ type: "block", id: item.id, item: index, start, end: height2 });
1015
+ commit(height2 - start, restNotes);
1016
+ return;
1017
+ }
1018
+ const bps = (item.breakpoints ?? []).filter((b) => b > start + EPS && b < height2 - EPS).sort((a, b) => b - a);
1019
+ let cut;
1020
+ for (const bp of bps) {
1021
+ if (fits(bp - start, notesIn(item, start, bp, false))) {
1022
+ cut = bp;
1023
+ break;
1024
+ }
1025
+ }
1026
+ if (cut !== void 0) {
1027
+ page.fragments.push({ type: "block", id: item.id, item: index, start, end: cut });
1028
+ commit(cut - start, notesIn(item, start, cut, false));
1029
+ newPage();
1030
+ start = cut;
1031
+ continue;
1032
+ }
1033
+ if (!empty()) {
1034
+ newPage();
1035
+ continue;
1036
+ }
1037
+ let room = cap;
1038
+ let end = Math.min(height2, start + room);
1039
+ let notes = notesIn(item, start, end, false);
1040
+ room = cap - noteCost(notes.length, sum(notes));
1041
+ if (room <= EPS) room = cap;
1042
+ end = Math.min(height2, start + room);
1043
+ notes = notesIn(item, start, end, end >= height2 - EPS);
1044
+ const forced = end < height2 - EPS;
1045
+ page.fragments.push({ type: "block", id: item.id, item: index, start, end, ...forced ? { forced: true } : {} });
1046
+ commit(end - start, notes);
1047
+ if (!forced) return;
1048
+ newPage();
1049
+ start = end;
1050
+ }
589
1051
  }
590
- return s;
591
- }
592
- function spacingStyle(p, defaultAfter, defaultBefore = 0) {
593
- return {
594
- display: "flow-root",
595
- paddingTop: pt(Math.max(0, num(p.spaceBefore, defaultBefore))),
596
- paddingBottom: pt(Math.max(0, num(p.spaceAfter, defaultAfter)))
597
- };
598
- }
599
- var EMPTY_MARKS = /* @__PURE__ */ new Map();
600
- var ZWSP = String.fromCharCode(8203);
601
- var RenderCtx = react.createContext({
602
- marks: EMPTY_MARKS,
603
- size: 11,
604
- spaceAfter: DEFAULT_SPACE_AFTER,
605
- contentWidth: 468
606
- });
607
- function WithContext({ value, children }) {
608
- const parent = react.useContext(RenderCtx);
609
- return /* @__PURE__ */ jsxRuntime.jsx(RenderCtx.Provider, { value: { ...parent, ...value }, children });
610
- }
611
- function RunView({ run }) {
612
- const ctx = react.useContext(RenderCtx);
613
- const mark = ctx.marks.get(run);
614
- let text = typeof run.text === "string" ? run.text : "";
615
- if (ctx.fields) text = substituteFields(text, ctx.fields);
616
- const s = {};
617
- if (run.bold || ctx.bold) s.fontWeight = 700;
618
- if (run.italic) s.fontStyle = "italic";
619
- const deco = [run.underline ? "underline" : "", run.strike ? "line-through" : ""].filter(Boolean).join(" ");
620
- if (run.smallCaps) s.fontVariant = "small-caps";
621
- if (typeof run.size === "number" && run.size > 0) s.fontSize = pt(run.size);
622
- if (typeof run.font === "string" && run.font !== "") s.fontFamily = fontStack(run.font);
623
- if (typeof run.letterSpacing === "number" && Number.isFinite(run.letterSpacing)) s.letterSpacing = pt(run.letterSpacing);
624
- if (run.code) {
625
- s.fontFamily = MONO;
626
- s.backgroundColor = CODE_FILL;
1052
+ function headerCount(item) {
1053
+ return Math.max(0, Math.min(item.headerRows ?? 0, item.rows.length));
627
1054
  }
628
- const highlight = hex(run.highlight);
629
- if (highlight) s.backgroundColor = highlight;
630
- const color = hex(run.color);
631
- if (color) s.color = color;
632
- const href = safeHref(run.link);
633
- let body = text;
634
- if (href) {
635
- body = /* @__PURE__ */ jsxRuntime.jsx(
636
- "a",
637
- {
638
- href,
639
- target: "_blank",
640
- rel: "noopener noreferrer",
641
- style: { color: color ?? LINK_COLOR, textDecoration: "underline" },
642
- children: text
1055
+ function tableUnits(item) {
1056
+ const units = [];
1057
+ for (let r = headerCount(item); r < item.rows.length; r++) {
1058
+ const row = item.rows[r];
1059
+ const last = units[units.length - 1];
1060
+ if (row.joinPrevious && last) {
1061
+ last.rows.push(r);
1062
+ last.height += row.height;
1063
+ last.notes.push(...row.footnotes ?? []);
1064
+ } else {
1065
+ units.push({ rows: [r], height: row.height, notes: [...row.footnotes ?? []] });
643
1066
  }
644
- );
645
- } else if (deco) {
646
- s.textDecoration = deco;
647
- }
648
- if (href && deco.includes("line-through")) s.textDecoration = "line-through";
649
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
650
- text !== "" && /* @__PURE__ */ jsxRuntime.jsx("span", { style: s, children: body }),
651
- mark !== void 0 && /* @__PURE__ */ jsxRuntime.jsx("sup", { "data-lw-footnote-ref": mark, style: { fontSize: "0.65em", lineHeight: 0 }, children: mark })
652
- ] });
653
- }
654
- function Runs({ runs }) {
655
- const list = Array.isArray(runs) ? runs : [];
656
- const visible = list.some((r) => typeof r?.text === "string" && r.text !== "" || r?.footnote);
657
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
658
- list.map((run, i) => run && typeof run === "object" ? /* @__PURE__ */ jsxRuntime.jsx(RunView, { run }, i) : null),
659
- !visible && ZWSP
660
- ] });
661
- }
662
- function BlockView({ block }) {
663
- const ctx = react.useContext(RenderCtx);
664
- switch (block?.type) {
665
- case "paragraph":
666
- return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "paragraph", style: spacingStyle(block, ctx.spaceAfter), children: /* @__PURE__ */ jsxRuntime.jsx(reactFancy.Text, { as: "p", style: paragraphStyle(block, ctx.size), children: /* @__PURE__ */ jsxRuntime.jsx(Runs, { runs: block.runs }) }) });
667
- case "heading": {
668
- const level = [1, 2, 3, 4, 5, 6].includes(block.level) ? block.level : 1;
669
- const Tag = `h${level}`;
670
- return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "heading", style: spacingStyle(block, 6, 12), children: /* @__PURE__ */ jsxRuntime.jsx(reactFancy.Heading, { as: Tag, weight: "bold", style: { ...paragraphStyle(block, HEADING_SIZES[level - 1]), fontWeight: 700 }, children: /* @__PURE__ */ jsxRuntime.jsx(Runs, { runs: block.runs }) }) });
671
1067
  }
672
- case "list":
673
- return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "list", style: { display: "flow-root" }, children: /* @__PURE__ */ jsxRuntime.jsx(ListLevel, { items: block.items, ordered: block.ordered === true }) });
674
- case "table":
675
- return /* @__PURE__ */ jsxRuntime.jsx(TableView, { block });
676
- case "code":
677
- return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "code", style: { display: "flow-root" }, children: /* @__PURE__ */ jsxRuntime.jsx(
678
- reactFancy.Text,
679
- {
680
- as: "div",
681
- style: {
682
- margin: 0,
683
- fontFamily: MONO,
684
- fontSize: pt(10),
685
- lineHeight: SINGLE_LINE,
686
- backgroundColor: CODE_FILL,
687
- color: "inherit",
688
- whiteSpace: "pre-wrap",
689
- overflowWrap: "break-word"
690
- },
691
- children: typeof block.text === "string" && block.text !== "" ? block.text : ZWSP
1068
+ return units;
1069
+ }
1070
+ function placeTable(item, index) {
1071
+ const h = headerCount(item);
1072
+ const headerIdx = Array.from({ length: h }, (_, i) => i);
1073
+ const headerHeight = item.rows.slice(0, h).reduce((a, r) => a + r.height, 0);
1074
+ const headerNotes = item.rows.slice(0, h).flatMap((r) => r.footnotes ?? []);
1075
+ const units = tableUnits(item);
1076
+ if (units.length === 0 && h === 0) return;
1077
+ if (units.length === 0) units.push({ rows: [], height: 0, notes: [] });
1078
+ let frag = null;
1079
+ let first = true;
1080
+ for (let u = 0; u < units.length; ) {
1081
+ const unit = units[u];
1082
+ if (frag === null) {
1083
+ const notes = first ? [...headerNotes, ...unit.notes] : unit.notes;
1084
+ const need = headerHeight + unit.height;
1085
+ if (!fits(need, notes) && !empty()) {
1086
+ newPage();
1087
+ continue;
692
1088
  }
693
- ) });
694
- case "quote":
695
- return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "quote", style: { display: "flow-root", marginLeft: pt(36), fontStyle: "italic", color: QUOTE_COLOR }, children: /* @__PURE__ */ jsxRuntime.jsx(WithContext, { value: { contentWidth: ctx.contentWidth - 36 }, children: (Array.isArray(block.blocks) ? block.blocks : []).map((b, i) => /* @__PURE__ */ jsxRuntime.jsx(BlockView, { block: b }, i)) }) });
696
- case "image":
697
- return /* @__PURE__ */ jsxRuntime.jsx(ImageView, { block });
698
- case "chart":
699
- return /* @__PURE__ */ jsxRuntime.jsx(ChartPlaceholder, { block });
700
- case "hr":
701
- return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "hr", style: { display: "flow-root", paddingBottom: pt(ctx.spaceAfter) }, children: /* @__PURE__ */ jsxRuntime.jsx("div", { style: { height: pt(ctx.size * SINGLE_LINE), display: "flex", alignItems: "flex-end" }, children: /* @__PURE__ */ jsxRuntime.jsx(reactFancy.Separator, { className: "w-full" }) }) });
702
- case "pageBreak":
703
- return null;
704
- default:
705
- return null;
1089
+ const overflow = !fits(need, notes);
1090
+ frag = {
1091
+ type: "table",
1092
+ id: item.id,
1093
+ item: index,
1094
+ rows: [...headerIdx, ...unit.rows],
1095
+ repeatedHeader: !first && h > 0,
1096
+ ...overflow ? { overflow: true } : {}
1097
+ };
1098
+ page.fragments.push(frag);
1099
+ commit(need, notes);
1100
+ first = false;
1101
+ u++;
1102
+ continue;
1103
+ }
1104
+ if (fits(unit.height, unit.notes)) {
1105
+ frag.rows.push(...unit.rows);
1106
+ commit(unit.height, unit.notes);
1107
+ u++;
1108
+ continue;
1109
+ }
1110
+ newPage();
1111
+ frag = null;
1112
+ }
706
1113
  }
707
1114
  }
708
- function ListLevel({ items, ordered }) {
709
- const ctx = react.useContext(RenderCtx);
710
- const list = Array.isArray(items) ? items : [];
711
- const style = {
712
- margin: 0,
713
- paddingLeft: pt(36),
714
- listStyleType: ordered ? "decimal" : "disc",
715
- fontSize: pt(ctx.size)
716
- };
717
- const children = list.map((item, i) => /* @__PURE__ */ jsxRuntime.jsxs("li", { style: { paddingLeft: pt(0) }, children: [
718
- /* @__PURE__ */ jsxRuntime.jsx("div", { style: spacingStyle(item, ctx.spaceAfter), children: /* @__PURE__ */ jsxRuntime.jsx(reactFancy.Text, { as: "div", style: paragraphStyle({ ...item, indentLeft: 0 }, ctx.size), children: /* @__PURE__ */ jsxRuntime.jsx(Runs, { runs: item?.runs }) }) }),
719
- Array.isArray(item?.children) && item.children.length > 0 && /* @__PURE__ */ jsxRuntime.jsx(ListLevel, { items: item.children, ordered })
720
- ] }, i));
721
- return ordered ? /* @__PURE__ */ jsxRuntime.jsx("ol", { style, children }) : /* @__PURE__ */ jsxRuntime.jsx("ul", { style, children });
1115
+ function sum(notes) {
1116
+ return notes.reduce((a, n) => a + n.height, 0);
722
1117
  }
723
- var IMAGE_SRC = /^data:image\/(png|jpe?g|gif|webp|bmp);base64,/i;
724
- function ImageView({ block }) {
725
- const ctx = react.useContext(RenderCtx);
726
- const maxPx = ctx.contentWidth * PX_PER_PT;
727
- const size = resolveImageSize({ src: String(block.src ?? ""), widthPx: block.widthPx, heightPx: block.heightPx }, maxPx);
728
- const src = typeof block.src === "string" && IMAGE_SRC.test(block.src) ? block.src : null;
729
- return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "image", style: { display: "flow-root", paddingBottom: pt(ctx.spaceAfter) }, children: src ? /* @__PURE__ */ jsxRuntime.jsx(
730
- reactFancy.ImageViewer,
731
- {
732
- src,
733
- alt: typeof block.alt === "string" ? block.alt : "",
734
- fit: "contain",
735
- zoomable: false,
736
- pannable: false,
737
- controls: false,
738
- checkerboard: false,
739
- className: "rounded-none bg-transparent dark:bg-transparent",
740
- style: { width: size.width, height: size.height, background: "transparent", borderRadius: 0 }
741
- }
742
- ) : /* @__PURE__ */ jsxRuntime.jsx(
743
- "div",
744
- {
745
- "data-lw-image-missing": "",
746
- style: { width: size.width, height: size.height, border: "0.75pt dashed #9CA3AF", color: "#6B7280", fontSize: pt(9), padding: pt(4), boxSizing: "border-box" },
747
- children: typeof block.alt === "string" && block.alt !== "" ? block.alt : "Image"
748
- }
749
- ) });
1118
+
1119
+ // src/font-urls.ts
1120
+ function carlitoUrls() {
1121
+ try {
1122
+ return {
1123
+ "Carlito-Regular.ttf": new URL("../fonts/Carlito-Regular.ttf", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).href,
1124
+ "Carlito-Bold.ttf": new URL("../fonts/Carlito-Bold.ttf", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).href,
1125
+ "Carlito-Italic.ttf": new URL("../fonts/Carlito-Italic.ttf", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).href,
1126
+ "Carlito-BoldItalic.ttf": new URL("../fonts/Carlito-BoldItalic.ttf", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).href
1127
+ };
1128
+ } catch {
1129
+ return null;
1130
+ }
750
1131
  }
751
- function ChartPlaceholder({ block }) {
752
- const ctx = react.useContext(RenderCtx);
753
- const maxPx = ctx.contentWidth * PX_PER_PT;
754
- const width = Math.min(
755
- maxPx,
756
- num(block.widthPx, typeof block.width === "number" && block.width > 0 ? maxPx * Math.min(100, block.width) / 100 : maxPx)
757
- );
758
- const height2 = num(block.heightPx, width * 0.6);
759
- const option = block.option ?? {};
760
- const title = typeof option.title === "string" ? option.title : option.title && typeof option.title.text === "string" ? option.title.text : typeof block.alt === "string" ? block.alt : "";
761
- return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-kind": "chart", style: { display: "flow-root", paddingBottom: pt(ctx.spaceAfter) }, children: /* @__PURE__ */ jsxRuntime.jsx(
762
- "div",
763
- {
764
- "data-lw-chart-placeholder": "",
765
- style: {
766
- width,
767
- height: height2,
768
- border: "0.75pt dashed #9CA3AF",
769
- color: "#6B7280",
770
- fontSize: pt(9),
771
- display: "flex",
772
- alignItems: "center",
773
- justifyContent: "center",
774
- boxSizing: "border-box"
775
- },
776
- children: title ? `Chart: ${title}` : "Chart"
777
- }
778
- ) });
1132
+
1133
+ // src/fonts.ts
1134
+ var CARLITO_FACES = [
1135
+ { file: "Carlito-Regular.ttf", weight: 400, style: "normal", sha256: "f6418f708baede9789daef5d458c0f53d2a888af9820e8062934e504fedc6595" },
1136
+ { file: "Carlito-Bold.ttf", weight: 700, style: "normal", sha256: "bb5d20f79b82599ec72983597437373a80f2d2085fa91fc144fd74e876a594db" },
1137
+ { file: "Carlito-Italic.ttf", weight: 400, style: "italic", sha256: "0b019225e58d702bfedcbd35c21696769f8ee115cb6343f84c2f240312450d1c" },
1138
+ { file: "Carlito-BoldItalic.ttf", weight: 700, style: "italic", sha256: "b32928186c119599e03ca6a1ffc680fdcb7fac95772f4b95d989cf6cd3861517" }
1139
+ ];
1140
+ function fontFaceCss(url) {
1141
+ return CARLITO_FACES.map(
1142
+ (f) => `@font-face { font-family: "${CARLITO_FAMILY}"; font-weight: ${f.weight}; font-style: ${f.style}; font-display: swap; src: url("${url(f.file)}") format("truetype"); }`
1143
+ ).join("\n");
779
1144
  }
780
- var DEFAULT_TABLE_BORDER = { style: "single", width: 0.5 };
781
- var DEFAULT_CELL_PADDING = { top: 3, right: 5.4, bottom: 3, left: 5.4 };
782
- var WORD_CELL_PADDING = { top: 0, right: 5.4, bottom: 0, left: 5.4 };
783
- function sides(base, over) {
784
- if (!over || typeof over !== "object") return base;
785
- const o = over;
786
- return {
787
- top: num(o.top, base.top),
788
- right: num(o.right, base.right),
789
- bottom: num(o.bottom, base.bottom),
790
- left: num(o.left, base.left)
791
- };
1145
+ var clean = (name) => typeof name === "string" ? name.replace(/[^A-Za-z0-9 _-]/g, "").trim() : "";
1146
+ function usesCarlito(name) {
1147
+ const n = clean(name);
1148
+ return (n === "" ? DEFAULT_FONT : n).toLowerCase() === "calibri";
792
1149
  }
793
- function TableView({ block, rows }) {
794
- const ctx = react.useContext(RenderCtx);
795
- const all = Array.isArray(block.rows) ? block.rows : [];
796
- const grid = tableGrid(all);
797
- const pct = columnPercents(grid.colCount, block.widths);
798
- const tb = block.borders && typeof block.borders === "object" ? block.borders : {
799
- top: DEFAULT_TABLE_BORDER,
800
- right: DEFAULT_TABLE_BORDER,
801
- bottom: DEFAULT_TABLE_BORDER,
802
- left: DEFAULT_TABLE_BORDER,
803
- insideH: DEFAULT_TABLE_BORDER,
804
- insideV: DEFAULT_TABLE_BORDER
1150
+ function carlitoFaces(doc) {
1151
+ const used = /* @__PURE__ */ new Set();
1152
+ const docCarlito = usesCarlito(doc?.defaultFont);
1153
+ const runs = (list, bold, italic) => {
1154
+ if (!Array.isArray(list)) return;
1155
+ for (const r of list) {
1156
+ if (!r || typeof r !== "object") continue;
1157
+ if (r.footnote && typeof r.footnote === "object") blocks(r.footnote.blocks, false, false);
1158
+ const hasFont = typeof r.font === "string" && r.font !== "";
1159
+ if (r.code || !(hasFont ? usesCarlito(r.font) : docCarlito)) continue;
1160
+ used.add(`${bold || r.bold ? 700 : 400}:${italic || r.italic ? "italic" : "normal"}`);
1161
+ }
805
1162
  };
806
- const basePad = block.cellPadding && typeof block.cellPadding === "object" ? sides(WORD_CELL_PADDING, block.cellPadding) : DEFAULT_CELL_PADDING;
807
- const widthPct = typeof block.width === "number" && block.width > 0 ? Math.min(100, block.width) : 100;
808
- const show = rows ?? all.map((_, i) => i);
809
- return /* @__PURE__ */ jsxRuntime.jsx(
810
- "div",
811
- {
812
- "data-lw-kind": "table",
813
- style: {
814
- width: `${widthPct}%`,
815
- marginLeft: block.align === "center" || block.align === "right" ? "auto" : void 0,
816
- marginRight: block.align === "center" ? "auto" : void 0
817
- },
818
- children: /* @__PURE__ */ jsxRuntime.jsx(reactFancy.Table, { "data-lw-table": "", className: "rounded-none border-0 overflow-visible", children: /* @__PURE__ */ jsxRuntime.jsxs(reactFancy.Table.Body, { className: "divide-y-0", children: [
819
- /* @__PURE__ */ jsxRuntime.jsx("tr", { "data-lw-sizer": "", "aria-hidden": "true", children: pct.map((p, i) => /* @__PURE__ */ jsxRuntime.jsx("td", { style: { width: `${p}%`, padding: 0, border: "none", height: 0 } }, i)) }),
820
- show.map((r) => {
821
- const row = all[r];
822
- if (!row) return null;
823
- const header = row.header === true;
824
- return /* @__PURE__ */ jsxRuntime.jsx(reactFancy.Table.Row, { "data-lw-row": r, className: "hover:bg-transparent dark:hover:bg-transparent", children: (grid.rows[r] ?? []).map((gc) => {
825
- const cell = row.cells[gc.cell];
826
- const cb = cell.borders && typeof cell.borders === "object" ? cell.borders : {};
827
- const edge = (own, outer, inner, isOuter) => borderCss(own ?? (isOuter ? outer : inner)) ?? "none";
828
- const pad = sides(basePad, cell.padding);
829
- const fill = hex(cell.shading) ?? (header ? HEADER_FILL : void 0);
830
- const style = {
831
- borderTop: edge(cb.top, tb.top, tb.insideH, gc.row === 0),
832
- borderBottom: edge(cb.bottom, tb.bottom, tb.insideH, gc.row + gc.rowSpan >= all.length),
833
- borderLeft: edge(cb.left, tb.left, tb.insideV, gc.col === 0),
834
- borderRight: edge(cb.right, tb.right, tb.insideV, gc.col + gc.colSpan >= grid.colCount),
835
- padding: `${pt(pad.top)} ${pt(pad.right)} ${pt(pad.bottom)} ${pt(pad.left)}`,
836
- verticalAlign: cell.valign === "center" ? "middle" : cell.valign === "bottom" ? "bottom" : "top",
837
- backgroundColor: fill ?? "transparent",
838
- color: "inherit",
839
- fontSize: "inherit",
840
- fontWeight: "inherit",
841
- textAlign: "left",
842
- overflowWrap: "break-word"
843
- };
844
- return /* @__PURE__ */ jsxRuntime.jsx(
845
- reactFancy.Table.Cell,
846
- {
847
- header,
848
- colSpan: gc.colSpan > 1 ? gc.colSpan : void 0,
849
- rowSpan: gc.rowSpan > 1 ? gc.rowSpan : void 0,
850
- "data-lw-cell": `${r}:${gc.cell}`,
851
- style,
852
- children: /* @__PURE__ */ jsxRuntime.jsx(
853
- WithContext,
854
- {
855
- value: {
856
- bold: header || ctx.bold,
857
- contentWidth: ctx.contentWidth * widthPct * (pct.slice(gc.col, gc.col + gc.colSpan).reduce((a, b) => a + b, 0) / 100) / 100
858
- },
859
- children: (Array.isArray(cell.blocks) ? cell.blocks : []).map((b, i) => /* @__PURE__ */ jsxRuntime.jsx(BlockView, { block: b }, i))
860
- }
861
- )
862
- },
863
- gc.cell
864
- );
865
- }) }, r);
866
- })
867
- ] }) })
1163
+ const blocks = (list, bold, italic) => {
1164
+ if (!Array.isArray(list)) return;
1165
+ for (const b of list) {
1166
+ if (!b || typeof b !== "object") continue;
1167
+ switch (b.type) {
1168
+ case "paragraph":
1169
+ runs(b.runs, bold, italic);
1170
+ break;
1171
+ case "heading":
1172
+ runs(b.runs, true, italic);
1173
+ break;
1174
+ case "list": {
1175
+ const items = (xs) => {
1176
+ if (!Array.isArray(xs)) return;
1177
+ for (const it of xs) {
1178
+ runs(it?.runs, bold, italic);
1179
+ items(it?.children);
1180
+ }
1181
+ };
1182
+ items(b.items);
1183
+ break;
1184
+ }
1185
+ case "quote":
1186
+ blocks(b.blocks, bold, true);
1187
+ break;
1188
+ case "table":
1189
+ for (const row of Array.isArray(b.rows) ? b.rows : []) {
1190
+ for (const cell of Array.isArray(row?.cells) ? row.cells : []) blocks(cell?.blocks, bold || row.header === true, italic);
1191
+ }
1192
+ break;
1193
+ }
868
1194
  }
869
- );
870
- }
871
- function isBlocksBand(band) {
872
- return !!band && typeof band === "object" && Array.isArray(band.blocks);
873
- }
874
- function hasBand(band) {
875
- if (isBlocksBand(band)) return band.blocks.length > 0;
876
- if (!band || typeof band !== "object") return false;
877
- const b = band;
878
- return [b.left, b.center, b.right].some((s) => typeof s === "string" && s !== "");
879
- }
880
- function BandView({ band }) {
881
- const ctx = react.useContext(RenderCtx);
882
- if (isBlocksBand(band)) {
883
- return /* @__PURE__ */ jsxRuntime.jsx(WithContext, { value: { marks: EMPTY_MARKS }, children: band.blocks.map((b, i) => b?.type === "pageBreak" || b?.type === "chart" ? null : /* @__PURE__ */ jsxRuntime.jsx(BlockView, { block: b }, i)) });
1195
+ };
1196
+ blocks(doc?.blocks, false, false);
1197
+ const page = doc?.page && typeof doc.page === "object" ? doc.page : {};
1198
+ for (const key of ["header", "footer", "firstHeader", "firstFooter", "evenHeader", "evenFooter"]) {
1199
+ const band = page[key];
1200
+ if (!band || typeof band !== "object") continue;
1201
+ if (Array.isArray(band.blocks)) blocks(band.blocks, false, false);
1202
+ else if (docCarlito && [band.left, band.center, band.right].some((s) => typeof s === "string" && s !== "")) used.add("400:normal");
884
1203
  }
885
- const slot = (v) => typeof v === "string" ? ctx.fields ? substituteFields(v, ctx.fields) : v : "";
886
- return /* @__PURE__ */ jsxRuntime.jsxs(
887
- reactFancy.Text,
888
- {
889
- as: "div",
890
- style: {
891
- display: "grid",
892
- gridTemplateColumns: "1fr auto 1fr",
893
- fontSize: pt(num(band.size, BAND_SIZE)),
894
- lineHeight: SINGLE_LINE,
895
- color: hex(band.color) ?? BAND_COLOR,
896
- whiteSpace: "pre"
897
- },
898
- children: [
899
- /* @__PURE__ */ jsxRuntime.jsx("span", { "data-lw-slot": "left", style: { textAlign: "left" }, children: slot(band.left) }),
900
- /* @__PURE__ */ jsxRuntime.jsx("span", { "data-lw-slot": "center", style: { textAlign: "center" }, children: slot(band.center) }),
901
- /* @__PURE__ */ jsxRuntime.jsx("span", { "data-lw-slot": "right", style: { textAlign: "right", justifySelf: "end" }, children: slot(band.right) })
902
- ]
903
- }
1204
+ return CARLITO_FACES.filter((f) => used.has(`${f.weight}:${f.style}`)).map(
1205
+ (f) => `${f.weight} ${f.style} 16px "${CARLITO_FAMILY}"`
904
1206
  );
905
1207
  }
906
- function FootnoteView({ id, footnote }) {
907
- return /* @__PURE__ */ jsxRuntime.jsxs("div", { "data-footnote": id, style: { display: "flex", gap: pt(3) }, children: [
908
- /* @__PURE__ */ jsxRuntime.jsx("sup", { style: { fontSize: pt(FOOTNOTE_SIZE * 0.65), lineHeight: 1, paddingTop: pt(2) }, children: id }),
909
- /* @__PURE__ */ jsxRuntime.jsx("div", { style: { flex: 1, minWidth: 0 }, children: /* @__PURE__ */ jsxRuntime.jsx(WithContext, { value: { marks: EMPTY_MARKS, size: FOOTNOTE_SIZE, spaceAfter: 0 }, children: (Array.isArray(footnote.blocks) ? footnote.blocks : []).map((b, i) => /* @__PURE__ */ jsxRuntime.jsx(BlockView, { block: b }, i)) }) })
910
- ] });
911
- }
912
- function FootnoteSeparator({ height: height2 }) {
913
- return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-footnote-separator": "", style: { height: height2, display: "flex", alignItems: "center" }, children: /* @__PURE__ */ jsxRuntime.jsx("div", { style: { width: pt(144), borderTop: `${pt(0.5)} solid #000000` } }) });
914
- }
915
1208
 
916
1209
  // src/viewer-css.ts
917
1210
  var VIEWER_CSS = `
@@ -921,12 +1214,24 @@ var VIEWER_CSS = `
921
1214
  :where([data-lw-viewer]) hr[data-react-fancy-separator] { margin: 0; width: 100%; border: 0; border-top: 0.75pt solid #000000; }
922
1215
  :where([data-lw-viewer]) [data-lw-sheet] p, :where([data-lw-viewer]) [data-lw-measure] p { margin-top: 0; margin-bottom: 0; }
923
1216
  `.trim();
1217
+ var FONT_LOAD_TIMEOUT_MS = 3e3;
1218
+ var FONT_CSS = (() => {
1219
+ const urls = carlitoUrls();
1220
+ return urls ? fontFaceCss((file) => urls[file]) : null;
1221
+ })();
1222
+ function initialFontState(faces) {
1223
+ if (faces.length === 0) return "unused";
1224
+ const fonts = typeof document !== "undefined" ? document.fonts : void 0;
1225
+ return fonts && typeof fonts.load === "function" ? "pending" : "fallback";
1226
+ }
924
1227
  function DocViewer({
925
1228
  doc,
926
1229
  fit = "width",
927
1230
  scale: fixedScale,
928
1231
  maxScale = 1,
929
1232
  gap = 16,
1233
+ filename,
1234
+ now,
930
1235
  onLayout,
931
1236
  injectStyles = true,
932
1237
  id,
@@ -936,12 +1241,28 @@ function DocViewer({
936
1241
  const geometry = react.useMemo(() => pageGeometry(doc), [doc]);
937
1242
  const numbering = react.useMemo(() => numberFootnotes(doc), [doc]);
938
1243
  const blocks = react.useMemo(() => Array.isArray(doc?.blocks) ? doc.blocks : [], [doc]);
939
- const header = hasBand(doc?.page?.header) ? doc.page.header : null;
940
- const footer = hasBand(doc?.page?.footer) ? doc.page.footer : null;
1244
+ const page = doc?.page && typeof doc.page === "object" ? doc.page : void 0;
1245
+ const nowKey = now instanceof Date ? now.getTime() : now;
1246
+ const nowDate = react.useMemo(() => resolveNow(nowKey === void 0 ? void 0 : typeof nowKey === "number" ? new Date(nowKey) : nowKey), [nowKey]);
1247
+ const author = doc?.meta && typeof doc.meta === "object" ? doc.meta.author : void 0;
1248
+ const title = doc?.title;
1249
+ const docFields = react.useMemo(
1250
+ () => ({
1251
+ section: 1,
1252
+ ...typeof author === "string" ? { author } : {},
1253
+ ...typeof title === "string" ? { title } : {},
1254
+ ...typeof filename === "string" ? { filename } : {},
1255
+ now: nowDate
1256
+ }),
1257
+ [author, title, filename, nowDate]
1258
+ );
941
1259
  const rootRef = react.useRef(null);
942
1260
  const measureRef = react.useRef(null);
943
1261
  const [layout, setLayout] = react.useState(null);
944
1262
  const [fontEpoch, setFontEpoch] = react.useState(0);
1263
+ const faces = react.useMemo(() => carlitoFaces(doc), [doc]);
1264
+ const facesKey = faces.join("|");
1265
+ const [font, setFont] = react.useState(() => initialFontState(faces));
945
1266
  const [width, setWidth] = react.useState(null);
946
1267
  const ctx = react.useMemo(
947
1268
  () => ({
@@ -952,15 +1273,37 @@ function DocViewer({
952
1273
  }),
953
1274
  [numbering, doc, geometry]
954
1275
  );
1276
+ react.useEffect(() => {
1277
+ const state = initialFontState(faces);
1278
+ setFont(state);
1279
+ if (state !== "pending") return;
1280
+ let live = true;
1281
+ const timer = setTimeout(() => live && setFont((f) => f === "pending" ? "fallback" : f), FONT_LOAD_TIMEOUT_MS);
1282
+ Promise.all(faces.map((f) => document.fonts.load(f))).then((loaded) => live && setFont(loaded.every((l) => l.length > 0) ? "carlito" : "fallback")).catch(() => live && setFont("fallback"));
1283
+ return () => {
1284
+ live = false;
1285
+ clearTimeout(timer);
1286
+ };
1287
+ }, [facesKey]);
955
1288
  react.useLayoutEffect(() => {
956
1289
  const el = measureRef.current;
957
- if (!el) return;
1290
+ if (!el || font === "pending") return;
958
1291
  const m = measure(el, blocks);
959
- const box = bodyBox(geometry, m.headerHeight / PX_PER_PT, m.footerHeight / PX_PER_PT);
960
- const pages = paginate(m.items, { pageHeight: box.height * PX_PER_PT, footnoteSeparator: m.footnoteSeparator });
1292
+ const toPt = (h) => ({
1293
+ default: h.default / PX_PER_PT,
1294
+ first: h.first / PX_PER_PT,
1295
+ even: h.even / PX_PER_PT
1296
+ });
1297
+ const boxes = pageBodyBoxes(geometry, page, { header: toPt(m.bands.header), footer: toPt(m.bands.footer) });
1298
+ const pages = paginate(m.items, {
1299
+ pageHeight: boxes.odd.height * PX_PER_PT,
1300
+ firstPageHeight: boxes.first.height * PX_PER_PT,
1301
+ evenPageHeight: boxes.even.height * PX_PER_PT,
1302
+ footnoteSeparator: m.footnoteSeparator
1303
+ });
961
1304
  const heights = m.items.map((it) => it.type === "block" ? it.height : 0);
962
- setLayout({ pages, box, heights });
963
- }, [blocks, geometry, numbering, fontEpoch, header, footer]);
1305
+ setLayout({ pages, boxes, heights });
1306
+ }, [blocks, geometry, numbering, fontEpoch, page, docFields, font]);
964
1307
  react.useEffect(() => {
965
1308
  const fonts = typeof document !== "undefined" ? document.fonts : void 0;
966
1309
  let live = true;
@@ -985,26 +1328,25 @@ function DocViewer({
985
1328
  const scale = typeof fixedScale === "number" && fixedScale > 0 ? fixedScale : fit === "none" || !width ? 1 : Math.min(maxScale, width / pageWpx);
986
1329
  const pageCount = layout?.pages.length ?? 0;
987
1330
  react.useEffect(() => {
988
- if (layout) onLayout?.({ pages: layout.pages.length, pageWidth: geometry.width, pageHeight: geometry.height, scale });
989
- }, [layout, geometry, scale, onLayout]);
990
- const typography = {
991
- fontFamily: fontStack(doc?.defaultFont),
992
- fontSize: pt(ctx.size),
993
- lineHeight: SINGLE_LINE,
994
- color: "#000000",
995
- textAlign: "left"
996
- };
1331
+ if (layout && font !== "pending") {
1332
+ onLayout?.({ pages: layout.pages.length, pageWidth: geometry.width, pageHeight: geometry.height, scale, font });
1333
+ }
1334
+ }, [layout, geometry, scale, onLayout, font]);
1335
+ const typography2 = typography(doc?.defaultFont, ctx.size);
1336
+ const ready = layout !== null && font !== "pending";
997
1337
  return /* @__PURE__ */ jsxRuntime.jsxs(
998
1338
  "div",
999
1339
  {
1000
1340
  ref: rootRef,
1001
1341
  id,
1002
1342
  "data-lw-viewer": "",
1003
- "data-lw-pages": pageCount || void 0,
1343
+ "data-lw-pages": ready && pageCount || void 0,
1344
+ "data-lw-font": ready ? font : void 0,
1004
1345
  className,
1005
1346
  style: { position: "relative", ...style },
1006
1347
  children: [
1007
1348
  injectStyles && /* @__PURE__ */ jsxRuntime.jsx("style", { href: "particle-academy-last-word-ui", precedence: "default", children: VIEWER_CSS }),
1349
+ injectStyles && FONT_CSS && /* @__PURE__ */ jsxRuntime.jsx("style", { href: "particle-academy-last-word-ui-fonts", precedence: "default", children: FONT_CSS }),
1008
1350
  /* @__PURE__ */ jsxRuntime.jsx(
1009
1351
  "div",
1010
1352
  {
@@ -1012,7 +1354,7 @@ function DocViewer({
1012
1354
  "aria-hidden": "true",
1013
1355
  "data-lw-measure": "",
1014
1356
  style: {
1015
- ...typography,
1357
+ ...typography2,
1016
1358
  position: "absolute",
1017
1359
  visibility: "hidden",
1018
1360
  pointerEvents: "none",
@@ -1021,40 +1363,50 @@ function DocViewer({
1021
1363
  width: pt(geometry.contentWidth)
1022
1364
  },
1023
1365
  children: /* @__PURE__ */ jsxRuntime.jsxs(RenderCtx.Provider, { value: ctx, children: [
1024
- header && /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-measure-header": "", children: /* @__PURE__ */ jsxRuntime.jsx(RenderCtx.Provider, { value: { ...ctx, fields: { page: 1, pages: 1 } }, children: /* @__PURE__ */ jsxRuntime.jsx(BandView, { band: header }) }) }),
1025
- footer && /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-measure-footer": "", children: /* @__PURE__ */ jsxRuntime.jsx(RenderCtx.Provider, { value: { ...ctx, fields: { page: 1, pages: 1 } }, children: /* @__PURE__ */ jsxRuntime.jsx(BandView, { band: footer }) }) }),
1366
+ ["header", "footer"].flatMap(
1367
+ (kind) => BAND_SLOTS.map((slot) => {
1368
+ const band = slotBand(page, kind, slot);
1369
+ if (!hasBand(band)) return null;
1370
+ const n = slot === "even" ? 2 : 1;
1371
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-measure-band": `${kind}:${slot}`, children: /* @__PURE__ */ jsxRuntime.jsx(RenderCtx.Provider, { value: { ...ctx, fields: { ...docFields, page: n, pages: n } }, children: /* @__PURE__ */ jsxRuntime.jsx(BandView, { band }) }) }, `${kind}:${slot}`);
1372
+ })
1373
+ ),
1026
1374
  blocks.map((b, i) => /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-measure-block": i, style: { display: "flow-root" }, children: /* @__PURE__ */ jsxRuntime.jsx(BlockView, { block: b }) }, i)),
1027
1375
  numbering.notes.map((n) => /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-measure-footnote": n.id, children: /* @__PURE__ */ jsxRuntime.jsx(FootnoteView, { id: n.id, footnote: n.footnote }) }, n.id)),
1028
1376
  numbering.notes.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-measure-separator": "", children: /* @__PURE__ */ jsxRuntime.jsx(FootnoteSeparator, { height: pt(FOOTNOTE_SEPARATOR_PT) }) })
1029
1377
  ] })
1030
1378
  }
1031
1379
  ),
1032
- layout && /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-page-stack": "", style: { display: "flex", flexDirection: "column", alignItems: "center", gap }, children: layout.pages.map((page) => /* @__PURE__ */ jsxRuntime.jsx(
1380
+ ready && layout && /* @__PURE__ */ jsxRuntime.jsx("div", { "data-lw-page-stack": "", style: { display: "flex", flexDirection: "column", alignItems: "center", gap }, children: layout.pages.map((p) => /* @__PURE__ */ jsxRuntime.jsx(
1033
1381
  PageView,
1034
1382
  {
1035
- page,
1383
+ page: p,
1036
1384
  pages: layout.pages.length,
1037
1385
  geometry,
1038
- box: layout.box,
1386
+ box: layout.boxes[pageClass(p.index)],
1039
1387
  scale,
1040
- typography,
1388
+ typography: typography2,
1041
1389
  ctx,
1042
- header,
1043
- footer,
1390
+ docPage: page,
1391
+ docFields,
1044
1392
  numbering,
1045
1393
  blocks,
1046
1394
  heights: layout.heights
1047
1395
  },
1048
- page.index
1396
+ p.index
1049
1397
  )) })
1050
1398
  ]
1051
1399
  }
1052
1400
  );
1053
1401
  }
1054
- function PageView({ page, pages, geometry, box, scale, typography, ctx, header, footer, numbering, blocks, heights }) {
1402
+ function PageView({ page, pages, geometry, box, scale, typography: typography2, ctx, docPage, docFields, numbering, blocks, heights }) {
1055
1403
  const n = page.index + 1;
1056
1404
  const g = geometry;
1057
- const bandCtx = { ...ctx, fields: { page: n, pages } };
1405
+ const bandCtx = { ...ctx, fields: { ...docFields, page: n, pages, sectionPages: pages } };
1406
+ const cls = pageClass(page.index);
1407
+ const header = pageBand(docPage, "header", page.index);
1408
+ const footer = pageBand(docPage, "footer", page.index);
1409
+ const variant = (kind) => bandSlot(docPage, kind, cls);
1058
1410
  const notes = page.footnotes.map((fid) => numbering.notes.find((x) => x.id === fid)).filter((x) => !!x);
1059
1411
  return /* @__PURE__ */ jsxRuntime.jsx(
1060
1412
  "div",
@@ -1067,7 +1419,7 @@ function PageView({ page, pages, geometry, box, scale, typography, ctx, header,
1067
1419
  {
1068
1420
  "data-lw-sheet": "",
1069
1421
  style: {
1070
- ...typography,
1422
+ ...typography2,
1071
1423
  position: "relative",
1072
1424
  width: pt(g.width),
1073
1425
  height: pt(g.height),
@@ -1082,6 +1434,7 @@ function PageView({ page, pages, geometry, box, scale, typography, ctx, header,
1082
1434
  "div",
1083
1435
  {
1084
1436
  "data-lw-band": "header",
1437
+ "data-lw-band-variant": variant("header"),
1085
1438
  style: { position: "absolute", top: pt(g.margins.header), left: pt(g.margins.left), width: pt(g.contentWidth) },
1086
1439
  children: /* @__PURE__ */ jsxRuntime.jsx(RenderCtx.Provider, { value: bandCtx, children: /* @__PURE__ */ jsxRuntime.jsx(BandView, { band: header }) })
1087
1440
  }
@@ -1112,6 +1465,7 @@ function PageView({ page, pages, geometry, box, scale, typography, ctx, header,
1112
1465
  "div",
1113
1466
  {
1114
1467
  "data-lw-band": "footer",
1468
+ "data-lw-band-variant": variant("footer"),
1115
1469
  style: { position: "absolute", bottom: pt(g.margins.footer), left: pt(g.margins.left), width: pt(g.contentWidth) },
1116
1470
  children: /* @__PURE__ */ jsxRuntime.jsx(RenderCtx.Provider, { value: bandCtx, children: /* @__PURE__ */ jsxRuntime.jsx(BandView, { band: footer }) })
1117
1471
  }
@@ -1171,17 +1525,29 @@ function docFromReader(output) {
1171
1525
  return value;
1172
1526
  }
1173
1527
 
1528
+ exports.CARLITO_FACES = CARLITO_FACES;
1529
+ exports.CARLITO_FAMILY = CARLITO_FAMILY;
1174
1530
  exports.DocViewer = DocViewer;
1531
+ exports.FONT_LOAD_TIMEOUT_MS = FONT_LOAD_TIMEOUT_MS;
1175
1532
  exports.PAGE_BAND_DISTANCE_DEFAULT = PAGE_BAND_DISTANCE_DEFAULT;
1176
1533
  exports.PAGE_MARGIN_DEFAULT = PAGE_MARGIN_DEFAULT;
1177
1534
  exports.PAGE_SIZES_PT = PAGE_SIZES_PT;
1178
1535
  exports.PX_PER_PT = PX_PER_PT;
1536
+ exports.bandSlot = bandSlot;
1179
1537
  exports.bodyBox = bodyBox;
1538
+ exports.carlitoFaces = carlitoFaces;
1180
1539
  exports.docFromReader = docFromReader;
1540
+ exports.fontFaceCss = fontFaceCss;
1541
+ exports.formatDatePicture = formatDatePicture;
1181
1542
  exports.numberFootnotes = numberFootnotes;
1543
+ exports.pageBand = pageBand;
1544
+ exports.pageBodyBoxes = pageBodyBoxes;
1545
+ exports.pageCapacity = pageCapacity;
1546
+ exports.pageClass = pageClass;
1182
1547
  exports.pageGeometry = pageGeometry;
1183
1548
  exports.pageMargins = pageMargins;
1184
1549
  exports.paginate = paginate;
1550
+ exports.resolveNow = resolveNow;
1185
1551
  exports.substituteFields = substituteFields;
1186
1552
  //# sourceMappingURL=index.cjs.map
1187
1553
  //# sourceMappingURL=index.cjs.map