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