pretext-pdf 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +242 -0
  2. package/LICENSE +21 -0
  3. package/README.md +402 -0
  4. package/dist/assets.d.ts +14 -0
  5. package/dist/assets.d.ts.map +1 -0
  6. package/dist/assets.js +182 -0
  7. package/dist/assets.js.map +1 -0
  8. package/dist/builder.d.ts +53 -0
  9. package/dist/builder.d.ts.map +1 -0
  10. package/dist/builder.js +129 -0
  11. package/dist/builder.js.map +1 -0
  12. package/dist/errors.d.ts +7 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +13 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/fonts.d.ts +21 -0
  17. package/dist/fonts.d.ts.map +1 -0
  18. package/dist/fonts.js +310 -0
  19. package/dist/fonts.js.map +1 -0
  20. package/dist/index.d.ts +29 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +154 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/measure.d.ts +53 -0
  25. package/dist/measure.d.ts.map +1 -0
  26. package/dist/measure.js +1029 -0
  27. package/dist/measure.js.map +1 -0
  28. package/dist/node-polyfill.d.ts +7 -0
  29. package/dist/node-polyfill.d.ts.map +1 -0
  30. package/dist/node-polyfill.js +82 -0
  31. package/dist/node-polyfill.js.map +1 -0
  32. package/dist/page-sizes.d.ts +13 -0
  33. package/dist/page-sizes.d.ts.map +1 -0
  34. package/dist/page-sizes.js +24 -0
  35. package/dist/page-sizes.js.map +1 -0
  36. package/dist/paginate.d.ts +15 -0
  37. package/dist/paginate.d.ts.map +1 -0
  38. package/dist/paginate.js +395 -0
  39. package/dist/paginate.js.map +1 -0
  40. package/dist/render.d.ts +12 -0
  41. package/dist/render.d.ts.map +1 -0
  42. package/dist/render.js +1028 -0
  43. package/dist/render.js.map +1 -0
  44. package/dist/rich-text.d.ts +14 -0
  45. package/dist/rich-text.d.ts.map +1 -0
  46. package/dist/rich-text.js +183 -0
  47. package/dist/rich-text.js.map +1 -0
  48. package/dist/types.d.ts +697 -0
  49. package/dist/types.d.ts.map +1 -0
  50. package/dist/types.js +2 -0
  51. package/dist/types.js.map +1 -0
  52. package/dist/validate.d.ts +3 -0
  53. package/dist/validate.d.ts.map +1 -0
  54. package/dist/validate.js +786 -0
  55. package/dist/validate.js.map +1 -0
  56. package/package.json +79 -0
