@patrickdk77/xfa-flatten 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +14 -0
  4. package/README.md +112 -2
  5. package/dist/barcode-paint.d.ts +11 -0
  6. package/dist/barcode-paint.js +135 -0
  7. package/dist/barcode.d.ts +45 -0
  8. package/dist/barcode.js +750 -0
  9. package/dist/canvas.d.ts +59 -0
  10. package/dist/canvas.js +179 -0
  11. package/dist/cli.d.ts +2 -0
  12. package/dist/cli.js +34 -0
  13. package/dist/css.d.ts +48 -0
  14. package/dist/css.js +288 -0
  15. package/dist/deadline.d.ts +6 -0
  16. package/dist/deadline.js +18 -0
  17. package/dist/filters.d.ts +21 -0
  18. package/dist/filters.js +296 -0
  19. package/dist/flatten.d.ts +25 -0
  20. package/dist/flatten.js +319 -0
  21. package/dist/font-metrics.d.ts +9 -0
  22. package/dist/font-metrics.js +215 -0
  23. package/dist/fonts.d.ts +36 -0
  24. package/dist/fonts.js +144 -0
  25. package/dist/images.d.ts +23 -0
  26. package/dist/images.js +519 -0
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.js +5 -0
  29. package/dist/index.mjs +3 -0
  30. package/dist/layout.d.ts +64 -0
  31. package/dist/layout.js +779 -0
  32. package/dist/limits.d.ts +2 -0
  33. package/dist/limits.js +6 -0
  34. package/dist/locale.d.ts +29 -0
  35. package/dist/locale.js +97 -0
  36. package/dist/paint.d.ts +15 -0
  37. package/dist/paint.js +533 -0
  38. package/dist/pdf-crypt.d.ts +35 -0
  39. package/dist/pdf-crypt.js +261 -0
  40. package/dist/pdf-read.d.ts +140 -0
  41. package/dist/pdf-read.js +1026 -0
  42. package/dist/pdf417-table.d.ts +2 -0
  43. package/dist/pdf417-table.js +146 -0
  44. package/dist/pdfjs-repair.d.ts +13 -0
  45. package/dist/pdfjs-repair.js +257 -0
  46. package/dist/pdfjs.d.ts +16 -0
  47. package/dist/pdfjs.js +62 -0
  48. package/dist/picture.d.ts +40 -0
  49. package/dist/picture.js +678 -0
  50. package/dist/saslprep.d.ts +11 -0
  51. package/dist/saslprep.js +178 -0
  52. package/dist/style.d.ts +29 -0
  53. package/dist/style.js +178 -0
  54. package/dist/text.d.ts +44 -0
  55. package/dist/text.js +199 -0
  56. package/dist/tiff.d.ts +3 -0
  57. package/dist/tiff.js +270 -0
  58. package/dist/tree.d.ts +23 -0
  59. package/dist/tree.js +54 -0
  60. package/dist/types.d.ts +31 -0
  61. package/dist/types.js +2 -0
  62. package/dist/writer.d.ts +38 -0
  63. package/dist/writer.js +145 -0
  64. package/dist/xfa-apply.d.ts +49 -0
  65. package/dist/xfa-apply.js +617 -0
  66. package/dist/xfa-model.d.ts +42 -0
  67. package/dist/xfa-model.js +227 -0
  68. package/dist/xfa-paint.d.ts +24 -0
  69. package/dist/xfa-paint.js +275 -0
  70. package/dist/xfa-spec.d.ts +47 -0
  71. package/dist/xfa-spec.js +3 -0
  72. package/dist/xml.d.ts +30 -0
  73. package/dist/xml.js +211 -0
  74. package/package.json +83 -4
