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