@@ -0,0 +1,1029 @@
1
+ import { PretextPdfError } from './errors.js';
2
+ import { measureRichText } from './rich-text.js';
3
+ /** Heading level size multipliers and defaults */
4
+ const HEADING_DEFAULTS = {
5
+ 1: { sizeMultiplier: 2.0, fontWeight: 700, spaceAfter: 16, spaceBefore: 28 },
6
+ 2: { sizeMultiplier: 1.5, fontWeight: 700, spaceAfter: 12, spaceBefore: 24 },
7
+ 3: { sizeMultiplier: 1.25, fontWeight: 700, spaceAfter: 8, spaceBefore: 20 },
8
+ 4: { sizeMultiplier: 1.1, fontWeight: 700, spaceAfter: 6, spaceBefore: 16 },
9
+ };
10
+ /** Lazily-loaded Pretext module — must be imported AFTER polyfill is installed */
11
+ let _pretext = null;
12
+ async function getPretext() {
13
+ if (!_pretext) {
14
+ _pretext = await import('@chenglou/pretext');
15
+ }
16
+ return _pretext;
17
+ }
18
+ async function getHyphenator(language) {
19
+ let dict;
20
+ try {
21
+ const mod = await import(`hyphenation.${language}`);
22
+ dict = mod.default ?? mod;
23
+ }
24
+ catch {
25
+ throw new PretextPdfError('UNSUPPORTED_LANGUAGE', `Hyphenation dictionary for "${language}" not found. Install it with: pnpm add hyphenation.${language}`);
26
+ }
27
+ // @ts-ignore hypher has no type definitions available
28
+ const { default: Hypher } = await import('hypher');
29
+ return new Hypher(dict);
30
+ }
31
+ // ─── RTL Text Support (Unicode Bidirectional Algorithm via bidi-js) ────────────
32
+ /**
33
+ * Detect text direction and apply Unicode Bidi Algorithm (TR9) for visual reordering.
34
+ * Returns the visual-order text ready for measurement and rendering.
35
+ *
36
+ * @param text Logical-order input text (how user types it)
37
+ * @param dirOverride Explicit direction override ('ltr', 'rtl', or 'auto')
38
+ * @returns { visual, isRTL, logical } where visual is reordered text ready to render
39
+ */
40
+ async function detectAndReorderRTL(text, dirOverride) {
41
+ // Step 1: Explicit override takes priority
42
+ if (dirOverride === 'ltr') {
43
+ return { visual: text, isRTL: false, logical: text };
44
+ }
45
+ if (dirOverride === 'rtl') {
46
+ // Even with override, apply bidi algorithm to get correct visual order
47
+ try {
48
+ // @ts-ignore bidi-js has no type definitions
49
+ const bidiFactory = (await import('bidi-js')).default;
50
+ const bidi = typeof bidiFactory === 'function' ? bidiFactory() : bidiFactory;
51
+ const { getEmbeddingLevels, getReorderedString } = bidi;
52
+ const embedLevelsResult = getEmbeddingLevels(text, 'rtl');
53
+ const visual = getReorderedString(text, embedLevelsResult);
54
+ return { visual, isRTL: true, logical: text };
55
+ }
56
+ catch (err) {
57
+ console.warn('bidi-js error during RTL reordering:', err, '— falling back to logical order');
58
+ return { visual: text, isRTL: false, logical: text };
59
+ }
60
+ }
61
+ // Step 2: Auto-detect dominant direction
62
+ // Hebrew (U+0590–U+05FF), Arabic (U+0600–U+06FF), Syriac (U+0700–U+074F)
63
+ const rtlRanges = /[\u0590-\u05FF\u0600-\u06FF\u0700-\u074F]/g;
64
+ const rtlCount = (text.match(rtlRanges) ?? []).length;
65
+ const ltrCount = (text.match(/[a-zA-Z0-9]/g) ?? []).length;
66
+ const isRTL = rtlCount > 0 && rtlCount >= ltrCount;
67
+ if (!isRTL) {
68
+ return { visual: text, isRTL: false, logical: text };
69
+ }
70
+ // Step 3: Apply bidi algorithm (TR9) to reorder visually
71
+ try {
72
+ // @ts-ignore bidi-js has no type definitions
73
+ const bidiFactory = (await import('bidi-js')).default;
74
+ const bidi = typeof bidiFactory === 'function' ? bidiFactory() : bidiFactory;
75
+ const { getEmbeddingLevels, getReorderedString } = bidi;
76
+ const embedLevelsResult = getEmbeddingLevels(text, 'rtl');
77
+ const visual = getReorderedString(text, embedLevelsResult);
78
+ return { visual, isRTL: true, logical: text };
79
+ }
80
+ catch (err) {
81
+ // Graceful fallback: if bidi-js throws (rare), use logical order
82
+ console.warn('bidi-js error during RTL reordering:', err, '— falling back to logical order');
83
+ return { visual: text, isRTL: false, logical: text };
84
+ }
85
+ }
86
+ /**
87
+ * Measure a single word's rendered width using pretext at maxWidth=99999.
88
+ */
89
+ async function measureWord(word, fontString) {
90
+ const { prepareWithSegments, layoutWithLines } = await getPretext();
91
+ if (!word)
92
+ return 0;
93
+ const prepared = prepareWithSegments(word, fontString, {});
94
+ const result = layoutWithLines(prepared, 99999, 99999);
95
+ const lines = result.lines ?? [];
96
+ return lines[0]?.width ?? 0;
97
+ }
98
+ /**
99
+ * Stage 3: Measure a single content element.
100
+ *
101
+ * Returns MeasuredBlock for most types.
102
+ * Returns MeasuredBlock[] for 'list' (each item becomes an independent block).
103
+ *
104
+ * NOTE: Image elements cannot be measured here — use measureAllBlocks() instead,
105
+ * which resolves the content-index-based imageMap key before calling measureImageWithKey().
106
+ */
107
+ export async function measureBlock(element, contentWidth, doc, hyphenatorOpts) {
108
+ const baseFontSize = doc.defaultFontSize ?? 12;
109
+ const baseFont = doc.defaultFont ?? 'Inter';
110
+ switch (element.type) {
111
+ case 'spacer': {
112
+ return {
113
+ element,
114
+ height: element.height,
115
+ lines: [],
116
+ fontSize: 0,
117
+ lineHeight: 0,
118
+ fontKey: '',
119
+ spaceAfter: 0,
120
+ spaceBefore: 0,
121
+ };
122
+ }
123
+ case 'page-break': {
124
+ return {
125
+ element,
126
+ height: 0,
127
+ lines: [],
128
+ fontSize: 0,
129
+ lineHeight: 0,
130
+ fontKey: '',
131
+ spaceAfter: 0,
132
+ spaceBefore: 0,
133
+ };
134
+ }
135
+ case 'paragraph': {
136
+ // NEW (Phase 7F): Detect and reorder RTL text
137
+ const { visual: visualText, isRTL, logical: logicalText } = await detectAndReorderRTL(element.text, element.dir);
138
+ const fontSize = element.fontSize ?? baseFontSize;
139
+ const lineHeight = element.lineHeight ?? doc.defaultLineHeight ?? (fontSize * 1.5);
140
+ const fontFamily = element.fontFamily ?? baseFont;
141
+ const fontWeight = element.fontWeight ?? 400;
142
+ const fontKey = buildFontKey(fontFamily, fontWeight, 'normal');
143
+ const columns = element.columns ?? 1;
144
+ const columnGap = element.columnGap ?? 24;
145
+ let measureWidth = contentWidth;
146
+ let columnData;
147
+ // Multi-column layout
148
+ if (columns > 1) {
149
+ const columnWidth = (contentWidth - (columns - 1) * columnGap) / columns;
150
+ if (columnWidth < 50) {
151
+ throw new PretextPdfError('COLUMN_WIDTH_TOO_NARROW', `Column width would be ${columnWidth.toFixed(1)}pt, which is below the minimum 50pt. Reduce columns, increase columnGap, or increase page width.`);
152
+ }
153
+ measureWidth = columnWidth;
154
+ }
155
+ const opts = hyphenatorOpts && element.hyphenate !== false ? hyphenatorOpts : undefined;
156
+ // CRITICAL (Phase 7F): Measure the VISUAL-ORDER text (what will actually be rendered)
157
+ const lines = await measureText(visualText, fontSize, fontFamily, fontWeight, measureWidth, lineHeight, opts);
158
+ if (columns > 1) {
159
+ const columnWidth = (contentWidth - (columns - 1) * columnGap) / columns;
160
+ const linesPerColumn = Math.ceil(lines.length / columns);
161
+ columnData = { columnCount: columns, columnGap, columnWidth, linesPerColumn };
162
+ }
163
+ // Construct result with or without columnData depending on columns value
164
+ if (columnData) {
165
+ return {
166
+ element,
167
+ height: columnData.linesPerColumn * lineHeight,
168
+ lines,
169
+ fontSize,
170
+ lineHeight,
171
+ fontKey,
172
+ spaceAfter: element.spaceAfter ?? 0,
173
+ spaceBefore: element.spaceBefore ?? 0,
174
+ columnData,
175
+ isRTL, // NEW (Phase 7F)
176
+ ...(isRTL && { logicalText }), // NEW: Only store logical text when RTL
177
+ };
178
+ }
179
+ else {
180
+ return {
181
+ element,
182
+ height: lines.length * lineHeight,
183
+ lines,
184
+ fontSize,
185
+ lineHeight,
186
+ fontKey,
187
+ spaceAfter: element.spaceAfter ?? 0,
188
+ spaceBefore: element.spaceBefore ?? 0,
189
+ isRTL, // NEW (Phase 7F)
190
+ ...(isRTL && { logicalText }), // NEW: Only store logical text when RTL
191
+ };
192
+ }
193
+ }
194
+ case 'heading': {
195
+ // NEW (Phase 7F): Detect and reorder RTL text
196
+ const { visual: visualText, isRTL, logical: logicalText } = await detectAndReorderRTL(element.text, element.dir);
197
+ const defaults = HEADING_DEFAULTS[element.level];
198
+ const fontSize = element.fontSize ?? (baseFontSize * defaults.sizeMultiplier);
199
+ const lineHeight = element.lineHeight ?? doc.defaultLineHeight ?? (fontSize * 1.4); // tighter for headings
200
+ const fontFamily = element.fontFamily ?? baseFont;
201
+ const fontWeight = element.fontWeight ?? defaults.fontWeight;
202
+ const fontKey = buildFontKey(fontFamily, fontWeight, 'normal');
203
+ const opts = hyphenatorOpts && element.hyphenate !== false ? hyphenatorOpts : undefined;
204
+ // CRITICAL (Phase 7F): Measure the VISUAL-ORDER text (what will actually be rendered)
205
+ const lines = await measureText(visualText, fontSize, fontFamily, fontWeight, contentWidth, lineHeight, opts);
206
+ return {
207
+ element,
208
+ height: lines.length * lineHeight,
209
+ lines,
210
+ fontSize,
211
+ lineHeight,
212
+ fontKey,
213
+ spaceAfter: element.spaceAfter ?? defaults.spaceAfter,
214
+ spaceBefore: element.spaceBefore ?? defaults.spaceBefore,
215
+ isRTL, // NEW (Phase 7F)
216
+ ...(isRTL && { logicalText }), // NEW: Only store logical text when RTL
217
+ };
218
+ }
219
+ case 'hr': {
220
+ const spaceAbove = element.spaceAbove ?? 12;
221
+ const thickness = element.thickness ?? 0.5;
222
+ const spaceBelow = element.spaceBelow ?? 12;
223
+ return {
224
+ element,
225
+ height: spaceAbove + thickness + spaceBelow,
226
+ lines: [],
227
+ fontSize: 0,
228
+ lineHeight: 0,
229
+ fontKey: '',
230
+ spaceAfter: 0,
231
+ spaceBefore: 0,
232
+ };
233
+ }
234
+ case 'image': {
235
+ // Image elements must be measured via measureAllBlocks() — not measureBlock() directly.
236
+ // measureAllBlocks() resolves the content-index-based imageMap key (img-N) before calling
237
+ // measureImageWithKey(). measureBlock() doesn't have access to the content index.
238
+ throw new PretextPdfError('VALIDATION_ERROR', 'Image elements cannot be measured via measureBlock() directly — use measureAllBlocks() which resolves the imageMap key correctly.');
239
+ }
240
+ case 'svg': {
241
+ // SVG elements must be measured via measureAllBlocks() — not measureBlock() directly.
242
+ // measureAllBlocks() resolves the content-index-based imageMap key (svg-N) before calling
243
+ // measureImageWithKey(). measureBlock() doesn't have access to the content index.
244
+ throw new PretextPdfError('VALIDATION_ERROR', 'SVG elements cannot be measured via measureBlock() directly — use measureAllBlocks() which resolves the imageMap key correctly.');
245
+ }
246
+ case 'list': {
247
+ return measureList(element, contentWidth, doc, baseFontSize, hyphenatorOpts);
248
+ }
249
+ case 'table': {
250
+ return measureTable(element, contentWidth, doc, baseFontSize, hyphenatorOpts);
251
+ }
252
+ case 'rich-paragraph': {
253
+ // NEW (Phase 7F): Detect paragraph-level RTL direction (for alignment default)
254
+ // Individual spans can override via span.dir, but paragraph.dir sets the default
255
+ const fullText = element.spans.map(s => s.text).join('');
256
+ const { isRTL } = await detectAndReorderRTL(fullText, element.dir);
257
+ const fontSize = element.fontSize ?? baseFontSize;
258
+ const lineHeight = element.lineHeight ?? doc.defaultLineHeight ?? (fontSize * 1.5);
259
+ // 'justify' uses left alignment for measurement (justify is rendering-only)
260
+ const alignRaw = element.align ?? 'left';
261
+ const align = alignRaw === 'justify' ? 'left' : alignRaw;
262
+ const columns = element.columns ?? 1;
263
+ const columnGap = element.columnGap ?? 24;
264
+ let measureWidth = contentWidth;
265
+ let columnData;
266
+ // Multi-column layout
267
+ if (columns > 1) {
268
+ const columnWidth = (contentWidth - (columns - 1) * columnGap) / columns;
269
+ if (columnWidth < 50) {
270
+ throw new PretextPdfError('COLUMN_WIDTH_TOO_NARROW', `Column width would be ${columnWidth.toFixed(1)}pt, which is below the minimum 50pt. Reduce columns, increase columnGap, or increase page width.`);
271
+ }
272
+ measureWidth = columnWidth;
273
+ }
274
+ const richLines = await measureRichText(element.spans, fontSize, lineHeight, measureWidth, align, doc);
275
+ if (columns > 1) {
276
+ const columnWidth = (contentWidth - (columns - 1) * columnGap) / columns;
277
+ const linesPerColumn = Math.ceil(richLines.length / columns);
278
+ columnData = { columnCount: columns, columnGap, columnWidth, linesPerColumn };
279
+ }
280
+ // For paginator/renderer compatibility, also produce a flat lines[] array
281
+ // (used for orphan/widow logic and line-count-based pagination).
282
+ // Each RichLine becomes one PretextLine with its totalWidth.
283
+ const lines = richLines.map(rl => ({
284
+ text: rl.fragments.map(f => f.text).join(''),
285
+ width: rl.totalWidth,
286
+ }));
287
+ // Construct result with or without columnData depending on columns value
288
+ // Phase 5B.4: Block height = sum of per-line heights (variable when spans have different fontSize)
289
+ const blockHeight = richLines.reduce((sum, rl) => sum + rl.lineHeight, 0);
290
+ if (columnData) {
291
+ return {
292
+ element,
293
+ height: blockHeight, // richLines already have per-line heights
294
+ lines,
295
+ fontSize,
296
+ lineHeight,
297
+ fontKey: buildFontKey(doc.defaultFont ?? 'Inter', 400, 'normal'),
298
+ spaceAfter: element.spaceAfter ?? 0,
299
+ spaceBefore: element.spaceBefore ?? 0,
300
+ richLines,
301
+ columnData,
302
+ isRTL, // NEW (Phase 7F)
303
+ };
304
+ }
305
+ else {
306
+ return {
307
+ element,
308
+ height: blockHeight, // richLines already have per-line heights
309
+ lines,
310
+ fontSize,
311
+ lineHeight,
312
+ fontKey: buildFontKey(doc.defaultFont ?? 'Inter', 400, 'normal'),
313
+ spaceAfter: element.spaceAfter ?? 0,
314
+ spaceBefore: element.spaceBefore ?? 0,
315
+ richLines,
316
+ isRTL, // NEW (Phase 7F)
317
+ };
318
+ }
319
+ }
320
+ case 'code': {
321
+ const fontSize = element.fontSize ?? Math.max(baseFontSize - 2, 8);
322
+ const lineHeight = element.lineHeight ?? (fontSize * 1.4);
323
+ const padding = element.padding ?? 8;
324
+ // Text area is narrower by padding on both sides
325
+ const textWidth = contentWidth - 2 * padding;
326
+ // Code blocks: never hyphenate — breaks would corrupt source code meaning
327
+ // Code blocks: always measure in logical (LTR) order — reordering breaks syntax
328
+ const lines = await measureText(element.text, fontSize, element.fontFamily, 400, Math.max(textWidth, 1), lineHeight);
329
+ // height = lines * lineHeight + padding top + padding bottom
330
+ const height = (lines.length || 1) * lineHeight + 2 * padding;
331
+ return {
332
+ element,
333
+ height,
334
+ lines,
335
+ fontSize,
336
+ lineHeight,
337
+ fontKey: buildFontKey(element.fontFamily, 400, 'normal'),
338
+ spaceAfter: element.spaceAfter ?? 12,
339
+ spaceBefore: element.spaceBefore ?? 12,
340
+ codePadding: padding,
341
+ isRTL: false, // NEW (Phase 7F): Code blocks always LTR
342
+ };
343
+ }
344
+ case 'blockquote': {
345
+ // NEW (Phase 7F): Detect and reorder RTL text
346
+ const { visual: visualText, isRTL, logical: logicalText } = await detectAndReorderRTL(element.text, element.dir);
347
+ const fontSize = element.fontSize ?? baseFontSize;
348
+ const lineHeight = element.lineHeight ?? doc.defaultLineHeight ?? (fontSize * 1.5);
349
+ const fontFamily = element.fontFamily ?? baseFont;
350
+ const fontWeight = element.fontWeight ?? 400;
351
+ const fontStyle = element.fontStyle ?? 'normal';
352
+ const fontKey = buildFontKey(fontFamily, fontWeight, fontStyle);
353
+ const borderWidth = element.borderWidth ?? 3;
354
+ const paddingH = element.paddingH ?? element.padding ?? 16;
355
+ const paddingV = element.paddingV ?? element.padding ?? 10;
356
+ // Text area excludes left border + horizontal padding on both sides
357
+ const textWidth = contentWidth - borderWidth - 2 * paddingH;
358
+ // CRITICAL (Phase 7F): Measure the VISUAL-ORDER text (what will actually be rendered)
359
+ const lines = await measureText(visualText, fontSize, fontFamily, fontWeight, Math.max(textWidth, 1), lineHeight, hyphenatorOpts);
360
+ // height = lines * lineHeight + padding top + padding bottom
361
+ const height = (lines.length || 1) * lineHeight + 2 * paddingV;
362
+ return {
363
+ element,
364
+ height,
365
+ lines,
366
+ fontSize,
367
+ lineHeight,
368
+ fontKey,
369
+ spaceAfter: element.spaceAfter ?? 12,
370
+ spaceBefore: element.spaceBefore ?? 0,
371
+ blockquotePaddingV: paddingV,
372
+ blockquotePaddingH: paddingH,
373
+ blockquoteBorderWidth: borderWidth,
374
+ isRTL, // NEW (Phase 7F)
375
+ ...(isRTL && { logicalText }), // NEW: Only store logical text when RTL
376
+ };
377
+ }
378
+ case 'toc': {
379
+ // Placeholder: zero height. Will be replaced by actual TOC entries in two-pass mode.
380
+ return {
381
+ element,
382
+ height: 0,
383
+ lines: [],
384
+ fontSize: 0,
385
+ lineHeight: 0,
386
+ fontKey: '',
387
+ spaceAfter: element.spaceAfter ?? 0,
388
+ spaceBefore: element.spaceBefore ?? 0,
389
+ };
390
+ }
391
+ case 'toc-entry': {
392
+ // Internal type - should never be measured directly by user input
393
+ throw new PretextPdfError('VALIDATION_ERROR', 'toc-entry is an internal type and cannot be used in document content');
394
+ }
395
+ }
396
+ }
397
+ // ─── HR is trivial (handled inline above) ────────────────────────────────────
398
+ // ─── Image measurement ────────────────────────────────────────────────────────
399
+ /** Measure an image element with its known imageMap key */
400
+ async function measureImageWithKey(element, imageKey, imageMap, contentWidth, pageContentHeight) {
401
+ const pdfImage = imageMap.get(imageKey);
402
+ if (!pdfImage) {
403
+ throw new PretextPdfError('IMAGE_LOAD_FAILED', `Image "${imageKey}": not found in imageMap. This is an internal error — please report it.`);
404
+ }
405
+ // Natural dimensions (in original pixels — aspect ratio is what matters, not the pixel count)
406
+ const naturalWidth = pdfImage.width;
407
+ const naturalHeight = pdfImage.height;
408
+ // Resolve render dimensions (in pt)
409
+ let renderWidth;
410
+ let renderHeight;
411
+ if (element.width !== undefined && element.height !== undefined) {
412
+ // Both provided: use as-is
413
+ renderWidth = element.width;
414
+ renderHeight = element.height;
415
+ }
416
+ else if (element.width !== undefined) {
417
+ // Width only: scale height
418
+ renderWidth = element.width;
419
+ renderHeight = renderWidth * (naturalHeight / naturalWidth);
420
+ }
421
+ else if (element.height !== undefined) {
422
+ // Height only: scale width
423
+ renderHeight = element.height;
424
+ renderWidth = renderHeight * (naturalWidth / naturalHeight);
425
+ }
426
+ else {
427
+ // Neither: fit to content width
428
+ renderWidth = contentWidth;
429
+ renderHeight = renderWidth * (naturalHeight / naturalWidth);
430
+ }
431
+ // Clamp to content width
432
+ if (renderWidth > contentWidth) {
433
+ const scale = contentWidth / renderWidth;
434
+ renderWidth = contentWidth;
435
+ renderHeight = renderHeight * scale;
436
+ }
437
+ // Validate height doesn't exceed page
438
+ if (renderHeight > pageContentHeight) {
439
+ throw new PretextPdfError('IMAGE_TOO_TALL', `Image "${imageKey}" would render at ${renderHeight.toFixed(1)}pt tall, which exceeds the page content area (${pageContentHeight.toFixed(1)}pt). ` +
440
+ `Reduce 'height' or increase page size/reduce margins.`);
441
+ }
442
+ const imageData = {
443
+ imageKey,
444
+ renderWidth,
445
+ renderHeight,
446
+ align: element.align ?? 'left',
447
+ };
448
+ return {
449
+ element,
450
+ height: renderHeight,
451
+ lines: [],
452
+ fontSize: 0,
453
+ lineHeight: 0,
454
+ fontKey: '',
455
+ spaceAfter: element.spaceAfter ?? 0,
456
+ spaceBefore: element.spaceBefore ?? 0,
457
+ imageData,
458
+ };
459
+ }
460
+ // ─── List measurement (returns MeasuredBlock[]) ───────────────────────────────
461
+ async function measureList(element, contentWidth, doc, baseFontSize, hyphenatorOpts) {
462
+ const baseFontFamily = doc.defaultFont ?? 'Inter';
463
+ const fontSize = element.fontSize ?? baseFontSize;
464
+ const lineHeight = element.lineHeight ?? doc.defaultLineHeight ?? (fontSize * 1.5);
465
+ const indent = element.indent ?? 20;
466
+ const markerWidth = element.markerWidth ?? 20;
467
+ const itemSpaceAfter = element.itemSpaceAfter ?? 4;
468
+ const fontKey = buildFontKey(baseFontFamily, 400, 'normal');
469
+ // Width available for item text (after indent + marker column)
470
+ const textWidth = contentWidth - indent - markerWidth;
471
+ if (textWidth <= 0) {
472
+ throw new PretextPdfError('VALIDATION_ERROR', `List indent (${indent}pt) + markerWidth (${markerWidth}pt) exceeds contentWidth (${contentWidth}pt). Reduce indent or markerWidth.`);
473
+ }
474
+ const blocks = [];
475
+ // Flatten items and nested items
476
+ const nestedStyle = element.nestedNumberingStyle ?? 'continue';
477
+ let orderedIndex = 1;
478
+ const allItems = [];
479
+ for (let i = 0; i < element.items.length; i++) {
480
+ const item = element.items[i];
481
+ const isFirst = i === 0;
482
+ const marker = element.style === 'ordered'
483
+ ? `${orderedIndex}.`
484
+ : (element.marker ?? '•');
485
+ orderedIndex++;
486
+ allItems.push({ text: item.text, marker, isNested: false, isFirstInList: isFirst, fontWeight: item.fontWeight ?? 400 });
487
+ // Nested items (1 level deep)
488
+ if (item.items && item.items.length > 0) {
489
+ // 'restart': nested ordered items count from 1, parent counter unaffected
490
+ // 'continue': nested items share the parent counter (existing behavior)
491
+ let nestedIndex = nestedStyle === 'restart' ? 1 : orderedIndex;
492
+ for (let ni = 0; ni < item.items.length; ni++) {
493
+ const nested = item.items[ni];
494
+ const nestedMarker = element.style === 'ordered'
495
+ ? `${nestedIndex}.`
496
+ : '◦'; // hollow bullet for nested unordered
497
+ nestedIndex++;
498
+ if (nestedStyle === 'continue')
499
+ orderedIndex++;
500
+ allItems.push({ text: nested.text, marker: nestedMarker, isNested: true, isFirstInList: false, fontWeight: nested.fontWeight ?? 400 });
501
+ }
502
+ }
503
+ }
504
+ for (let i = 0; i < allItems.length; i++) {
505
+ const item = allItems[i];
506
+ const isLast = i === allItems.length - 1;
507
+ const nestedIndent = item.isNested ? indent + markerWidth : indent;
508
+ const nestedTextWidth = item.isNested ? textWidth - markerWidth : textWidth;
509
+ const lines = await measureText(item.text, fontSize, baseFontFamily, item.fontWeight, nestedTextWidth, lineHeight, hyphenatorOpts);
510
+ const listItemData = {
511
+ marker: item.marker,
512
+ indent: nestedIndent,
513
+ markerWidth,
514
+ color: element.color ?? '#000000',
515
+ fontWeight: item.fontWeight,
516
+ };
517
+ // spaceBefore: only the first item in the entire list gets the list's spaceBefore
518
+ // spaceAfter: itemSpaceAfter between items, list.spaceAfter on the last item
519
+ const spaceBefore = item.isFirstInList ? (element.spaceBefore ?? 0) : 0;
520
+ const spaceAfter = isLast ? (element.spaceAfter ?? 0) : itemSpaceAfter;
521
+ blocks.push({
522
+ element, // All items share the parent ListElement (for type checking in renderer)
523
+ height: Math.max(lines.length, 1) * lineHeight,
524
+ lines,
525
+ fontSize,
526
+ lineHeight,
527
+ fontKey,
528
+ spaceAfter,
529
+ spaceBefore,
530
+ listItemData,
531
+ });
532
+ }
533
+ return blocks;
534
+ }
535
+ // ─── Table measurement ────────────────────────────────────────────────────────
536
+ async function measureTable(element, contentWidth, doc, baseFontSize, hyphenatorOpts) {
537
+ const baseFontFamily = doc.defaultFont ?? 'Inter';
538
+ const fontSize = element.fontSize ?? baseFontSize;
539
+ const lineHeight = doc.defaultLineHeight ?? (fontSize * 1.5);
540
+ const cellPaddingH = element.cellPaddingH ?? 8;
541
+ const cellPaddingV = element.cellPaddingV ?? 6;
542
+ const borderWidth = element.borderWidth ?? 0.5;
543
+ const borderColor = element.borderColor ?? '#cccccc';
544
+ const headerBgColor = element.headerBgColor ?? '#f5f5f5';
545
+ // Pre-pass: measure natural widths for 'auto' columns
546
+ // NOTE: with colspan, we map cells to their starting column index
547
+ const hasAutoColumns = element.columns.some(c => c.width === 'auto');
548
+ let naturalWidths;
549
+ if (hasAutoColumns) {
550
+ naturalWidths = new Array(element.columns.length).fill(0);
551
+ for (const row of element.rows) {
552
+ let colIdx = 0; // track column position accounting for colspan
553
+ for (const cell of row.cells) {
554
+ const cs = cell.colspan ?? 1;
555
+ // For auto columns: measure natural width and distribute across spanned columns
556
+ // For now, attribute full width to the first column of the span
557
+ if (element.columns[colIdx]?.width === 'auto') {
558
+ const fontWeight = cell.fontWeight ?? (row.isHeader ? 700 : 400);
559
+ const cellFontSize = cell.fontSize ?? fontSize;
560
+ const cellFamily = cell.fontFamily ?? baseFontFamily;
561
+ const w = await measureNaturalTextWidth(cell.text, cellFontSize, cellFamily, fontWeight);
562
+ const cellNaturalWidth = w + 2 * cellPaddingH;
563
+ // Distribute across spanned columns
564
+ const perColumn = cellNaturalWidth / cs;
565
+ for (let si = colIdx; si < colIdx + cs && si < element.columns.length; si++) {
566
+ if (element.columns[si]?.width === 'auto') {
567
+ naturalWidths[si] = Math.max(naturalWidths[si], perColumn);
568
+ }
569
+ }
570
+ }
571
+ colIdx += cs;
572
+ }
573
+ }
574
+ }
575
+ // Resolve column widths (passes naturalWidths for 'auto' columns)
576
+ const columnWidths = resolveColumnWidths(element.columns, contentWidth, cellPaddingH, borderWidth, naturalWidths);
577
+ // Determine header row count
578
+ const headerRowCount = element.headerRows !== undefined
579
+ ? element.headerRows
580
+ : element.rows.filter(r => r.isHeader).length;
581
+ // Measure all rows
582
+ const measuredRows = [];
583
+ for (const row of element.rows) {
584
+ const measuredCells = [];
585
+ let maxCellHeight = 0;
586
+ let colStart = 0; // track column position accounting for colspan
587
+ for (const cell of row.cells) {
588
+ const cs = cell.colspan ?? 1;
589
+ const col = element.columns[colStart];
590
+ // Calculate merged width: sum of spanned column widths + borders between them
591
+ let mergedWidth = 0;
592
+ for (let si = colStart; si < colStart + cs && si < columnWidths.length; si++) {
593
+ mergedWidth += columnWidths[si];
594
+ if (si < colStart + cs - 1)
595
+ mergedWidth += borderWidth; // border between columns
596
+ }
597
+ const fontWeight = cell.fontWeight ?? (row.isHeader ? 700 : 400);
598
+ const fontFamily = cell.fontFamily ?? baseFontFamily;
599
+ const cellFontSize = cell.fontSize ?? fontSize;
600
+ const cellLineHeight = doc.defaultLineHeight ?? (cellFontSize * 1.5);
601
+ const fontKey = buildFontKey(fontFamily, fontWeight, 'normal');
602
+ // Text area is narrower than merged cell (padding on both sides + border)
603
+ const textWidth = mergedWidth - 2 * cellPaddingH - borderWidth;
604
+ const lines = await measureText(cell.text, cellFontSize, fontFamily, fontWeight, Math.max(textWidth, 1), cellLineHeight, hyphenatorOpts);
605
+ const cellContentHeight = Math.max(lines.length, 1) * cellLineHeight;
606
+ maxCellHeight = Math.max(maxCellHeight, cellContentHeight);
607
+ // RTL detection for table cells (same as paragraphs)
608
+ const cellDir = cell.dir ?? 'auto';
609
+ const { isRTL: cellIsRTL } = await detectAndReorderRTL(cell.text, cellDir);
610
+ // Apply RTL alignment default: if align not explicitly set and text is RTL, default to right
611
+ const align = cell.align ?? col.align ?? (cellIsRTL ? 'right' : 'left');
612
+ const measuredCell = {
613
+ lines,
614
+ fontSize: cellFontSize,
615
+ lineHeight: cellLineHeight,
616
+ fontKey,
617
+ fontFamily,
618
+ align,
619
+ color: cell.color ?? '#000000',
620
+ colspan: cs,
621
+ mergedWidth,
622
+ isRTL: cellIsRTL,
623
+ };
624
+ if (cell.bgColor !== undefined)
625
+ measuredCell.bgColor = cell.bgColor;
626
+ measuredCells.push(measuredCell);
627
+ colStart += cs;
628
+ }
629
+ // Row height = tallest cell content + vertical padding on both sides
630
+ const rowHeight = maxCellHeight + 2 * cellPaddingV;
631
+ // Compute which column boundaries have active vertical lines (not spanned by merged cells)
632
+ const activeBoundaries = computeActiveBoundaries(row.cells, element.columns.length);
633
+ measuredRows.push({
634
+ cells: measuredCells,
635
+ height: rowHeight,
636
+ isHeader: row.isHeader ?? false,
637
+ activeBoundaries,
638
+ });
639
+ }
640
+ // Header rows are the first N rows
641
+ const headerRows = measuredRows.slice(0, headerRowCount);
642
+ const headerRowHeight = headerRows.reduce((sum, r) => sum + r.height, 0);
643
+ // Total table height = sum of all row heights
644
+ const totalHeight = measuredRows.reduce((sum, r) => sum + r.height, 0);
645
+ const tableData = {
646
+ columnWidths,
647
+ rows: measuredRows,
648
+ headerRowCount,
649
+ headerRowHeight,
650
+ cellPaddingH,
651
+ cellPaddingV,
652
+ borderWidth,
653
+ borderColor,
654
+ headerBgColor,
655
+ };
656
+ return {
657
+ element,
658
+ height: totalHeight,
659
+ lines: [],
660
+ fontSize: 0,
661
+ lineHeight: 0,
662
+ fontKey: '',
663
+ spaceAfter: element.spaceAfter ?? 0,
664
+ spaceBefore: element.spaceBefore ?? 0,
665
+ tableData,
666
+ };
667
+ }
668
+ // ─── Column width resolution ──────────────────────────────────────────────────
669
+ /**
670
+ * Resolve column width definitions to concrete pt values.
671
+ * Fixed widths are used as-is. Star widths ('2*', '*') share the remaining space.
672
+ * 'auto' columns use naturalWidths[i] (measured content width) — caller must pre-compute these.
673
+ *
674
+ * naturalWidths is required if any column uses 'auto'. It maps column index → natural text width in pt
675
+ * (the minimum width needed to display cell text on one line, including cellPaddingH on both sides).
676
+ */
677
+ export function resolveColumnWidths(columns, contentWidth, cellPaddingH, borderWidth, naturalWidths) {
678
+ const MIN_COLUMN_WIDTH = cellPaddingH * 2 + borderWidth * 2 + 4; // minimum usable pt
679
+ let totalFixed = 0;
680
+ let totalStars = 0;
681
+ let totalAutoNatural = 0;
682
+ let autoCount = 0;
683
+ for (let i = 0; i < columns.length; i++) {
684
+ const col = columns[i];
685
+ if (typeof col.width === 'number') {
686
+ totalFixed += col.width;
687
+ }
688
+ else if (col.width === 'auto') {
689
+ // Auto columns reserve their natural width from remaining space
690
+ const natural = naturalWidths?.[i] ?? MIN_COLUMN_WIDTH;
691
+ totalAutoNatural += natural;
692
+ autoCount++;
693
+ }
694
+ else {
695
+ // '*' → 1 star, '2*' → 2 stars, '1.5*' → 1.5 stars
696
+ const match = col.width.match(/^(\d*\.?\d*)?\*$/);
697
+ const stars = (match && match[1]) ? parseFloat(match[1]) : 1;
698
+ totalStars += stars;
699
+ }
700
+ }
701
+ const remaining = contentWidth - totalFixed;
702
+ if (remaining < -0.01) {
703
+ throw new PretextPdfError('TABLE_COLUMN_OVERFLOW', `Table fixed column widths (${totalFixed.toFixed(1)}pt) exceed content width (${contentWidth.toFixed(1)}pt). ` +
704
+ `Reduce column widths or page margins.`);
705
+ }
706
+ // How much space is available after fixed columns
707
+ const availableForFlexible = Math.max(0, remaining);
708
+ // Auto columns claim their natural width (capped at available space).
709
+ // Star columns share whatever remains after auto columns.
710
+ // If auto columns overflow, they get proportional shares of available space.
711
+ const autoFits = totalAutoNatural <= availableForFlexible;
712
+ const autoUsed = autoFits ? totalAutoNatural : availableForFlexible;
713
+ const availableForStars = availableForFlexible - autoUsed;
714
+ const starUnit = totalStars > 0 ? Math.max(0, availableForStars) / totalStars : 0;
715
+ return columns.map((col, i) => {
716
+ let resolved;
717
+ if (typeof col.width === 'number') {
718
+ resolved = col.width;
719
+ }
720
+ else if (col.width === 'auto') {
721
+ const natural = naturalWidths?.[i] ?? MIN_COLUMN_WIDTH;
722
+ if (autoFits) {
723
+ resolved = natural;
724
+ }
725
+ else {
726
+ // Constrained: proportional share based on natural widths
727
+ resolved = totalAutoNatural > 0
728
+ ? (natural / totalAutoNatural) * availableForFlexible
729
+ : MIN_COLUMN_WIDTH;
730
+ }
731
+ }
732
+ else {
733
+ const match = col.width.match(/^(\d*\.?\d*)?\*$/);
734
+ const stars = (match && match[1]) ? parseFloat(match[1]) : 1;
735
+ resolved = stars * starUnit;
736
+ }
737
+ if (resolved < MIN_COLUMN_WIDTH) {
738
+ throw new PretextPdfError('TABLE_COLUMN_TOO_NARROW', `Table column ${i} resolved to ${resolved.toFixed(1)}pt, minimum is ${MIN_COLUMN_WIDTH.toFixed(1)}pt. ` +
739
+ `Increase the column width or reduce cellPaddingH/borderWidth.`);
740
+ }
741
+ return resolved;
742
+ });
743
+ }
744
+ /**
745
+ * Compute which column boundaries have visible vertical lines.
746
+ * A boundary is "active" (visible) if it's not spanned by any merged cell.
747
+ * Returns array of boundary indices (0 = between col 0 and 1, 1 = between col 1 and 2, etc.)
748
+ * where vertical lines should be drawn.
749
+ *
750
+ * Example: 3 columns with a cell spanning cols 0-1 → active boundaries are [1] (only between cols 1-2)
751
+ */
752
+ function computeActiveBoundaries(cells, colCount) {
753
+ // Track which boundaries are "spanned" (internal to a merged cell)
754
+ const spannedBoundaries = new Set();
755
+ let colIdx = 0;
756
+ for (const cell of cells) {
757
+ const cs = cell.colspan ?? 1;
758
+ // Boundaries internal to this cell's span are: colIdx to colIdx + cs - 1
759
+ // The internal boundaries are colIdx, colIdx+1, ..., colIdx+cs-2
760
+ for (let b = colIdx; b < colIdx + cs - 1; b++) {
761
+ spannedBoundaries.add(b);
762
+ }
763
+ colIdx += cs;
764
+ }
765
+ // Active boundaries are all boundaries (0 to colCount-2) that are NOT spanned
766
+ const activeBoundaries = [];
767
+ for (let b = 0; b < colCount - 1; b++) {
768
+ if (!spannedBoundaries.has(b)) {
769
+ activeBoundaries.push(b);
770
+ }
771
+ }
772
+ return activeBoundaries;
773
+ }
774
+ /**
775
+ * Measure the natural (unwrapped) width of text in pt.
776
+ * Uses a very large maxWidth so Pretext never wraps — returns the actual line width.
777
+ */
778
+ async function measureNaturalTextWidth(text, fontSize, fontFamily, fontWeight) {
779
+ if (!text || text.trim() === '')
780
+ return 0;
781
+ const { prepareWithSegments, layoutWithLines } = await getPretext();
782
+ const weightPrefix = fontWeight === 700 ? 'bold ' : '';
783
+ const fontString = `${weightPrefix}${fontSize}px ${fontFamily}`;
784
+ // Use a very large width to prevent wrapping; also handle multi-line text (\n)
785
+ // by taking the max line width across all lines
786
+ const prepared = prepareWithSegments(text, fontString, { whiteSpace: 'pre-wrap' });
787
+ const result = layoutWithLines(prepared, 99999, fontSize * 1.5);
788
+ const lines = result.lines ?? [];
789
+ return lines.reduce((max, line) => Math.max(max, line.width), 0);
790
+ }
791
+ // ─── Text measurement (shared by all text-bearing elements) ──────────────────
792
+ /**
793
+ * Measure text with automatic word hyphenation (Liang's algorithm via hypher).
794
+ * Splits on \n to preserve paragraph breaks; tokenizes words; greedily packs with hyphenation fallback.
795
+ */
796
+ async function measureTextWithHyphenation(text, fontString, maxWidth, opts) {
797
+ const { instance: hypher, minWordLength, leftMin, rightMin } = opts;
798
+ const widthCache = new Map();
799
+ const measure = async (w) => {
800
+ if (widthCache.has(w))
801
+ return widthCache.get(w);
802
+ const width = await measureWord(w, fontString);
803
+ widthCache.set(w, width);
804
+ return width;
805
+ };
806
+ let spaceWidth = await measure(' ');
807
+ // Fallback if canvas returns 0 for space
808
+ if (spaceWidth === 0) {
809
+ const aWidth = await measure('a');
810
+ const aaWidth = await measure('a a');
811
+ spaceWidth = aaWidth - 2 * aWidth;
812
+ if (spaceWidth <= 0)
813
+ spaceWidth = aWidth * 0.3; // Reasonable estimate
814
+ }
815
+ const allLines = [];
816
+ for (const para of text.split('\n')) {
817
+ if (!para.trim()) {
818
+ allLines.push({ text: '', width: 0 });
819
+ continue;
820
+ }
821
+ const words = para.split(/\s+/).filter(w => w.length > 0);
822
+ // Pre-measure all unique words in this paragraph
823
+ const uniqueWords = new Set(words);
824
+ for (const w of uniqueWords) {
825
+ await measure(w);
826
+ }
827
+ const lines = [];
828
+ let currentWords = [];
829
+ let currentWidth = 0;
830
+ const flush = () => {
831
+ if (currentWords.length > 0) {
832
+ lines.push({ text: currentWords.join(' '), width: currentWidth });
833
+ currentWords = [];
834
+ currentWidth = 0;
835
+ }
836
+ };
837
+ for (const word of words) {
838
+ const ww = widthCache.get(word);
839
+ const addW = currentWords.length > 0 ? spaceWidth + ww : ww;
840
+ if (currentWidth + addW <= maxWidth || currentWords.length === 0) {
841
+ currentWords.push(word);
842
+ currentWidth += addW;
843
+ }
844
+ else {
845
+ // Try hyphenation
846
+ let hyphenated = false;
847
+ if (word.length >= minWordLength) {
848
+ const sylls = hypher.hyphenate(word);
849
+ for (let split = sylls.length - 1; split >= 1; split--) {
850
+ const prefix = sylls.slice(0, split).join('');
851
+ const suffix = sylls.slice(split).join('');
852
+ if (prefix.length < leftMin || suffix.length < rightMin)
853
+ continue;
854
+ const hyphenPart = prefix + '-';
855
+ const hw = await measure(hyphenPart);
856
+ const addHW = currentWords.length > 0 ? spaceWidth + hw : hw;
857
+ if (currentWidth + addHW <= maxWidth) {
858
+ currentWords.push(hyphenPart);
859
+ currentWidth += addHW;
860
+ flush();
861
+ await measure(suffix);
862
+ currentWords = [suffix];
863
+ currentWidth = widthCache.get(suffix);
864
+ hyphenated = true;
865
+ break;
866
+ }
867
+ }
868
+ }
869
+ if (!hyphenated) {
870
+ flush();
871
+ currentWords = [word];
872
+ currentWidth = ww;
873
+ }
874
+ }
875
+ }
876
+ flush();
877
+ allLines.push(...lines);
878
+ }
879
+ return allLines;
880
+ }
881
+ /**
882
+ * Measure text using Pretext and return an array of lines (text + width).
883
+ * Empty/whitespace-only string → returns empty array (nothing to render).
884
+ * If hyphenatorOpts provided, delegates to measureTextWithHyphenation() for word-level hyphenation.
885
+ */
886
+ async function measureText(text, fontSize, fontFamily, fontWeight, maxWidth, lineHeight, hyphenatorOpts) {
887
+ if (!text || text.trim() === '')
888
+ return [];
889
+ const weightPrefix = fontWeight === 700 ? 'bold ' : '';
890
+ const fontString = `${weightPrefix}${fontSize}px ${fontFamily}`;
891
+ // Delegate to hyphenation path if enabled
892
+ if (hyphenatorOpts) {
893
+ return measureTextWithHyphenation(text, fontString, maxWidth, hyphenatorOpts);
894
+ }
895
+ const { prepareWithSegments, layoutWithLines } = await getPretext();
896
+ // whiteSpace: 'pre-wrap' — preserves \n in multi-line text. CRITICAL per Phase 1 lessons.
897
+ const prepared = prepareWithSegments(text, fontString, { whiteSpace: 'pre-wrap' });
898
+ const result = layoutWithLines(prepared, maxWidth, lineHeight);
899
+ return (result.lines ?? []).map((line) => ({
900
+ text: line.text,
901
+ width: line.width,
902
+ }));
903
+ }
904
+ /**
905
+ * Measure a short header/footer string — returns total height in pt.
906
+ */
907
+ export async function measureHeaderFooterHeight(text, fontSize, fontFamily, contentWidth, lineHeight) {
908
+ if (!text || text.trim() === '')
909
+ return 0;
910
+ const { prepareWithSegments, layoutWithLines } = await getPretext();
911
+ // Replace tokens with representative numbers for measurement
912
+ const sampleText = text
913
+ .replace('{{pageNumber}}', '99')
914
+ .replace('{{totalPages}}', '99');
915
+ const fontString = `${fontSize}px ${fontFamily}`;
916
+ const prepared = prepareWithSegments(sampleText, fontString, {});
917
+ const result = layoutWithLines(prepared, contentWidth, lineHeight);
918
+ return result.lineCount * lineHeight;
919
+ }
920
+ /** Build a font map key from family + weight + style */
921
+ export function buildFontKey(family, weight, style) {
922
+ return `${family}-${weight}-${style}`;
923
+ }
924
+ /**
925
+ * Build measured TOC entry blocks from collected headings.
926
+ * Called during two-pass mode after first pagination to generate the actual TOC content.
927
+ */
928
+ export async function buildTocEntryBlocks(headings, tocElement, contentWidth, doc) {
929
+ const minLevel = tocElement.minLevel ?? 1;
930
+ const maxLevel = tocElement.maxLevel ?? 3;
931
+ const fontSize = tocElement.fontSize ?? doc.defaultFontSize ?? 12;
932
+ const titleFontSize = tocElement.titleFontSize ?? (fontSize + 4);
933
+ const lineHeight = fontSize * 1.5;
934
+ const levelIndent = tocElement.levelIndent ?? 16;
935
+ const leader = tocElement.leader ?? '.';
936
+ const fontFamily = tocElement.fontFamily ?? doc.defaultFont ?? 'Inter';
937
+ const fontWeight = 400;
938
+ const fontKey = buildFontKey(fontFamily, fontWeight, 'normal');
939
+ const blocks = [];
940
+ // Title block (if showTitle !== false)
941
+ if (tocElement.showTitle !== false) {
942
+ const title = tocElement.title ?? 'Table of Contents';
943
+ const titleLines = await measureText(title, titleFontSize, fontFamily, 700, contentWidth, titleFontSize * 1.5, undefined);
944
+ blocks.push({
945
+ element: { type: 'toc-entry', text: title, pageNumber: -1, level: 1, levelIndent: 0, leader: '', fontFamily, fontWeight: 700 },
946
+ height: titleLines.length * (titleFontSize * 1.5),
947
+ lines: titleLines,
948
+ fontSize: titleFontSize,
949
+ lineHeight: titleFontSize * 1.5,
950
+ fontKey: buildFontKey(fontFamily, 700, 'normal'),
951
+ spaceAfter: lineHeight,
952
+ spaceBefore: 0,
953
+ tocEntryData: { entryX: 0, pageStr: '', leaderChar: '' },
954
+ });
955
+ }
956
+ // Entry blocks — one per heading in range
957
+ for (const h of headings) {
958
+ if (h.level < minLevel || h.level > maxLevel)
959
+ continue;
960
+ const indent = (h.level - minLevel) * levelIndent;
961
+ const pageStr = String(h.pageIndex + 1); // 1-based page numbers
962
+ const entryTextWidth = contentWidth - indent - 30; // reserve 30pt for page number area
963
+ const lines = await measureText(h.text, fontSize, fontFamily, fontWeight, entryTextWidth, lineHeight, undefined);
964
+ blocks.push({
965
+ element: { type: 'toc-entry', text: h.text, pageNumber: h.pageIndex + 1, level: h.level, levelIndent: indent, leader, fontFamily, fontWeight },
966
+ height: lines.length * lineHeight,
967
+ lines,
968
+ fontSize,
969
+ lineHeight,
970
+ fontKey,
971
+ spaceAfter: tocElement.entrySpacing ?? 4,
972
+ spaceBefore: 0,
973
+ tocEntryData: { entryX: indent, pageStr, leaderChar: leader },
974
+ });
975
+ }
976
+ return blocks;
977
+ }
978
+ /**
979
+ * Measure all content elements in a document.
980
+ * Handles list flattening (lists return MeasuredBlock[]).
981
+ * Handles image key resolution (images need their content-index-based key).
982
+ * Initializes hyphenator if doc.hyphenation is configured.
983
+ */
984
+ export async function measureAllBlocks(doc, contentWidth, imageMap, pageContentHeight) {
985
+ const results = [];
986
+ // Initialize hyphenator if enabled
987
+ let hyphenatorOpts;
988
+ if (doc.hyphenation) {
989
+ const { language, minWordLength = 6, leftMin = 2, rightMin = 3 } = doc.hyphenation;
990
+ const instance = await getHyphenator(language);
991
+ hyphenatorOpts = { instance, minWordLength, leftMin, rightMin };
992
+ }
993
+ for (let i = 0; i < doc.content.length; i++) {
994
+ const el = doc.content[i];
995
+ if (el.type === 'image') {
996
+ // Images need their specific imageMap key (keyed by content index in assets.ts)
997
+ const imageKey = `img-${i}`;
998
+ const block = await measureImageWithKey(el, imageKey, imageMap, contentWidth, pageContentHeight);
999
+ results.push(block);
1000
+ }
1001
+ else if (el.type === 'svg') {
1002
+ const svgKey = `svg-${i}`;
1003
+ // Synthetic ImageElement reuses existing measurement logic (aspect ratio, clamping, height validation)
1004
+ const syntheticImage = {
1005
+ type: 'image',
1006
+ src: '', // unused by measureImageWithKey — it reads from imageMap only
1007
+ ...(el.width !== undefined ? { width: el.width } : {}),
1008
+ ...(el.height !== undefined ? { height: el.height } : {}),
1009
+ ...(el.align !== undefined ? { align: el.align } : {}),
1010
+ spaceAfter: el.spaceAfter ?? 8,
1011
+ spaceBefore: el.spaceBefore ?? 8,
1012
+ };
1013
+ const block = await measureImageWithKey(syntheticImage, svgKey, imageMap, contentWidth, pageContentHeight);
1014
+ block.element = el;
1015
+ results.push(block);
1016
+ }
1017
+ else {
1018
+ const result = await measureBlock(el, contentWidth, doc, hyphenatorOpts);
1019
+ if (Array.isArray(result)) {
1020
+ results.push(...result);
1021
+ }
1022
+ else {
1023
+ results.push(result);
1024
+ }
1025
+ }
1026
+ }
1027
+ return results;
1028
+ }
1029
+ //# sourceMappingURL=measure.js.map