package/dist/layout.js ADDED
@@ -0,0 +1,779 @@
1
+ "use strict";
2
+ // Box layout for pdf.js's XFA tree. pdf.js gives most boxes an explicit size and position; what it leaves to
3
+ // CSS (flex rows and columns, text flow, percentages, shrink-to-fit captions) is worked out here with a small
4
+ // subset of CSS: border-box sizing, absolute and relative positioning, single-line flexbox and block flow.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.borderStyles = borderStyles;
7
+ exports.layoutBox = layoutBox;
8
+ exports.intrinsicWidth = intrinsicWidth;
9
+ exports.selectedText = selectedText;
10
+ exports.reflowPage = reflowPage;
11
+ const css_1 = require("./css");
12
+ const style_1 = require("./style");
13
+ const text_1 = require("./text");
14
+ const INLINE = new Set(['span', 'a', 'b', 'i', 'u', 'sup', 'sub', '#text', 'br', 'label', 'strong', 'em', 'font']);
15
+ function sides(style, prefix, ref, em) {
16
+ let out = [0, 0, 0, 0];
17
+ const short = style[prefix];
18
+ if (short !== undefined) {
19
+ const parts = String(short)
20
+ .trim()
21
+ .split(/\s+/)
22
+ .map(p => (0, css_1.resolveLength)((0, css_1.parseLength)(p, em), ref) ?? 0);
23
+ out = (0, css_1.fourSides)(parts) ?? out;
24
+ }
25
+ const names = ['Top', 'Right', 'Bottom', 'Left'];
26
+ names.forEach((n, i) => {
27
+ const v = style[prefix + n];
28
+ if (v !== undefined)
29
+ out[i] = (0, css_1.resolveLength)((0, css_1.parseLength)(v, em), ref) ?? 0;
30
+ });
31
+ return out;
32
+ }
33
+ function borderStyles(style) {
34
+ const s = style.borderStyle;
35
+ if (s === undefined)
36
+ return ['none', 'none', 'none', 'none'];
37
+ return (0, css_1.fourSides)(String(s).trim().split(/\s+/)) ?? ['none', 'none', 'none', 'none'];
38
+ }
39
+ function borderWidths(style) {
40
+ const st = borderStyles(style);
41
+ const raw = style.borderWidth;
42
+ let w = [0, 0, 0, 0];
43
+ if (raw !== undefined) {
44
+ w = (0, css_1.fourSides)(String(raw)
45
+ .trim()
46
+ .split(/\s+/)
47
+ .map(p => (0, css_1.parseLength)(p)?.px ?? 0)) ?? [0, 0, 0, 0];
48
+ }
49
+ else if (st.some(x => x !== 'none' && x !== 'hidden')) {
50
+ w = [3, 3, 3, 3];
51
+ }
52
+ return w.map((v, i) => (st[i] === 'none' || st[i] === 'hidden' ? 0 : v));
53
+ }
54
+ function displayOf(node, style) {
55
+ const d = style.display;
56
+ if (typeof d === 'string' && d !== '') {
57
+ if (d === 'inline' && node.children.some(k => k.name === 'svg'))
58
+ return 'block';
59
+ return d;
60
+ }
61
+ if (INLINE.has(node.name))
62
+ return 'inline';
63
+ return 'block';
64
+ }
65
+ function flexOf(style) {
66
+ const v = style.flex;
67
+ if (v === undefined)
68
+ return { grow: 0, shrink: 1, basis: null };
69
+ const parts = String(v).trim().split(/\s+/);
70
+ if (parts.length === 1 && /^[\d.]+$/.test(parts[0]))
71
+ return { grow: Number(parts[0]), shrink: 1, basis: { pct: 0, px: 0 } };
72
+ return { grow: Number(parts[0]) || 0, shrink: parts[1] !== undefined ? Number(parts[1]) : 1, basis: (0, css_1.parseLength)(parts[2]) };
73
+ }
74
+ function isAbsolute(style) {
75
+ return style.position === 'absolute' || style.position === 'fixed';
76
+ }
77
+ function lengthOf(style, key, ref, em) {
78
+ return (0, css_1.resolveLength)((0, css_1.parseLength)(style[key], em), ref);
79
+ }
80
+ function attrLength(node, key, ref) {
81
+ const v = node.attrs[key];
82
+ if (typeof v === 'number')
83
+ return v;
84
+ if (typeof v === 'string')
85
+ return (0, css_1.resolveLength)((0, css_1.parseLength)(v), ref);
86
+ return null;
87
+ }
88
+ /** Lays out one element and everything inside it. */
89
+ function layoutBox(node, parent, parentInh, req, ctx) {
90
+ ctx.env.check?.();
91
+ const style = (0, style_1.cascade)(node, parent);
92
+ const inh = (0, style_1.inherit)(node, style, parentInh);
93
+ const em = inh.size;
94
+ const padding = sides(style, 'padding', req.cw, em);
95
+ const border = borderWidths(style);
96
+ const margin = sides(style, 'margin', req.cw, em);
97
+ const extraW = padding[1] + padding[3] + border[1] + border[3];
98
+ const extraH = padding[0] + padding[2] + border[0] + border[2];
99
+ let w = req.forcedW ?? lengthOf(style, 'width', req.cw, em);
100
+ if (w === null && node.name === 'svg')
101
+ w = attrLength(node, 'width', req.cw);
102
+ if (w === null) {
103
+ const avail = Math.max(0, req.cw - margin[1] - margin[3]);
104
+ w = req.shrink ? Math.min(avail, intrinsicWidth(node, parent, parentInh, ctx)) : avail;
105
+ }
106
+ const minW = lengthOf(style, 'minWidth', req.cw, em);
107
+ const maxW = lengthOf(style, 'maxWidth', req.cw, em);
108
+ if (maxW !== null)
109
+ w = Math.min(w, maxW);
110
+ if (minW !== null)
111
+ w = Math.max(w, minW);
112
+ let h = req.forcedH ?? lengthOf(style, 'height', req.ch, em);
113
+ if (h === null && node.name === 'svg')
114
+ h = attrLength(node, 'height', req.ch);
115
+ const minH = lengthOf(style, 'minHeight', req.ch, em);
116
+ const maxH = lengthOf(style, 'maxHeight', req.ch, em);
117
+ if (h !== null && maxH !== null)
118
+ h = Math.min(h, maxH);
119
+ if (h !== null && minH !== null)
120
+ h = Math.max(h, minH);
121
+ const box = {
122
+ node,
123
+ style,
124
+ inh,
125
+ x: margin[3],
126
+ y: margin[0],
127
+ w,
128
+ h: h ?? 0,
129
+ border,
130
+ padding,
131
+ kids: [],
132
+ lines: null,
133
+ absolute: isAbsolute(style),
134
+ positioned: style.position === 'relative' || isAbsolute(style),
135
+ transform: null,
136
+ clip: style.overflow === 'hidden',
137
+ };
138
+ const iw = Math.max(0, w - extraW);
139
+ const ih = h === null ? null : Math.max(0, h - extraH);
140
+ const contentH = layoutContent(box, iw, ih, ctx);
141
+ if (ih !== null && node.classes.includes('xfaDraw'))
142
+ box.textNeed = Math.max(0, textExtent(box) - ih);
143
+ if (h === null) {
144
+ h = contentH + extraH;
145
+ if (maxH !== null)
146
+ h = Math.min(h, maxH);
147
+ if (minH !== null)
148
+ h = Math.max(h, minH);
149
+ }
150
+ box.h = h;
151
+ layoutAbsolute(box, ctx);
152
+ box.transform = (0, css_1.parseTransform)(style.transform, box.w, box.h);
153
+ if (box.transform) {
154
+ const [ox, oy] = (0, css_1.parseOrigin)(style.transformOrigin, box.w, box.h);
155
+ box.transform = [
156
+ box.transform[0],
157
+ box.transform[1],
158
+ box.transform[2],
159
+ box.transform[3],
160
+ box.transform[4] + ox - box.transform[0] * ox - box.transform[2] * oy,
161
+ box.transform[5] + oy - box.transform[1] * ox - box.transform[3] * oy,
162
+ ];
163
+ }
164
+ return box;
165
+ }
166
+ /** Least line pitch fitDrawText leaves, as a share of the CSS line height. */
167
+ const MIN_SQUEEZE = 0.75;
168
+ function squeezeY(box, k) {
169
+ for (const kid of box.kids) {
170
+ kid.y *= k;
171
+ kid.h *= k;
172
+ squeezeY(kid, k);
173
+ }
174
+ if (box.lines) {
175
+ for (const line of box.lines)
176
+ line.top *= k;
177
+ }
178
+ }
179
+ /**
180
+ * How far a box's in-flow content reaches below its top, looking inside children whose own height pdf.js fixed
181
+ * (a rich text div sized to its draw, say), since their content can run past them.
182
+ */
183
+ function textExtent(box) {
184
+ let extent = 0;
185
+ if (box.lines?.length)
186
+ extent = box.border[0] + box.padding[0] + (0, text_1.linesHeight)(box.lines);
187
+ for (const kid of box.kids)
188
+ if (!kid.absolute)
189
+ extent = Math.max(extent, kid.y + Math.max(kid.h, textExtent(kid)));
190
+ return extent;
191
+ }
192
+ /**
193
+ * pdf.js sizes a draw's rich text with its font metrics (a first line of about 1.17 em, later lines at the font's
194
+ * line height) and counts some empty paragraphs as no line, but asks CSS for a 1.365 line height. When the text
195
+ * comes out taller than the box pdf.js made, the lines are drawn closer together, down to 0.75 of their pitch, so
196
+ * the text stays inside the space pdf.js laid out for it instead of running into what follows.
197
+ */
198
+ function fitDrawText(box, ih) {
199
+ const extent = textExtent(box);
200
+ if (extent <= ih + 0.5 || extent <= 0)
201
+ return;
202
+ // Line boxes move but keep their height, so the last line's height is left out of the scaled span.
203
+ const last = Math.min((0, style_1.lineHeightOf)(box.inh), ih);
204
+ const k = Math.max(MIN_SQUEEZE, extent > last ? (ih - last) / (extent - last) : 1);
205
+ if (k >= 1)
206
+ return;
207
+ for (const kid of box.kids) {
208
+ if (kid.absolute)
209
+ continue;
210
+ kid.y *= k;
211
+ kid.h *= k;
212
+ squeezeY(kid, k);
213
+ }
214
+ }
215
+ function inFlow(node, parent) {
216
+ const st = (0, style_1.cascade)(node, parent);
217
+ return !isAbsolute(st) && st.display !== 'none';
218
+ }
219
+ /** Lays out absolutely positioned children against the box's padding box. */
220
+ function layoutAbsolute(box, ctx) {
221
+ const pw = box.w - box.border[1] - box.border[3];
222
+ const ph = box.h - box.border[0] - box.border[2];
223
+ for (const child of box.node.children) {
224
+ const st = (0, style_1.cascade)(child, box.node);
225
+ if (!isAbsolute(st) || st.display === 'none')
226
+ continue;
227
+ const kid = layoutBox(child, box.node, box.inh, { cw: pw, ch: ph, shrink: true }, ctx);
228
+ const left = lengthOf(st, 'left', pw, box.inh.size);
229
+ const top = lengthOf(st, 'top', ph, box.inh.size);
230
+ const right = lengthOf(st, 'right', pw, box.inh.size);
231
+ const bottom = lengthOf(st, 'bottom', ph, box.inh.size);
232
+ // With no offsets an absolute box keeps its static position, the content box origin.
233
+ kid.x += box.border[3] + (left ?? (right !== null ? pw - right - kid.w : box.padding[3]));
234
+ kid.y += box.border[0] + (top ?? (bottom !== null ? ph - bottom - kid.h : box.padding[0]));
235
+ insertInOrder(box, kid);
236
+ }
237
+ }
238
+ /** Keeps kids in document order so painting follows the tree. */
239
+ function insertInOrder(box, kid) {
240
+ const order = box.node.children.indexOf(kid.node);
241
+ let at = box.kids.length;
242
+ for (let i = 0; i < box.kids.length; i++) {
243
+ if (box.node.children.indexOf(box.kids[i].node) > order) {
244
+ at = i;
245
+ break;
246
+ }
247
+ }
248
+ box.kids.splice(at, 0, kid);
249
+ }
250
+ /** Lays out the in-flow content and returns its height. */
251
+ function layoutContent(box, iw, ih, ctx) {
252
+ const { node, style } = box;
253
+ const name = node.name;
254
+ if (name === 'input' || name === 'select' || name === 'textarea' || name === 'img' || name === 'svg' || name === 'br') {
255
+ return leafHeight(box, iw);
256
+ }
257
+ const display = displayOf(node, style);
258
+ if (display === 'flex')
259
+ return layoutFlex(box, iw, ih, ctx);
260
+ return layoutBlock(box, iw, ih, ctx);
261
+ }
262
+ function leafHeight(box, iw) {
263
+ const { node } = box;
264
+ if (node.name === 'textarea') {
265
+ const text = typeof node.attrs.textContent === 'string' ? node.attrs.textContent : '';
266
+ box.lines = (0, text_1.layoutLines)([{ kind: 'text', text, inh: box.inh, raise: 0, hScale: 100 }], iw, box.inh);
267
+ return (0, text_1.linesHeight)(box.lines);
268
+ }
269
+ if (node.name === 'input' || node.name === 'select')
270
+ return (0, style_1.lineHeightOf)(box.inh);
271
+ return 0;
272
+ }
273
+ /** Collects inline content into pieces, or returns null when the node is not inline. */
274
+ function collectInline(node, parent, parentInh, out) {
275
+ if (node.name === '#text') {
276
+ out.push({ kind: 'text', text: node.value ?? '', inh: parentInh, raise: 0, hScale: 100 });
277
+ return;
278
+ }
279
+ if (node.name === 'br') {
280
+ out.push({ kind: 'break', text: '', inh: parentInh, raise: 0, hScale: 100 });
281
+ return;
282
+ }
283
+ const style = (0, style_1.cascade)(node, parent);
284
+ if (style.display === 'none')
285
+ return;
286
+ const inh = (0, style_1.inherit)(node, style, parentInh);
287
+ const raise = (0, css_1.parseLength)(style.verticalAlign)?.px ?? 0;
288
+ let hScale = 100;
289
+ const t = typeof style.transform === 'string' ? /scaleX\(([\d.]+)\)/.exec(style.transform) : null;
290
+ if (t)
291
+ hScale = Number(t[1]) * 100;
292
+ if (node.children.length === 0) {
293
+ if (node.value)
294
+ out.push({ kind: 'text', text: node.value, inh, raise, hScale });
295
+ return;
296
+ }
297
+ for (const k of node.children) {
298
+ const before = out.length;
299
+ collectInline(k, node, inh, out);
300
+ for (let i = before; i < out.length; i++) {
301
+ if (raise !== 0)
302
+ out[i].raise += raise;
303
+ if (hScale !== 100 && out[i].hScale === 100)
304
+ out[i].hScale = hScale;
305
+ }
306
+ }
307
+ }
308
+ function isInlineLevel(node, parent) {
309
+ if (node.name === '#text' || node.name === 'br')
310
+ return true;
311
+ const st = (0, style_1.cascade)(node, parent);
312
+ return displayOf(node, st) === 'inline';
313
+ }
314
+ /** Block flow: block children stack; runs of inline children become line boxes. */
315
+ function layoutBlock(box, iw, ih, ctx) {
316
+ const { node } = box;
317
+ const top = box.border[0] + box.padding[0];
318
+ const left = box.border[3] + box.padding[3];
319
+ if (node.children.length === 0) {
320
+ if (node.value) {
321
+ box.lines = (0, text_1.layoutLines)([{ kind: 'text', text: node.value, inh: box.inh, raise: 0, hScale: 100 }], iw, box.inh);
322
+ return (0, text_1.linesHeight)(box.lines);
323
+ }
324
+ return 0;
325
+ }
326
+ let y = 0;
327
+ let run = [];
328
+ const flushRun = () => {
329
+ if (run.length === 0)
330
+ return;
331
+ const hasText = run.some(p => p.kind === 'break' || (p.inh.preWrap ? p.text !== '' : p.text.trim() !== ''));
332
+ if (hasText) {
333
+ const lines = (0, text_1.layoutLines)(run, iw, box.inh);
334
+ const anon = anonymousBox(box, left, top + y, iw, lines);
335
+ box.kids.push(anon);
336
+ y += anon.h;
337
+ }
338
+ run = [];
339
+ };
340
+ for (const child of node.children) {
341
+ if (!inFlow(child, node))
342
+ continue;
343
+ if (isInlineLevel(child, node)) {
344
+ collectInline(child, node, box.inh, run);
345
+ continue;
346
+ }
347
+ flushRun();
348
+ const kid = layoutBox(child, node, box.inh, { cw: iw, ch: ih }, ctx);
349
+ const m = sides(kid.style, 'margin', iw, kid.inh.size);
350
+ kid.x = left + m[3];
351
+ kid.y = top + y + m[0];
352
+ applyRelative(kid, iw, ih);
353
+ box.kids.push(kid);
354
+ y += kid.h + m[0] + m[2];
355
+ }
356
+ flushRun();
357
+ return y;
358
+ }
359
+ function anonymousBox(parent, x, y, w, lines) {
360
+ return {
361
+ node: { name: '#lines', classes: [], style: {}, attrs: {}, children: [] },
362
+ style: {},
363
+ inh: parent.inh,
364
+ x,
365
+ y,
366
+ w,
367
+ h: (0, text_1.linesHeight)(lines),
368
+ border: [0, 0, 0, 0],
369
+ padding: [0, 0, 0, 0],
370
+ kids: [],
371
+ lines,
372
+ absolute: false,
373
+ positioned: false,
374
+ transform: null,
375
+ clip: false,
376
+ };
377
+ }
378
+ function applyRelative(kid, cw, ch) {
379
+ if (kid.style.position !== 'relative')
380
+ return;
381
+ const dx = lengthOf(kid.style, 'left', cw, kid.inh.size);
382
+ const dy = lengthOf(kid.style, 'top', ch, kid.inh.size);
383
+ if (dx !== null)
384
+ kid.x += dx;
385
+ if (dy !== null)
386
+ kid.y += dy;
387
+ }
388
+ /** Single-line flexbox in any of the four directions. */
389
+ function layoutFlex(box, iw, ih, ctx) {
390
+ const { node, style } = box;
391
+ const dir = String(style.flexDirection ?? 'row');
392
+ const row = dir.startsWith('row');
393
+ const reverse = dir.endsWith('reverse');
394
+ const alignItems = String(style.alignItems ?? 'stretch');
395
+ const justify = String(style.justifyContent ?? 'flex-start');
396
+ const left = box.border[3] + box.padding[3];
397
+ const top = box.border[0] + box.padding[0];
398
+ const items = [];
399
+ let pending = [];
400
+ const flushText = () => {
401
+ if (pending.some(p => p.kind === 'text' && (p.inh.preWrap ? p.text !== '' : p.text.trim() !== ''))) {
402
+ const pieces = pending;
403
+ const text = { name: '#anon', classes: [], style: {}, attrs: { pieces }, children: [] };
404
+ items.push({ node: text, style: {}, margin: [0, 0, 0, 0], grow: 0, shrink: 1, basis: 0, main: 0, box: null, autoCross: true, minMain: 0 });
405
+ }
406
+ pending = [];
407
+ };
408
+ for (const child of node.children) {
409
+ if (!inFlow(child, node))
410
+ continue;
411
+ if (child.name === '#text') {
412
+ collectInline(child, node, box.inh, pending);
413
+ continue;
414
+ }
415
+ flushText();
416
+ if (child.name === 'br')
417
+ continue;
418
+ const st = (0, style_1.cascade)(child, node);
419
+ const fl = flexOf(st);
420
+ const crossKey = row ? 'height' : 'width';
421
+ items.push({
422
+ node: child,
423
+ style: st,
424
+ margin: sides(st, 'margin', iw, box.inh.size),
425
+ grow: fl.grow,
426
+ shrink: fl.shrink,
427
+ basis: 0,
428
+ main: 0,
429
+ box: null,
430
+ autoCross: lengthOf(st, crossKey, row ? ih : iw, box.inh.size) === null,
431
+ minMain: 0,
432
+ });
433
+ }
434
+ flushText();
435
+ const mainSize = row ? iw : ih;
436
+ // Flex basis: an explicit basis, else the main size property, else the content size.
437
+ for (const it of items) {
438
+ const fl = flexOf(it.style);
439
+ const ref = row ? iw : ih;
440
+ let basis = fl.basis ? (0, css_1.resolveLength)(fl.basis, ref) : null;
441
+ if (basis === null)
442
+ basis = lengthOf(it.style, row ? 'width' : 'height', ref, box.inh.size);
443
+ if (basis === null) {
444
+ if (row)
445
+ basis = itemIntrinsicWidth(it, node, box.inh, ctx);
446
+ else {
447
+ it.box = layoutItem(it, node, box, { cw: iw, ch: ih, shrink: !stretches(it, alignItems) }, ctx);
448
+ basis = it.box.h;
449
+ if (it.style.overflow !== 'hidden')
450
+ it.minMain = basis;
451
+ }
452
+ }
453
+ it.basis = Math.max(0, basis);
454
+ it.main = it.basis;
455
+ }
456
+ const marginMain = (it) => (row ? it.margin[1] + it.margin[3] : it.margin[0] + it.margin[2]);
457
+ let used = 0;
458
+ for (const it of items)
459
+ used += it.main + marginMain(it);
460
+ if (mainSize !== null) {
461
+ const free = mainSize - used;
462
+ if (free > 0.001) {
463
+ const totalGrow = items.reduce((a, it) => a + it.grow, 0);
464
+ if (totalGrow > 0)
465
+ for (const it of items)
466
+ it.main += (free * it.grow) / Math.max(1, totalGrow);
467
+ }
468
+ else if (free < -0.001) {
469
+ // Shrink in proportion to shrink factor times basis; items that reach their minimum are frozen and the
470
+ // rest of the overflow goes to the others.
471
+ const frozen = new Set();
472
+ for (let round = 0; round < items.length + 1; round++) {
473
+ let over = mainSize;
474
+ for (const it of items)
475
+ over -= (frozen.has(it) ? it.main : it.basis) + marginMain(it);
476
+ const open = items.filter(it => !frozen.has(it));
477
+ const weight = open.reduce((a, it) => a + it.shrink * it.basis, 0);
478
+ if (over >= -0.001 || weight <= 0)
479
+ break;
480
+ let clamped = false;
481
+ for (const it of open) {
482
+ it.main = it.basis + (over * it.shrink * it.basis) / weight;
483
+ if (it.main < it.minMain) {
484
+ it.main = it.minMain;
485
+ frozen.add(it);
486
+ clamped = true;
487
+ }
488
+ it.main = Math.max(0, it.main);
489
+ }
490
+ if (!clamped)
491
+ break;
492
+ }
493
+ }
494
+ }
495
+ // Lay items out at their main size; find the cross size.
496
+ for (const it of items) {
497
+ const stretch = stretches(it, alignItems);
498
+ if (row)
499
+ it.box = layoutItem(it, node, box, { cw: iw, ch: ih, forcedW: it.main, shrink: false }, ctx);
500
+ else if (!it.box || Math.abs(it.box.h - it.main) > 0.001 || stretch)
501
+ it.box = layoutItem(it, node, box, { cw: iw, ch: ih, forcedH: it.main, shrink: !stretch }, ctx);
502
+ }
503
+ let cross = row ? ih : iw;
504
+ if (cross === null) {
505
+ cross = 0;
506
+ for (const it of items)
507
+ if (it.box)
508
+ cross = Math.max(cross, it.box.h + it.margin[0] + it.margin[2]);
509
+ }
510
+ if (row) {
511
+ for (const it of items) {
512
+ if (it.box && stretches(it, alignItems) && it.autoCross) {
513
+ const target = Math.max(0, cross - it.margin[0] - it.margin[2]);
514
+ if (Math.abs(it.box.h - target) > 0.001)
515
+ it.box = layoutItem(it, node, box, { cw: iw, ch: ih, forcedW: it.main, forcedH: target }, ctx);
516
+ }
517
+ }
518
+ }
519
+ // Place along the main axis.
520
+ let total = 0;
521
+ for (const it of items)
522
+ total += (it.box ? (row ? it.box.w : it.box.h) : 0) + marginMain(it);
523
+ const free = mainSize === null ? 0 : mainSize - total;
524
+ let pos = 0;
525
+ let gap = 0;
526
+ const jc = justify.replace('flex-', '');
527
+ if (free > 0) {
528
+ if (jc === 'center')
529
+ pos = free / 2;
530
+ else if (jc === 'end')
531
+ pos = free;
532
+ else if (jc === 'space-between' && items.length > 1)
533
+ gap = free / (items.length - 1);
534
+ else if (jc === 'space-around' && items.length > 0) {
535
+ gap = free / items.length;
536
+ pos = gap / 2;
537
+ }
538
+ }
539
+ // An overflowing column starts at its top, as with CSS 'safe' alignment. A browser would center or end-align it
540
+ // and push the text up over whatever sits above; starting at the top keeps it readable.
541
+ const mainExtent = mainSize ?? total;
542
+ for (const it of items) {
543
+ const b = it.box;
544
+ if (!b)
545
+ continue;
546
+ const size = row ? b.w : b.h;
547
+ const startMargin = row ? it.margin[3] : it.margin[0];
548
+ const endMargin = row ? it.margin[1] : it.margin[2];
549
+ let mainPos = pos + startMargin;
550
+ if (reverse)
551
+ mainPos = mainExtent - pos - endMargin - size;
552
+ pos += startMargin + size + endMargin + gap;
553
+ const self = String(it.style.alignSelf ?? 'auto');
554
+ const align = (self === 'auto' ? alignItems : self).replace('flex-', '').replace('self-', '');
555
+ const crossSize = row ? b.h : b.w;
556
+ const crossStart = row ? it.margin[0] : it.margin[3];
557
+ const crossEnd = row ? it.margin[2] : it.margin[1];
558
+ let crossPos = crossStart;
559
+ if (align === 'center')
560
+ crossPos = (cross - crossSize - crossStart - crossEnd) / 2 + crossStart;
561
+ else if (align === 'end')
562
+ crossPos = cross - crossSize - crossEnd;
563
+ if (row) {
564
+ b.x = left + mainPos;
565
+ b.y = top + crossPos;
566
+ }
567
+ else {
568
+ b.x = left + crossPos;
569
+ b.y = top + mainPos;
570
+ }
571
+ applyRelative(b, iw, ih);
572
+ box.kids.push(b);
573
+ }
574
+ return row ? cross : total;
575
+ }
576
+ function stretches(it, alignItems) {
577
+ const self = String(it.style.alignSelf ?? 'auto');
578
+ const align = self === 'auto' ? alignItems : self;
579
+ return (align === 'stretch' || align === 'normal') && it.autoCross;
580
+ }
581
+ function layoutItem(it, parent, box, req, ctx) {
582
+ if (it.node.name === '#anon') {
583
+ const pieces = it.node.attrs.pieces;
584
+ const w = req.forcedW ?? (req.shrink ? Math.min(req.cw, (0, text_1.maxContentWidth)(pieces, box.inh)) : req.cw);
585
+ const lines = (0, text_1.layoutLines)(pieces, w, box.inh);
586
+ const anon = anonymousBox(box, 0, 0, w, lines);
587
+ if (req.forcedH !== undefined)
588
+ anon.h = req.forcedH;
589
+ return anon;
590
+ }
591
+ return layoutBox(it.node, parent, box.inh, req, ctx);
592
+ }
593
+ function itemIntrinsicWidth(it, parent, inh, ctx) {
594
+ if (it.node.name === '#anon')
595
+ return (0, text_1.maxContentWidth)(it.node.attrs.pieces, inh);
596
+ return intrinsicWidth(it.node, parent, inh, ctx);
597
+ }
598
+ /** Max-content width: the width a node takes when nothing wraps. */
599
+ function intrinsicWidth(node, parent, parentInh, ctx) {
600
+ const style = (0, style_1.cascade)(node, parent);
601
+ const inh = (0, style_1.inherit)(node, style, parentInh);
602
+ const fixed = lengthOf(style, 'width', null, inh.size);
603
+ if (fixed !== null)
604
+ return fixed;
605
+ const pad = sides(style, 'padding', 0, inh.size);
606
+ const bw = borderWidths(style);
607
+ const extra = pad[1] + pad[3] + bw[1] + bw[3];
608
+ if (node.name === 'svg')
609
+ return attrLength(node, 'width', null) ?? 0;
610
+ if (node.name === 'img') {
611
+ const src = typeof node.attrs.src === 'string' ? node.attrs.src : '';
612
+ return (ctx.env.imageSize(src)?.width ?? 0) + extra;
613
+ }
614
+ if (node.name === 'input' || node.name === 'select') {
615
+ const text = node.name === 'input' ? String(node.attrs.value ?? '') : selectedText(node);
616
+ return Math.max(20, (0, text_1.maxContentWidth)([{ kind: 'text', text, inh, raise: 0, hScale: 100 }], inh)) + extra;
617
+ }
618
+ if (node.name === 'textarea')
619
+ return extra + 20;
620
+ if (node.children.length === 0) {
621
+ return node.value ? (0, text_1.maxContentWidth)([{ kind: 'text', text: node.value, inh, raise: 0, hScale: 100 }], inh) + extra : extra;
622
+ }
623
+ const display = displayOf(node, style);
624
+ const row = display === 'flex' && String(style.flexDirection ?? 'row').startsWith('row');
625
+ let w = 0;
626
+ let run = [];
627
+ const flush = () => {
628
+ if (run.length)
629
+ w = row ? w + (0, text_1.maxContentWidth)(run, inh) : Math.max(w, (0, text_1.maxContentWidth)(run, inh));
630
+ run = [];
631
+ };
632
+ for (const k of node.children) {
633
+ if (!inFlow(k, node))
634
+ continue;
635
+ if (isInlineLevel(k, node) && !(display === 'flex' && k.name !== '#text')) {
636
+ collectInline(k, node, inh, run);
637
+ continue;
638
+ }
639
+ flush();
640
+ const st = (0, style_1.cascade)(k, node);
641
+ const m = sides(st, 'margin', 0, inh.size);
642
+ const kw = intrinsicWidth(k, node, inh, ctx) + m[1] + m[3];
643
+ w = row ? w + kw : Math.max(w, kw);
644
+ }
645
+ flush();
646
+ return w + extra;
647
+ }
648
+ /** The text a select shows: its selected option that is not the hidden placeholder. */
649
+ function selectedText(node) {
650
+ if (typeof node.attrs.xfaShown === 'string')
651
+ return node.attrs.xfaShown;
652
+ const chosen = [];
653
+ for (const o of node.children) {
654
+ if (o.name !== 'option')
655
+ continue;
656
+ const sel = o.attrs.selected === true || o.attrs.selected === 'true';
657
+ const hidden = o.attrs.hidden === true || o.attrs.hidden === 'true';
658
+ if (sel && !hidden)
659
+ chosen.push(o.value ?? '');
660
+ }
661
+ return chosen.join(', ');
662
+ }
663
+ /** Growth smaller than this, in points, is not worth moving anything for. */
664
+ const MIN_GROWTH = 0.5;
665
+ const FIXED_CLASSES = ['xfaSubform', 'xfaDraw', 'xfaField', 'xfaExclgroup', 'xfaArea'];
666
+ /**
667
+ * Whether a box may grow taller than pdf.js made it: a template element with no fixed height, or a box pdf.js adds
668
+ * around one (wrappers, rich text). Content areas and pages never grow, and neither does a form box the template
669
+ * mapping did not reach.
670
+ */
671
+ function growable(box) {
672
+ const { node } = box;
673
+ if (node.classes.includes('xfaContentarea') || node.classes.includes('xfaPage'))
674
+ return false;
675
+ const tpl = node.tpl;
676
+ if (!tpl)
677
+ return !FIXED_CLASSES.some(c => node.classes.includes(c));
678
+ const fixed = (key) => {
679
+ const v = tpl.attrs[key];
680
+ return v !== undefined && v.trim() !== '' && Number.parseFloat(v) > 0;
681
+ };
682
+ return !fixed('h') && !fixed('maxH');
683
+ }
684
+ function inFlowKids(box) {
685
+ return box.kids.filter(k => !k.absolute);
686
+ }
687
+ function isColumn(box) {
688
+ return displayOf(box.node, box.style) === 'flex' && !String(box.style.flexDirection ?? 'row').startsWith('row');
689
+ }
690
+ function isRow(box) {
691
+ return displayOf(box.node, box.style) === 'flex' && String(box.style.flexDirection ?? 'row').startsWith('row');
692
+ }
693
+ /** A growable box that passes a child's growth on: a flex column or row, or a box around a single child. */
694
+ function passesGrowth(box) {
695
+ return growable(box) && (isColumn(box) || isRow(box) || inFlowKids(box).length === 1);
696
+ }
697
+ function innerBottom(box) {
698
+ return box.h - box.border[2] - box.padding[2];
699
+ }
700
+ function bottomOf(boxes) {
701
+ let b = 0;
702
+ for (const k of boxes)
703
+ b = Math.max(b, k.y + k.h);
704
+ return b;
705
+ }
706
+ /**
707
+ * Room a box at the top of the growth chain has inside the box that stops the growth: in a flex column, the space
708
+ * below the last child, since the children below move down; otherwise the space down to the nearest box below it
709
+ * that it would run into.
710
+ */
711
+ function slackIn(limit, top) {
712
+ const kids = inFlowKids(limit);
713
+ if (isColumn(limit))
714
+ return innerBottom(limit) - bottomOf(kids);
715
+ let floor = innerBottom(limit);
716
+ const bottom = top.y + top.h;
717
+ for (const k of limit.kids) {
718
+ if (k === top || k.y < bottom - MIN_GROWTH)
719
+ continue;
720
+ if (k.x < top.x + top.w && k.x + k.w > top.x)
721
+ floor = Math.min(floor, k.y);
722
+ }
723
+ return floor - bottom;
724
+ }
725
+ /** Moves the children after kid in a flex column down by d. */
726
+ function shiftAfter(column, kid, d) {
727
+ const at = column.kids.indexOf(kid);
728
+ for (let i = at + 1; i < column.kids.length; i++)
729
+ if (!column.kids[i].absolute)
730
+ column.kids[i].y += d;
731
+ }
732
+ /** Grows box by d and passes the growth up the chain, which ends at limit. */
733
+ function grow(chain, limit, d) {
734
+ let delta = d;
735
+ chain[0].h += delta;
736
+ for (let i = 1; i <= chain.length && delta > 0; i++) {
737
+ const parent = i < chain.length ? chain[i] : limit;
738
+ const kid = chain[i - 1];
739
+ if (isColumn(parent))
740
+ shiftAfter(parent, kid, delta);
741
+ if (parent === limit)
742
+ break;
743
+ const need = (isColumn(parent) ? bottomOf(inFlowKids(parent)) : kid.y + kid.h) - innerBottom(parent);
744
+ delta = Math.max(0, need);
745
+ parent.h += delta;
746
+ }
747
+ }
748
+ /**
749
+ * pdf.js measures some rich text short (lists, paragraphs that hold only a line break), so a draw's text can need
750
+ * more height than its box. Where the draw and the boxes around it have no fixed height in the template, the draw
751
+ * grows and the content after it in the same flow moves down, as far as the space left in the content area (or the
752
+ * first box of fixed height) allows; nothing moves into the box below. Text that still does not fit is drawn with
753
+ * its lines closer together (fitDrawText).
754
+ */
755
+ function reflowPage(page) {
756
+ const visit = (box, trail) => {
757
+ for (const kid of box.kids)
758
+ visit(kid, [...trail, box]);
759
+ const need = box.textNeed ?? 0;
760
+ if (need <= MIN_GROWTH)
761
+ return;
762
+ // A line box is taller than the glyph height pdf.js counts for a line, so most text "needs" a few points more
763
+ // than its box. Only text short by half a line or more, a line pdf.js did not count, makes the box grow.
764
+ if (growable(box) && need >= (0, style_1.lineHeightOf)(box.inh) / 2) {
765
+ const chain = [box];
766
+ let i = trail.length - 1;
767
+ while (i >= 0 && passesGrowth(trail[i]))
768
+ chain.push(trail[i--]);
769
+ const limit = i >= 0 ? trail[i] : null;
770
+ if (limit) {
771
+ const d = Math.min(need, Math.max(0, slackIn(limit, chain[chain.length - 1])));
772
+ if (d > MIN_GROWTH)
773
+ grow(chain, limit, d);
774
+ }
775
+ }
776
+ fitDrawText(box, Math.max(0, box.h - box.border[0] - box.border[2] - box.padding[0] - box.padding[2]));
777
+ };
778
+ visit(page, []);
779
+ }