pulpweaver4 0.0.91 → 0.0.185

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 (502) hide show
  1. package/dist/ast/djot.js +23 -0
  2. package/dist/ast/djot.js.map +1 -1
  3. package/dist/ast/index.d.ts +1 -0
  4. package/dist/ast/index.js +1 -0
  5. package/dist/ast/index.js.map +1 -1
  6. package/dist/ast/nodes.d.ts +59 -5
  7. package/dist/ast/nodes.js.map +1 -1
  8. package/dist/ast/table.d.ts +27 -0
  9. package/dist/ast/table.js +32 -0
  10. package/dist/ast/table.js.map +1 -0
  11. package/dist/browser.js +2420 -0
  12. package/dist/citations/index.d.ts +1 -1
  13. package/dist/citations/index.js +1 -1
  14. package/dist/citations/index.js.map +1 -1
  15. package/dist/citations/project.d.ts +12 -2
  16. package/dist/citations/project.js +21 -7
  17. package/dist/citations/project.js.map +1 -1
  18. package/dist/colour/images.d.ts +11 -2
  19. package/dist/colour/images.js +53 -3
  20. package/dist/colour/images.js.map +1 -1
  21. package/dist/colour/ink-limit.d.ts +2 -2
  22. package/dist/colour/ink-limit.js +6 -0
  23. package/dist/colour/ink-limit.js.map +1 -1
  24. package/dist/colour/previews.d.ts +8 -4
  25. package/dist/colour/previews.js +11 -8
  26. package/dist/colour/previews.js.map +1 -1
  27. package/dist/config/config.d.ts +91 -3
  28. package/dist/config/config.js +200 -3
  29. package/dist/config/config.js.map +1 -1
  30. package/dist/config/project-schema.d.ts +0 -8
  31. package/dist/config/project-schema.js +207 -12
  32. package/dist/config/project-schema.js.map +1 -1
  33. package/dist/config/schema.js +10 -0
  34. package/dist/config/schema.js.map +1 -1
  35. package/dist/config/secrets.d.ts +11 -0
  36. package/dist/config/secrets.js +19 -0
  37. package/dist/config/secrets.js.map +1 -0
  38. package/dist/csl/project.d.ts +19 -4
  39. package/dist/csl/project.js +23 -10
  40. package/dist/csl/project.js.map +1 -1
  41. package/dist/fonts/index.d.ts +1 -1
  42. package/dist/fonts/index.js +1 -1
  43. package/dist/fonts/index.js.map +1 -1
  44. package/dist/fonts/lint.d.ts +51 -0
  45. package/dist/fonts/lint.js +101 -16
  46. package/dist/fonts/lint.js.map +1 -1
  47. package/dist/fonts/walk.d.ts +13 -0
  48. package/dist/fonts/walk.js +50 -33
  49. package/dist/fonts/walk.js.map +1 -1
  50. package/dist/html/css.d.ts +4 -0
  51. package/dist/html/css.js +11 -3
  52. package/dist/html/css.js.map +1 -1
  53. package/dist/html/dom.d.ts +6 -1
  54. package/dist/html/dom.js +28 -6
  55. package/dist/html/dom.js.map +1 -1
  56. package/dist/html/generated.d.ts +17 -0
  57. package/dist/html/generated.js +21 -0
  58. package/dist/html/generated.js.map +1 -0
  59. package/dist/html/images.d.ts +18 -0
  60. package/dist/html/images.js +49 -2
  61. package/dist/html/images.js.map +1 -1
  62. package/dist/html/index.d.ts +1 -0
  63. package/dist/html/index.js +1 -0
  64. package/dist/html/index.js.map +1 -1
  65. package/dist/html/render.d.ts +5 -4
  66. package/dist/html/render.js +24 -6
  67. package/dist/html/render.js.map +1 -1
  68. package/dist/hyphenation/exceptions.d.ts +5 -0
  69. package/dist/hyphenation/exceptions.js +11 -0
  70. package/dist/hyphenation/exceptions.js.map +1 -1
  71. package/dist/hyphenation/index.d.ts +1 -1
  72. package/dist/hyphenation/index.js +1 -1
  73. package/dist/hyphenation/index.js.map +1 -1
  74. package/dist/import/convert.d.ts +21 -0
  75. package/dist/import/convert.js +65 -0
  76. package/dist/import/convert.js.map +1 -0
  77. package/dist/incremental/cache.d.ts +59 -0
  78. package/dist/incremental/cache.js +64 -0
  79. package/dist/incremental/cache.js.map +1 -0
  80. package/dist/incremental/index.d.ts +3 -0
  81. package/dist/incremental/index.js +4 -0
  82. package/dist/incremental/index.js.map +1 -0
  83. package/dist/incremental/keys.d.ts +27 -0
  84. package/dist/incremental/keys.js +89 -0
  85. package/dist/incremental/keys.js.map +1 -0
  86. package/dist/incremental/session.d.ts +180 -0
  87. package/dist/incremental/session.js +401 -0
  88. package/dist/incremental/session.js.map +1 -0
  89. package/dist/index.d.ts +6 -0
  90. package/dist/index.js +6 -0
  91. package/dist/index.js.map +1 -1
  92. package/dist/indexes/layout.d.ts +8 -2
  93. package/dist/indexes/layout.js +6 -4
  94. package/dist/indexes/layout.js.map +1 -1
  95. package/dist/layout/cache.d.ts +174 -0
  96. package/dist/layout/cache.js +150 -0
  97. package/dist/layout/cache.js.map +1 -0
  98. package/dist/layout/converge.d.ts +28 -0
  99. package/dist/layout/converge.js +102 -9
  100. package/dist/layout/converge.js.map +1 -1
  101. package/dist/layout/counters.d.ts +4 -0
  102. package/dist/layout/counters.js +15 -0
  103. package/dist/layout/counters.js.map +1 -1
  104. package/dist/layout/index.d.ts +5 -2
  105. package/dist/layout/index.js +3 -0
  106. package/dist/layout/index.js.map +1 -1
  107. package/dist/layout/lists.d.ts +52 -3
  108. package/dist/layout/lists.js +513 -46
  109. package/dist/layout/lists.js.map +1 -1
  110. package/dist/layout/lookahead.d.ts +151 -0
  111. package/dist/layout/lookahead.js +581 -0
  112. package/dist/layout/lookahead.js.map +1 -0
  113. package/dist/layout/margin-boxes.d.ts +11 -1
  114. package/dist/layout/margin-boxes.js +24 -1
  115. package/dist/layout/margin-boxes.js.map +1 -1
  116. package/dist/layout/page-rules.d.ts +6 -1
  117. package/dist/layout/page-rules.js +42 -1
  118. package/dist/layout/page-rules.js.map +1 -1
  119. package/dist/layout/page.js +4 -2
  120. package/dist/layout/page.js.map +1 -1
  121. package/dist/layout/pagebuilder.d.ts +248 -3
  122. package/dist/layout/pagebuilder.js +512 -19
  123. package/dist/layout/pagebuilder.js.map +1 -1
  124. package/dist/layout/pages.d.ts +108 -1
  125. package/dist/layout/pages.js +1362 -159
  126. package/dist/layout/pages.js.map +1 -1
  127. package/dist/layout/paragraph.d.ts +14 -0
  128. package/dist/layout/paragraph.js +304 -31
  129. package/dist/layout/paragraph.js.map +1 -1
  130. package/dist/layout/pre.js +4 -0
  131. package/dist/layout/pre.js.map +1 -1
  132. package/dist/layout/protrusion.d.ts +26 -0
  133. package/dist/layout/protrusion.js +39 -0
  134. package/dist/layout/protrusion.js.map +1 -0
  135. package/dist/layout/ranges.d.ts +2 -0
  136. package/dist/layout/ranges.js +22 -0
  137. package/dist/layout/ranges.js.map +1 -0
  138. package/dist/layout/region.d.ts +2 -1
  139. package/dist/layout/region.js +9 -5
  140. package/dist/layout/region.js.map +1 -1
  141. package/dist/layout/templates.d.ts +71 -0
  142. package/dist/layout/templates.js +290 -0
  143. package/dist/layout/templates.js.map +1 -0
  144. package/dist/layout/vlist.d.ts +3 -3
  145. package/dist/linebreak/items.d.ts +27 -2
  146. package/dist/linebreak/items.js +10 -3
  147. package/dist/linebreak/items.js.map +1 -1
  148. package/dist/linebreak/knuth-plass.d.ts +20 -0
  149. package/dist/linebreak/knuth-plass.js +68 -16
  150. package/dist/linebreak/knuth-plass.js.map +1 -1
  151. package/dist/lint/book.d.ts +13 -0
  152. package/dist/lint/book.js +52 -0
  153. package/dist/lint/book.js.map +1 -0
  154. package/dist/lint/config.d.ts +9 -0
  155. package/dist/lint/config.js +40 -6
  156. package/dist/lint/config.js.map +1 -1
  157. package/dist/lint/linter.js +1 -0
  158. package/dist/lint/linter.js.map +1 -1
  159. package/dist/lint/project.js +1 -1
  160. package/dist/lint/project.js.map +1 -1
  161. package/dist/lint/rules/layout.d.ts +3 -1
  162. package/dist/lint/rules/layout.js +8 -6
  163. package/dist/lint/rules/layout.js.map +1 -1
  164. package/dist/lint/rules/source.js +1 -1
  165. package/dist/lint/rules/source.js.map +1 -1
  166. package/dist/lint/testing.js +1 -0
  167. package/dist/lint/testing.js.map +1 -1
  168. package/dist/measure/bidi-data.d.ts +14 -0
  169. package/dist/measure/bidi-data.js +69 -0
  170. package/dist/measure/bidi-data.js.map +1 -0
  171. package/dist/measure/bidi.d.ts +70 -0
  172. package/dist/measure/bidi.js +225 -0
  173. package/dist/measure/bidi.js.map +1 -0
  174. package/dist/measure/css.d.ts +5 -0
  175. package/dist/measure/css.js +2 -0
  176. package/dist/measure/css.js.map +1 -1
  177. package/dist/measure/measurer.d.ts +36 -2
  178. package/dist/measure/measurer.js +220 -22
  179. package/dist/measure/measurer.js.map +1 -1
  180. package/dist/measure/model.d.ts +20 -2
  181. package/dist/measure/model.js +13 -6
  182. package/dist/measure/model.js.map +1 -1
  183. package/dist/measure/script-data.d.ts +6 -0
  184. package/dist/measure/script-data.js +34 -0
  185. package/dist/measure/script-data.js.map +1 -0
  186. package/dist/measure/scripts.d.ts +36 -0
  187. package/dist/measure/scripts.js +293 -0
  188. package/dist/measure/scripts.js.map +1 -0
  189. package/dist/output/output.d.ts +35 -3
  190. package/dist/output/output.js +26 -4
  191. package/dist/output/output.js.map +1 -1
  192. package/dist/paint/backgrounds.js +7 -20
  193. package/dist/paint/backgrounds.js.map +1 -1
  194. package/dist/paint/blend.d.ts +33 -13
  195. package/dist/paint/blend.js +73 -21
  196. package/dist/paint/blend.js.map +1 -1
  197. package/dist/paint/cache.d.ts +80 -0
  198. package/dist/paint/cache.js +537 -0
  199. package/dist/paint/cache.js.map +1 -0
  200. package/dist/paint/canvas.d.ts +4 -13
  201. package/dist/paint/canvas.js +45 -5
  202. package/dist/paint/canvas.js.map +1 -1
  203. package/dist/paint/context.d.ts +2 -0
  204. package/dist/paint/emphasis.js +1 -1
  205. package/dist/paint/emphasis.js.map +1 -1
  206. package/dist/paint/flatten.d.ts +24 -2
  207. package/dist/paint/flatten.js +55 -12
  208. package/dist/paint/flatten.js.map +1 -1
  209. package/dist/paint/forms.d.ts +64 -0
  210. package/dist/paint/forms.js +319 -0
  211. package/dist/paint/forms.js.map +1 -0
  212. package/dist/paint/images.d.ts +4 -1
  213. package/dist/paint/images.js +13 -2
  214. package/dist/paint/images.js.map +1 -1
  215. package/dist/paint/layers.d.ts +64 -0
  216. package/dist/paint/layers.js +137 -0
  217. package/dist/paint/layers.js.map +1 -0
  218. package/dist/paint/painter.d.ts +19 -6
  219. package/dist/paint/painter.js +15 -135
  220. package/dist/paint/painter.js.map +1 -1
  221. package/dist/paint/stacking.d.ts +1 -1
  222. package/dist/paint/stacking.js +9 -2
  223. package/dist/paint/stacking.js.map +1 -1
  224. package/dist/paint/text.d.ts +14 -3
  225. package/dist/paint/text.js +25 -4
  226. package/dist/paint/text.js.map +1 -1
  227. package/dist/paint/vertical.js +2 -2
  228. package/dist/paint/vertical.js.map +1 -1
  229. package/dist/pdf/encoded.d.ts +16 -0
  230. package/dist/pdf/encoded.js +35 -0
  231. package/dist/pdf/encoded.js.map +1 -0
  232. package/dist/pdf/include/colour.d.ts +105 -0
  233. package/dist/pdf/include/colour.js +349 -0
  234. package/dist/pdf/include/colour.js.map +1 -0
  235. package/dist/pdf/include/functions.d.ts +17 -0
  236. package/dist/pdf/include/functions.js +389 -0
  237. package/dist/pdf/include/functions.js.map +1 -0
  238. package/dist/pdf/include/pages.d.ts +14 -0
  239. package/dist/pdf/include/pages.js +27 -0
  240. package/dist/pdf/include/pages.js.map +1 -0
  241. package/dist/pdf/include/pdfjs/LICENSE +177 -0
  242. package/dist/pdf/include/pdfjs/pdf.min.mjs +27 -0
  243. package/dist/pdf/include/pdfjs/pdf.worker.min.mjs +27 -0
  244. package/dist/pdf/include/pdfjs/standard_fonts/FoxitDingbats.pfb +0 -0
  245. package/dist/pdf/include/pdfjs/standard_fonts/FoxitFixed.pfb +0 -0
  246. package/dist/pdf/include/pdfjs/standard_fonts/FoxitFixedBold.pfb +0 -0
  247. package/dist/pdf/include/pdfjs/standard_fonts/FoxitFixedBoldItalic.pfb +0 -0
  248. package/dist/pdf/include/pdfjs/standard_fonts/FoxitFixedItalic.pfb +0 -0
  249. package/dist/pdf/include/pdfjs/standard_fonts/FoxitSerif.pfb +0 -0
  250. package/dist/pdf/include/pdfjs/standard_fonts/FoxitSerifBold.pfb +0 -0
  251. package/dist/pdf/include/pdfjs/standard_fonts/FoxitSerifBoldItalic.pfb +0 -0
  252. package/dist/pdf/include/pdfjs/standard_fonts/FoxitSerifItalic.pfb +0 -0
  253. package/dist/pdf/include/pdfjs/standard_fonts/FoxitSymbol.pfb +0 -0
  254. package/dist/pdf/include/pdfjs/standard_fonts/LICENSE_FOXIT +27 -0
  255. package/dist/pdf/include/pdfjs/standard_fonts/LICENSE_LIBERATION +363 -0
  256. package/dist/pdf/include/pdfjs/standard_fonts/LiberationSans-Bold.ttf +0 -0
  257. package/dist/pdf/include/pdfjs/standard_fonts/LiberationSans-BoldItalic.ttf +0 -0
  258. package/dist/pdf/include/pdfjs/standard_fonts/LiberationSans-Italic.ttf +0 -0
  259. package/dist/pdf/include/pdfjs/standard_fonts/LiberationSans-Regular.ttf +0 -0
  260. package/dist/pdf/include/pdfjs/wasm/LICENSE_JBIG2 +196 -0
  261. package/dist/pdf/include/pdfjs/wasm/LICENSE_OPENJPEG +39 -0
  262. package/dist/pdf/include/pdfjs/wasm/LICENSE_PDFJS_JBIG2 +13 -0
  263. package/dist/pdf/include/pdfjs/wasm/LICENSE_PDFJS_OPENJPEG +22 -0
  264. package/dist/pdf/include/pdfjs/wasm/LICENSE_PDFJS_QCMS +19 -0
  265. package/dist/pdf/include/pdfjs/wasm/LICENSE_QCMS +21 -0
  266. package/dist/pdf/include/pdfjs/wasm/jbig2.wasm +0 -0
  267. package/dist/pdf/include/pdfjs/wasm/openjpeg.wasm +0 -0
  268. package/dist/pdf/include/pdfjs/wasm/qcms_bg.wasm +0 -0
  269. package/dist/pdf/include/pdfjs/wasm/quickjs-eval.wasm +0 -0
  270. package/dist/pdf/include/prepare.d.ts +58 -0
  271. package/dist/pdf/include/prepare.js +266 -0
  272. package/dist/pdf/include/prepare.js.map +1 -0
  273. package/dist/pdf/include/preview.d.ts +38 -0
  274. package/dist/pdf/include/preview.js +101 -0
  275. package/dist/pdf/include/preview.js.map +1 -0
  276. package/dist/pdf/include/rewrite.d.ts +57 -0
  277. package/dist/pdf/include/rewrite.js +803 -0
  278. package/dist/pdf/include/rewrite.js.map +1 -0
  279. package/dist/pdf/include/serialize.d.ts +32 -0
  280. package/dist/pdf/include/serialize.js +158 -0
  281. package/dist/pdf/include/serialize.js.map +1 -0
  282. package/dist/pdf/include/testing.d.ts +26 -0
  283. package/dist/pdf/include/testing.js +50 -0
  284. package/dist/pdf/include/testing.js.map +1 -0
  285. package/dist/pdf/index.d.ts +1 -0
  286. package/dist/pdf/index.js +1 -0
  287. package/dist/pdf/index.js.map +1 -1
  288. package/dist/pdf/structure/annotations.d.ts +33 -0
  289. package/dist/pdf/structure/annotations.js +112 -0
  290. package/dist/pdf/structure/annotations.js.map +1 -0
  291. package/dist/pdf/structure/forms.d.ts +10 -0
  292. package/dist/pdf/structure/forms.js +46 -0
  293. package/dist/pdf/structure/forms.js.map +1 -0
  294. package/dist/pdf/structure/index.d.ts +41 -5
  295. package/dist/pdf/structure/index.js +40 -5
  296. package/dist/pdf/structure/index.js.map +1 -1
  297. package/dist/pdf/structure/links.d.ts +2 -0
  298. package/dist/pdf/structure/links.js +1 -1
  299. package/dist/pdf/structure/links.js.map +1 -1
  300. package/dist/pdf/structure/presentation.d.ts +28 -0
  301. package/dist/pdf/structure/presentation.js +79 -0
  302. package/dist/pdf/structure/presentation.js.map +1 -0
  303. package/dist/pdf/structure/tags.d.ts +34 -2
  304. package/dist/pdf/structure/tags.js +117 -14
  305. package/dist/pdf/structure/tags.js.map +1 -1
  306. package/dist/pdf/types.d.ts +357 -11
  307. package/dist/pdf/wasm/pulpweaver4_pdf.d.ts +44 -2
  308. package/dist/pdf/wasm/pulpweaver4_pdf.js +191 -2
  309. package/dist/pdf/wasm/pulpweaver4_pdf_bg.wasm +0 -0
  310. package/dist/pdf/writer.d.ts +13 -1
  311. package/dist/pdf/writer.js +26 -1
  312. package/dist/pdf/writer.js.map +1 -1
  313. package/dist/plugin/define.d.ts +200 -15
  314. package/dist/plugin/define.js +124 -15
  315. package/dist/plugin/define.js.map +1 -1
  316. package/dist/plugin/failure.d.ts +1 -1
  317. package/dist/plugin/index.d.ts +5 -4
  318. package/dist/plugin/index.js +5 -4
  319. package/dist/plugin/index.js.map +1 -1
  320. package/dist/plugin/reference.d.ts +38 -0
  321. package/dist/plugin/reference.js +287 -0
  322. package/dist/plugin/reference.js.map +1 -0
  323. package/dist/plugin/register.d.ts +39 -7
  324. package/dist/plugin/register.js +83 -2
  325. package/dist/plugin/register.js.map +1 -1
  326. package/dist/preflight/index.d.ts +1 -1
  327. package/dist/preflight/index.js +1 -1
  328. package/dist/preflight/index.js.map +1 -1
  329. package/dist/preflight/pdfx.d.ts +35 -0
  330. package/dist/preflight/pdfx.js +33 -2
  331. package/dist/preflight/pdfx.js.map +1 -1
  332. package/dist/preflight/reader.d.ts +10 -3
  333. package/dist/preflight/reader.js +86 -5
  334. package/dist/preflight/reader.js.map +1 -1
  335. package/dist/print/impose.d.ts +66 -0
  336. package/dist/print/impose.js +331 -0
  337. package/dist/print/impose.js.map +1 -0
  338. package/dist/print/output.js +400 -50
  339. package/dist/print/output.js.map +1 -1
  340. package/dist/problem.js +4 -3
  341. package/dist/problem.js.map +1 -1
  342. package/dist/profile/index.d.ts +1 -0
  343. package/dist/profile/index.js +1 -0
  344. package/dist/profile/index.js.map +1 -1
  345. package/dist/profile/lint.d.ts +1 -1
  346. package/dist/profile/lint.js +29 -1
  347. package/dist/profile/lint.js.map +1 -1
  348. package/dist/profile/list-table.d.ts +51 -0
  349. package/dist/profile/list-table.js +137 -0
  350. package/dist/profile/list-table.js.map +1 -0
  351. package/dist/profile/metadata.js +3 -0
  352. package/dist/profile/metadata.js.map +1 -1
  353. package/dist/profile/profile.d.ts +3 -0
  354. package/dist/profile/profile.js +9 -1
  355. package/dist/profile/profile.js.map +1 -1
  356. package/dist/project.js +3 -0
  357. package/dist/project.js.map +1 -1
  358. package/dist/qpdf/index.d.ts +2 -0
  359. package/dist/qpdf/index.js +3 -0
  360. package/dist/qpdf/index.js.map +1 -0
  361. package/dist/qpdf/qpdf.d.ts +125 -0
  362. package/dist/qpdf/qpdf.js +205 -0
  363. package/dist/qpdf/qpdf.js.map +1 -0
  364. package/dist/qpdf/testing.d.ts +12 -0
  365. package/dist/qpdf/testing.js +9 -0
  366. package/dist/qpdf/testing.js.map +1 -0
  367. package/dist/qpdf/wasm/LICENSE-qpdf +202 -0
  368. package/dist/qpdf/wasm/LICENSE-zlib +22 -0
  369. package/dist/qpdf/wasm/NOTICE-qpdf.md +42 -0
  370. package/dist/qpdf/wasm/qpdf.wasm +0 -0
  371. package/dist/render/index.d.ts +3 -0
  372. package/dist/render/index.js +2 -0
  373. package/dist/render/index.js.map +1 -0
  374. package/dist/render/render.d.ts +98 -0
  375. package/dist/render/render.js +243 -0
  376. package/dist/render/render.js.map +1 -0
  377. package/dist/reproducible/clock.d.ts +4 -5
  378. package/dist/reproducible/clock.js +4 -5
  379. package/dist/reproducible/clock.js.map +1 -1
  380. package/dist/spike/spike-page.chromium.json +4 -4
  381. package/dist/style/colours.d.ts +7 -2
  382. package/dist/style/colours.js +24 -2
  383. package/dist/style/colours.js.map +1 -1
  384. package/dist/style/compile.js +1 -1
  385. package/dist/style/compile.js.map +1 -1
  386. package/dist/style/defaults.d.ts +9 -3
  387. package/dist/style/defaults.js +14 -2
  388. package/dist/style/defaults.js.map +1 -1
  389. package/dist/style/gcpm.d.ts +1 -1
  390. package/dist/style/gcpm.js +17 -5
  391. package/dist/style/gcpm.js.map +1 -1
  392. package/dist/style/properties.js +84 -0
  393. package/dist/style/properties.js.map +1 -1
  394. package/dist/test/book.d.ts +22 -2
  395. package/dist/test/book.js +35 -2
  396. package/dist/test/book.js.map +1 -1
  397. package/dist/test/build.d.ts +23 -0
  398. package/dist/test/build.js +86 -33
  399. package/dist/test/build.js.map +1 -1
  400. package/dist/test/layout.js +128 -19
  401. package/dist/test/layout.js.map +1 -1
  402. package/dist/test/limits.d.ts +8 -0
  403. package/dist/test/limits.js +9 -0
  404. package/dist/test/limits.js.map +1 -0
  405. package/dist/test/pipeline.d.ts +23 -0
  406. package/dist/test/pipeline.js.map +1 -1
  407. package/dist/test/render.d.ts +26 -3
  408. package/dist/test/render.js +151 -23
  409. package/dist/test/render.js.map +1 -1
  410. package/dist/test/runner.d.ts +6 -3
  411. package/dist/test/runner.js +172 -105
  412. package/dist/test/runner.js.map +1 -1
  413. package/dist/test/text.js +2 -2
  414. package/dist/test/text.js.map +1 -1
  415. package/dist/text/output.js +2 -2
  416. package/dist/text/output.js.map +1 -1
  417. package/dist/text/render.d.ts +4 -3
  418. package/dist/text/render.js +126 -4
  419. package/dist/text/render.js.map +1 -1
  420. package/dist/transform/index.d.ts +1 -1
  421. package/dist/transform/index.js +1 -1
  422. package/dist/transform/index.js.map +1 -1
  423. package/dist/transform/run.d.ts +2 -0
  424. package/dist/transform/run.js +32 -16
  425. package/dist/transform/run.js.map +1 -1
  426. package/dist/web/output.js +116 -10
  427. package/dist/web/output.js.map +1 -1
  428. package/dist/web/runtime/justify.js.txt +2 -2
  429. package/dist/web/site.d.ts +2 -0
  430. package/dist/web/site.js +8 -1
  431. package/dist/web/site.js.map +1 -1
  432. package/docs/README.md +6 -1
  433. package/docs/manual/chapters/front.dj +34 -0
  434. package/docs/manual/chapters/guides/citations.dj +426 -0
  435. package/docs/manual/chapters/guides/colour-and-prepress.dj +261 -0
  436. package/docs/manual/chapters/guides/editions.dj +329 -0
  437. package/docs/manual/chapters/guides/in-a-web-page.dj +143 -0
  438. package/docs/manual/chapters/guides/lines-and-pages.dj +681 -0
  439. package/docs/manual/chapters/guides/lint-rules.dj +355 -0
  440. package/docs/manual/chapters/guides/pdfs.dj +501 -0
  441. package/docs/manual/chapters/guides/plugins.dj +425 -0
  442. package/docs/manual/chapters/guides/testing.dj +264 -0
  443. package/docs/manual/chapters/guides/writing-in-djot.dj +537 -0
  444. package/docs/manual/chapters/start/for-latex-users.dj +256 -0
  445. package/docs/manual/chapters/start/getting-started.dj +167 -0
  446. package/docs/manual/chapters/start/your-first-book.dj +426 -0
  447. package/docs/manual/fonts/CrimsonPro-Italic-VF.ttf +0 -0
  448. package/docs/manual/fonts/CrimsonPro-VF.ttf +0 -0
  449. package/docs/manual/fonts/JetBrainsMono-Regular.otf +0 -0
  450. package/docs/manual/fonts/NotoSansSymbols2-Boxes.ttf +0 -0
  451. package/docs/manual/fonts/OFL.txt +95 -0
  452. package/docs/manual/pulpweaver4.toml +39 -0
  453. package/docs/manual/styles/manual.css +137 -0
  454. package/docs/reference/css-properties/index.md +9 -0
  455. package/docs/reference/css-properties/pw-expansion.md +31 -0
  456. package/docs/reference/css-properties/pw-flow-into.md +31 -0
  457. package/docs/reference/css-properties/pw-knockout.md +26 -0
  458. package/docs/reference/css-properties/pw-layer.md +24 -0
  459. package/docs/reference/css-properties/pw-page-breaking.md +30 -0
  460. package/docs/reference/css-properties/pw-page-duration.md +28 -0
  461. package/docs/reference/css-properties/pw-page-rotate.md +29 -0
  462. package/docs/reference/css-properties/pw-page-transition.md +29 -0
  463. package/docs/reference/css-properties/pw-protrusion.md +31 -0
  464. package/docs/reference/lint-rules/ibid-across-page.md +2 -2
  465. package/docs/reference/plugin-api/capabilities.md +2 -2
  466. package/docs/reference/plugin-api/claim-kind.md +1 -1
  467. package/docs/reference/plugin-api/combine-exceptions.md +19 -0
  468. package/docs/reference/plugin-api/element-break-context.md +34 -0
  469. package/docs/reference/plugin-api/element-break-item.md +24 -0
  470. package/docs/reference/plugin-api/element-breaker.md +24 -0
  471. package/docs/reference/plugin-api/flow-definition.md +30 -0
  472. package/docs/reference/plugin-api/generated-reference.md +32 -0
  473. package/docs/reference/plugin-api/index-definition.md +32 -0
  474. package/docs/reference/plugin-api/index-titles.md +18 -0
  475. package/docs/reference/plugin-api/index.md +27 -3
  476. package/docs/reference/plugin-api/insert-class-definition.md +46 -0
  477. package/docs/reference/plugin-api/insert-placement.md +22 -0
  478. package/docs/reference/plugin-api/insert-placements.md +18 -0
  479. package/docs/reference/plugin-api/layout-definition.md +9 -5
  480. package/docs/reference/plugin-api/layout-slot.md +6 -16
  481. package/docs/reference/plugin-api/lint-context.md +3 -1
  482. package/docs/reference/plugin-api/lint-definition.md +1 -1
  483. package/docs/reference/plugin-api/lint-edition.md +2 -0
  484. package/docs/reference/plugin-api/page-builder-event.md +22 -0
  485. package/docs/reference/plugin-api/page-builder-hook.md +7 -3
  486. package/docs/reference/plugin-api/page-builder-page-event.md +30 -0
  487. package/docs/reference/plugin-api/page-template-definition.md +34 -0
  488. package/docs/reference/plugin-api/page-template-region-definition.md +46 -0
  489. package/docs/reference/plugin-api/plugin-definition.md +5 -1
  490. package/docs/reference/plugin-api/plugin-reference-options.md +32 -0
  491. package/docs/reference/plugin-api/plugin-reference.md +22 -0
  492. package/docs/reference/plugin-api/plugin-registry.md +15 -5
  493. package/docs/reference/plugin-api/plugin-stage.md +1 -1
  494. package/docs/reference/plugin-api/plugin.md +9 -2
  495. package/docs/reference/plugin-api/reference-page.md +34 -0
  496. package/docs/reference/plugin-api/render-reference-page.md +18 -0
  497. package/docs/reference/plugin-api/renderers.md +1 -1
  498. package/docs/reference/pulpweaver4-toml/editions.md +239 -2
  499. package/docs/reference/pulpweaver4-toml/index.md +44 -1
  500. package/docs/reference/pulpweaver4-toml/inks.md +15 -4
  501. package/docs/reference/pulpweaver4-toml/lint.md +1 -1
  502. package/package.json +5 -1
@@ -1,15 +1,16 @@
1
1
  import { exactWidthRegistrations, rewriteExactWidths } from '../style/borders.js';
2
2
  import { elementPropertyRegistrations } from '../style/gcpm.js';
3
- import { formatCounter } from './counters.js';
3
+ import { counterValue, formatCounter, pageCounterOf } from './counters.js';
4
4
  import { BIGSKIP, parseGlue, parseLength } from './glue.js';
5
5
  import { writeFirstLetters } from './first-letter.js';
6
6
  import { buildVerticalList } from './lists.js';
7
7
  import { makeMarginBoxes, parseContent } from './margin-boxes.js';
8
- import { badness } from '../linebreak/knuth-plass.js';
9
8
  import { pageBox } from './page-box.js';
10
9
  import { PageRules, valueOf } from './page-rules.js';
11
10
  import { PageBuilder, natural, pruneTop, vertBreak, vpack, } from './pagebuilder.js';
11
+ import { approximateBreaks, searchSteps } from './lookahead.js';
12
12
  import { NATURAL, Region } from './region.js';
13
+ import { balancedColumnHeight, DEFAULT_FLOW, pageRegions, pluginTemplatesCss, splitColumns } from './templates.js';
13
14
  import { EJECT_PENALTY, INFINITE_VPENALTY } from './vlist.js';
14
15
  /** TeX's `\vfuzz`, 0.1 pt in px: a page no taller than this past its height isn't overfull. */
15
16
  const VFUZZ = 0.1 * 96 / 72;
@@ -22,6 +23,9 @@ function shell(box, lang, extra = '') {
22
23
  page.className = `pw-page${extra ? ` ${extra}` : ''}`;
23
24
  page.lang = lang;
24
25
  page.style.cssText = `position:relative;width:${width + 2 * o}px;height:${height + 2 * o}px;overflow:hidden;text-rendering:geometricPrecision`;
26
+ // Chromium adds a style set through the CSSOM to the attributes only when they are read, after those set since:
27
+ // a page made again for its side (`reshell`) would write it last, where a page made from nothing writes it here.
28
+ page.setAttribute('style', page.style.cssText);
25
29
  const area = document.createElement('div');
26
30
  area.className = 'pw-area';
27
31
  area.style.cssText = `position:absolute;left:${o + margin.left}px;top:${o + margin.top}px;width:${width - margin.left - margin.right}px;` +
@@ -41,12 +45,46 @@ class PageStyles {
41
45
  boxes = new Map();
42
46
  constructor(opts) {
43
47
  this.opts = opts;
44
- this.rules = opts.pageRules ?? PageRules.none;
48
+ const pluginCss = opts.pageTemplates?.size ? pluginTemplatesCss(opts.pageTemplates) : '';
49
+ if (pluginCss) {
50
+ const base = opts.pageRules ?? PageRules.none;
51
+ this.rules = base.empty ? PageRules.read(pluginCss) : PageRules.merge(PageRules.read(pluginCss), base);
52
+ }
53
+ else {
54
+ this.rules = opts.pageRules ?? PageRules.none;
55
+ }
45
56
  this.rootFontSize = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
46
57
  }
47
58
  get named() {
48
59
  return this.rules.names.size > 0;
49
60
  }
61
+ get hasRegions() {
62
+ return this.rules.hasRegions;
63
+ }
64
+ get fontSize() {
65
+ return this.rootFontSize;
66
+ }
67
+ /** The `@region` boxes of a page in `context`, empty when the page uses the default single region. */
68
+ regions(context) {
69
+ return pageRegions(this.style(context), this.box(context), this.rootFontSize);
70
+ }
71
+ /** The first region feeding `flow` across the stylesheet's page rules, if any. */
72
+ firstRegionFor(flow) {
73
+ const contexts = [
74
+ { name: '', first: false, blank: false, side: 'right' },
75
+ { name: '', first: true, blank: false, side: 'right' },
76
+ { name: '', first: false, blank: false, side: 'left' },
77
+ ];
78
+ for (const name of this.rules.names) {
79
+ contexts.push({ name, first: false, blank: false, side: 'right' }, { name, first: false, blank: false, side: 'left' });
80
+ }
81
+ for (const ctx of contexts) {
82
+ const hit = this.regions(ctx).find((r) => r.flow === flow);
83
+ if (hit)
84
+ return hit;
85
+ }
86
+ return undefined;
87
+ }
50
88
  style(context) {
51
89
  return this.rules.resolve(context);
52
90
  }
@@ -91,6 +129,15 @@ class PageStyles {
91
129
  });
92
130
  }
93
131
  }
132
+ /** Whether left and right pages have text areas of one height, whatever their name: whether a page builder sees them alike. */
133
+ sidesAlike() {
134
+ return (this.alike ??= ['', ...this.rules.names].every((name) => {
135
+ const l = this.box({ name, first: false, blank: false, side: 'left' });
136
+ const r = this.box({ name, first: false, blank: false, side: 'right' });
137
+ return l.height - l.margin.top - l.margin.bottom === r.height - r.margin.top - r.margin.bottom;
138
+ }));
139
+ }
140
+ alike;
94
141
  /** The width of the text area of a right page of the name, not the first: the measure its content is set at. */
95
142
  measure(name) {
96
143
  const b = this.box({ name, first: false, blank: false, side: 'right' });
@@ -157,13 +204,46 @@ export function layoutPages(root, opts) {
157
204
  opts.container.append(measuring.page);
158
205
  measuring.main.append(root);
159
206
  root.style.marginTop = root.style.marginBottom = root.style.paddingTop = root.style.paddingBottom = '0';
207
+ // Extract elements directed to named flows (`flow-into: <name>` or a plugin flow's selector) before
208
+ // building vertical lists, while computed styles reflect their place in `root`.
209
+ const namedFlows = extractNamedFlows(root, opts.flows);
210
+ const useTemplates = styles.hasRegions || namedFlows.size > 0;
211
+ const customInserts = opts.inserts;
212
+ const rootEm = Number.parseFloat(getComputedStyle(root).fontSize) || 16;
213
+ const insertClasses = customInserts?.size ? new Set(customInserts.keys()) : undefined;
214
+ const insertWidths = customInserts?.size ? marginInsertWidths(customInserts, plain, rootEm) : undefined;
215
+ const listOpts = {
216
+ fonts: opts.fonts,
217
+ ...(opts.hyphenator ? { hyphenator: opts.hyphenator } : {}),
218
+ ...(opts.penalty ? { penalty: opts.penalty } : {}),
219
+ ...(opts.boxes ? { boxes: opts.boxes } : {}),
220
+ ...(insertClasses ? { insertClasses } : {}),
221
+ ...(insertWidths?.size ? { insertWidths } : {}),
222
+ ...(opts.lineBreaker ? { lineBreaker: opts.lineBreaker } : {}),
223
+ ...(opts.elementBreaks?.length ? { elementBreaks: opts.elementBreaks } : {}),
224
+ ...(opts.elementBreaker ? { elementBreaker: opts.elementBreaker } : {}),
225
+ };
226
+ const vsizeOf = (box) => box.height - box.margin.top - box.margin.bottom;
227
+ const plainWidth = plain.width - plain.margin.left - plain.margin.right;
228
+ const vsize = vsizeOf(plain);
229
+ const firstPage = opts.firstPage ?? 1;
230
+ const sideOf = (n) => (n % 2 === 1 ? 'right' : 'left');
231
+ if (useTemplates) {
232
+ return layoutTemplatedPages(root, namedFlows, opts, styles, measuring, lang, plainWidth, vsize, firstPage, sideOf, listOpts);
233
+ }
160
234
  // A styled `::first-letter` is a span of its own, which a float can be.
161
- const firstLetters = writeFirstLetters(root);
235
+ const firstLetters = opts.firstLetters === false ? [] : writeFirstLetters(root);
162
236
  const names = new PageNames(root, styles.named);
163
237
  const restore = styles.named ? measureNamedPages(root, names, styles) : () => { };
164
- const { fonts, hyphenator, penalty, boxes, lineBreaker } = opts;
238
+ const { fonts, hyphenator, penalty, boxes, lineBreaker, elementBreaks, elementBreaker, cache } = opts;
239
+ // A reused container's elements are out of the document, and can't say their page names.
165
240
  const list = buildVerticalList(root, {
166
241
  fonts, ...(hyphenator ? { hyphenator } : {}), ...(penalty ? { penalty } : {}), ...(boxes ? { boxes } : {}), ...(lineBreaker ? { lineBreaker } : {}),
242
+ ...(elementBreaks?.length ? { elementBreaks } : {}),
243
+ ...(elementBreaker ? { elementBreaker } : {}),
244
+ ...(insertClasses ? { insertClasses } : {}),
245
+ ...(insertWidths?.size ? { insertWidths } : {}),
246
+ ...(cache ? { cache, reuseContainers: !styles.named } : {}),
167
247
  });
168
248
  const cs = getComputedStyle(root);
169
249
  const em = Number.parseFloat(cs.fontSize) || 16;
@@ -172,8 +252,6 @@ export function layoutPages(root, opts) {
172
252
  const v = cs.getPropertyValue(prop).trim();
173
253
  return v && v !== 'none' ? parseLength(v, em) : fallback;
174
254
  };
175
- const vsizeOf = (box) => box.height - box.margin.top - box.margin.bottom;
176
- const vsize = vsizeOf(plain);
177
255
  const maxDepth = length('--pw-max-depth', 0);
178
256
  const floatSkip = glue('--pw-float-skip', BIGSKIP);
179
257
  const zero = { width: 0, stretch: 0, shrink: 0 };
@@ -186,22 +264,156 @@ export function layoutPages(root, opts) {
186
264
  top: floats,
187
265
  bottom: { ...floats, skip: floatSkip },
188
266
  };
267
+ addCustomInserts(inserts, customInserts, em, vsize, maxDepth, floatSkip, zero);
189
268
  fixTables(root);
190
269
  restore();
191
- const firstPage = opts.firstPage ?? 1;
192
- const sideOf = (n) => (n % 2 === 1 ? 'right' : 'left');
193
270
  const headers = new HeaderRows();
194
- const builder = new PageBuilder({
271
+ // Read on the flow, which inherits `:root`. Anything but `lookahead` is TeX's greedy builder.
272
+ const lookahead = cs.getPropertyValue('--pw-page-breaking').trim() === 'lookahead';
273
+ const prepared = contributions(list.items, floatSkip, names, customInserts);
274
+ // The book's end: \vfill\eject, so the last page's text sits at its top.
275
+ const tail = [{ type: 'glue', width: 0, stretch: 1, shrink: 0, stretchOrder: 2 }, { type: 'penalty', penalty: -10000 }];
276
+ const items = [...prepared, ...tail];
277
+ // An incremental build starts from the last layout's state before the
278
+ // first page that looked at what changed, and stops at a page that ends as
279
+ // one of the last layout's did. A lookahead search starts again at the
280
+ // last of its checkpoints before what changed, and stops at one after it
281
+ // that stands as the last search's did (`lookahead.ts`, #170, #180).
282
+ const previous = opts.cache?.pages;
283
+ const baseOptions = {
195
284
  vsize, maxDepth, topSkip: glue('--pw-top-skip', '0px'), inserts, unit: SP_PER_PX, firstPage,
196
285
  vsizeOf: (n, first) => vsizeOf(styles.box({
197
286
  name: first?.type === 'box' && first.kind !== 'null' ? names.ofBox(first) : '', first: n === firstPage, blank: false, side: sideOf(n),
198
287
  })),
199
- continuation: (last, next) => headers.repeat(last, next),
200
- });
201
- contribute(builder, contributions(list.items, floatSkip, names));
202
- // The book's end: \vfill\eject, so the last page's text sits at its top.
203
- builder.contribute([{ type: 'glue', width: 0, stretch: 1, shrink: 0, stretchOrder: 2 }, { type: 'penalty', penalty: -10000 }]);
204
- const built = builder.finish();
288
+ continuation: (l, next) => headers.repeat(l, next),
289
+ };
290
+ // Column rows follow the greedy builder's room, then the search breaks that fixed list.
291
+ const flow = lookahead
292
+ ? [...(prepared.some((i) => i.type === 'box' && i.kind === 'columns') ? expandColumns(prepared, baseOptions) : prepared), ...tail]
293
+ : items;
294
+ const signatures = opts.cache ? new Signatures().of(flow) : undefined;
295
+ const greedy = previous && signatures && !lookahead && !previous.search ? restartFrom(previous, signatures) : undefined;
296
+ let resumed;
297
+ let stop;
298
+ let builder;
299
+ let search;
300
+ if (lookahead) {
301
+ const cache = opts.cache;
302
+ const old = previous?.search && signatures ? previous.search : undefined;
303
+ const exact = old?.exact;
304
+ const marks = new Signatures();
305
+ const searchOptions = {
306
+ sidesAlike: sidesAlike(styles, flow, 0),
307
+ marks: (b) => marks.marks(b.markValues()),
308
+ ...(exact ? { last: { plan: exact.plan, checkpoints: exact.checkpoints, ...differ(exact.signatures, signatures) } } : {}),
309
+ };
310
+ // A search an earlier build left to finish (#180): its breaks, if it was of this list.
311
+ const pending = cache?.search;
312
+ if (cache)
313
+ cache.search = undefined;
314
+ let found = pending?.result && signatures && sameList(pending.signatures, signatures) ? pending.result : undefined;
315
+ if (!found) {
316
+ const run = new PendingSearch(signatures ?? [], searchSteps(flow, baseOptions, searchOptions));
317
+ // Searched again after an edit, as long as the session lets it before it shows a preview; else to the end.
318
+ const more = old ? cache?.preview?.() : undefined;
319
+ if (run.run(more))
320
+ found = run.result;
321
+ else {
322
+ cache.search = run;
323
+ // What it finds is the search the next starts again from, whether or not a layout follows its breaks.
324
+ run.done = (result) => {
325
+ const now = cache.pages;
326
+ if (now?.search?.approximate && now.signatures === signatures) {
327
+ cache.pages = { ...now, search: { ...now.search, exact: { signatures: signatures, plan: result.plan, checkpoints: result.checkpoints } } };
328
+ }
329
+ };
330
+ // A table's repeated header is measured once, while it is where the layout put it.
331
+ headers.prime(flow);
332
+ }
333
+ }
334
+ const diff = old ? differ(previous.signatures, signatures) : undefined;
335
+ const alike = (from) => sidesAlike(styles, flow, from);
336
+ const matcher = old ? restartFrom(previous, signatures) : undefined;
337
+ let plan;
338
+ if (found && old && cache?.swap !== undefined) {
339
+ plan = swapRun(previous, old, found.plan, flow, baseOptions, matcher, alike, cache.swap);
340
+ // A run of the search's pages, the last layout's after it: the search stays, for the next run (#199).
341
+ if (plan !== found.plan)
342
+ cache.search = pending;
343
+ }
344
+ else if (found)
345
+ plan = found.plan;
346
+ else {
347
+ // A preview: from the last layout's state before the edit, its breaks taken up again as soon as the builder stands as it did.
348
+ const at = resumeAt(previous, old, old.plan, diff.first) ?? { state: previous.states.get(0), steps: 0 };
349
+ const steps = new Map([...old.fired].map(([k, pages]) => [pages, k]));
350
+ const approx = approximateBreaks(flow, baseOptions, at.state, (state, made) => {
351
+ const o = matcher.matches(state, alike);
352
+ // On a page of the same number first, so that the pages after aren't numbered again.
353
+ return o && (o.number === state.number || made > RENUMBER_AFTER) ? steps.get(o.pages) : undefined;
354
+ });
355
+ plan = [...old.plan.slice(0, at.steps), ...approx.steps, ...(approx.rejoined === undefined ? [] : old.plan.slice(approx.rejoined))];
356
+ }
357
+ // The builder starts again after the last of the plan's breaks that it shares with the last, at a page that looked at nothing changed.
358
+ const from = old ? resumeAt(previous, old, plan, diff.first) : undefined;
359
+ const base = from?.steps ?? 0;
360
+ resumed = from;
361
+ const fired = new Map([[base, from?.state.pages ?? 0]]);
362
+ // From `lead` of its breaks on, the plan is the last's from `lead + lag` on: where the builder
363
+ // stands then as the last layout did after as many of its breaks, the pages after are the last's.
364
+ let common = 0;
365
+ if (old)
366
+ while (common < plan.length && common < old.plan.length && plan[plan.length - 1 - common] === old.plan[old.plan.length - 1 - common])
367
+ common++;
368
+ const lead = plan.length - common;
369
+ const lag = old ? old.plan.length - plan.length : 0;
370
+ const options = {
371
+ ...baseOptions,
372
+ stop: (state) => {
373
+ const at = base + builder.planned();
374
+ fired.set(at, state.pages);
375
+ if (!old || at < lead)
376
+ return false;
377
+ const pages = old.fired.get(at + lag);
378
+ const match = pages === undefined ? undefined : previous.states.get(pages);
379
+ if (!match || !matcher.same(state, match, alike))
380
+ return false;
381
+ stop = { state, last: match };
382
+ return true;
383
+ },
384
+ };
385
+ builder = from ? PageBuilder.resume(options, from.state) : new PageBuilder(options);
386
+ builder.follow(plan.slice(base));
387
+ const start = from?.state.next ?? 0;
388
+ builder.contribute(flow.slice(start), start);
389
+ search = keepSearch(old, base, lag, stop, plan, fired, found ? { signatures: signatures ?? [], plan: found.plan, checkpoints: found.checkpoints } : exact, !found || plan !== found.plan);
390
+ }
391
+ else {
392
+ const options = {
393
+ ...baseOptions,
394
+ ...(greedy ? {
395
+ stop: (state) => {
396
+ const match = greedy.matches(state, (from) => sidesAlike(styles, items, from));
397
+ if (match)
398
+ stop = { state, last: match };
399
+ return match !== undefined;
400
+ },
401
+ } : {}),
402
+ };
403
+ builder = greedy ? PageBuilder.resume(options, greedy.state) : new PageBuilder(options);
404
+ contribute(builder, items, greedy?.state.next ?? 0);
405
+ }
406
+ const restart = greedy ?? resumed;
407
+ const last = restart || stop ? previous : undefined;
408
+ const fresh = builder.finish();
409
+ if (opts.cache)
410
+ opts.cache.stats.pages = fresh.length;
411
+ // The pages kept from the last layout: those before the restart, and those after the stop, renumbered.
412
+ const before = restart ? last.pages.slice(0, restart.state.pages) : [];
413
+ const after = stop ? last.pages.slice(stop.last.pages) : [];
414
+ const shift = stop ? stop.state.number - stop.last.number : 0;
415
+ const built = [...before.map((k) => k.laid.built), ...fresh, ...after.map((k) => (shift ? { ...k.laid.built, number: k.laid.built.number + shift } : k.laid.built))];
416
+ const kept = (i) => (i < before.length ? before[i] : i >= before.length + fresh.length ? after[i - before.length - fresh.length] : undefined);
205
417
  // A box taller than the page is placed alone on one, overfull, and the
206
418
  // page's foot cuts it off: named before it moves. (A page a little over
207
419
  // its goal, as TeX's can be after an insert is split, is no such loss.)
@@ -219,23 +431,30 @@ export function layoutPages(root, opts) {
219
431
  }];
220
432
  })];
221
433
  // Each page's name is its first box's; a blank page takes the next page's.
222
- const pageNames = built.map((b) => {
223
- const first = b.items.find((i) => i.type === 'box' && i.kind !== 'null');
434
+ const pageNames = built.map((b, i) => {
435
+ const k = kept(i);
436
+ if (k)
437
+ return k.name;
438
+ const first = b.items.find((x) => x.type === 'box' && x.kind !== 'null');
224
439
  return first ? names.ofBox(first) : undefined;
225
440
  });
226
441
  for (let i = pageNames.length - 1; i >= 0; i--)
227
442
  pageNames[i] ??= pageNames[i + 1] ?? pageNames[i - 1] ?? '';
228
443
  // Each page's elements that start on it, in order, with any `counter-reset: page` or
229
444
  // `counter-set: page`: read before the pages change the document, so styles are computed once.
230
- const started = new Set();
445
+ // What was placed before the restart started on the pages kept.
446
+ const started = restart ? placedBefore(flow, restart.state.next, root) : new Set();
231
447
  const resetsOn = built.map((b, i) => {
448
+ const k = kept(i);
449
+ if (k)
450
+ return k.resets;
232
451
  const out = [];
233
452
  const starts = (el) => {
234
453
  if (started.has(el))
235
454
  return;
236
455
  started.add(el);
237
- const cs = getComputedStyle(el);
238
- const n = counterValue(cs.getPropertyValue('counter-set'), 'page') ?? counterValue(cs.counterReset, 'page');
456
+ // A reused container's elements are the last layout's, out of the document: the cache read theirs.
457
+ const n = el.isConnected ? pageCounterOf(getComputedStyle(el)) : opts.cache?.resets.get(el);
239
458
  if (n !== undefined)
240
459
  out.push(n);
241
460
  };
@@ -251,11 +470,18 @@ export function layoutPages(root, opts) {
251
470
  }
252
471
  return out;
253
472
  });
254
- const fragments = new Set();
473
+ // The new pages go where the pages they replace were, before those kept after them.
474
+ const fragments = restart ? placedBefore(flow, restart.state.next, root) : new Set();
475
+ const next = after[0]?.laid.element ?? null;
255
476
  const pages = [];
256
477
  for (const [i, b] of built.entries()) {
257
478
  const context = { name: pageNames[i], first: i === 0, blank: b.blank, side: sideOf(b.number) };
258
479
  const box = styles.box(context);
480
+ const k = kept(i);
481
+ if (k) {
482
+ pages.push({ b, element: k.laid.element, context, box, lines: [...k.laid.lines], resets: k.resets, kept: k });
483
+ continue;
484
+ }
259
485
  const { page, area, main } = shell(box, lang, `${opts.pageClass ?? ''}${b.blank ? ' pw-blank' : ''}`.trim());
260
486
  if (context.name)
261
487
  page.dataset.pwPageName = context.name;
@@ -264,43 +490,23 @@ export function layoutPages(root, opts) {
264
490
  page.dataset.pwTrimBox = `${o} ${o} ${box.width} ${box.height}`;
265
491
  page.dataset.pwBleedBox = `${o - box.bleed} ${o - box.bleed} ${box.width + 2 * box.bleed} ${box.height + 2 * box.bleed}`;
266
492
  }
267
- opts.container.append(page);
493
+ opts.container.insertBefore(page, next?.parentNode === opts.container ? next : null);
268
494
  const lines = [];
269
495
  pages.push({ b, element: page, context, box, lines, resets: resetsOn[i] });
270
496
  if (b.blank) {
271
497
  area.remove();
272
498
  continue;
273
499
  }
274
- main.style.height = `${b.height}px`;
275
- new Region(main, root, fragments, lines).build(b.items, b.glue);
276
- const placed = (cls) => (b.inserts[cls] ?? []).filter((x) => x.list.some((i) => i.type === 'box'));
277
- const top = placed('top');
278
- const bottom = placed('bottom');
279
- const notes = placed('footnote');
280
- let topHeight = 0;
281
- if (top.length) {
282
- const region = floatRegion(area, 'pw-top-floats');
283
- region.style.top = '0';
284
- new Region(region, root, fragments, lines).build(top.flatMap((x) => x.list), NATURAL);
285
- topHeight = natural(top.flatMap((x) => x.list));
286
- main.style.top = `${topHeight}px`;
287
- }
288
- let bottomOffset = 0;
289
- if (notes.length) {
290
- const region = floatRegion(area, 'pw-footnotes');
291
- region.style.bottom = '0';
292
- const rule = document.createElement('div');
293
- rule.className = 'pw-footnote-rule';
294
- rule.style.cssText = 'position:absolute;left:0;bottom:100%';
295
- region.append(rule);
296
- new Region(region, root, fragments, lines).build(notes.flatMap((x) => x.list), NATURAL);
297
- bottomOffset = natural(notes.flatMap((x) => x.list)) + inserts.footnote.skip.width;
298
- }
299
- if (bottom.length) {
300
- const region = floatRegion(area, 'pw-bottom-floats');
301
- region.style.bottom = `${bottomOffset}px`;
302
- new Region(region, root, fragments, lines).build(bottom.flatMap((x) => x.list), NATURAL);
303
- }
500
+ placeRegionContent(area, main, root, b, inserts, fragments, lines, customInserts);
501
+ if (customInserts?.size)
502
+ placeMarginInserts(page, box, context.side, root, b, customInserts, rootEm, fragments, lines);
503
+ }
504
+ // The pages replaced, whose lines the new ones have taken.
505
+ if (previous) {
506
+ const shown = new Set(pages.map((p) => p.element));
507
+ for (const k of previous.pages)
508
+ if (!shown.has(k.laid.element))
509
+ k.laid.element.remove();
304
510
  }
305
511
  // Page numbers, now that every page is made, then what shows them. A
306
512
  // page without a folio is numbered in the style its page would have off
@@ -322,33 +528,433 @@ export function layoutPages(root, opts) {
322
528
  const folio = (p.b.blank && i > 0 ? folios[i].own : folios[i].folio) ?? lastStyle;
323
529
  lastStyle = folio;
324
530
  const label = opts.label?.(p.b.number) ?? formatCounter(counter, folio);
325
- p.element.dataset.pwPageNumber = String(counter);
326
- p.element.dataset.pwPageStyle = folio;
327
531
  // Every page says its prefix, empty where its rules give none, so one
328
532
  // set for some pages doesn't run on into the next (#92).
329
533
  const prefix = valueOf(style.page, '--pw-page-prefix');
330
- p.element.dataset.pwPagePrefix = prefix === undefined ? '' : unquote(prefix);
331
- return { ...p, style, counter, label };
534
+ return { ...p, style, counter, label, folio, prefix: prefix === undefined ? '' : unquote(prefix) };
332
535
  });
333
- const targets = new Map();
334
- for (const p of numbered)
335
- for (const el of p.element.querySelectorAll('[id]'))
336
- if (!targets.has(el.id))
337
- targets.set(el.id, p.counter);
536
+ // Whether any page was made or changed, which a kept page's `target-counter()` in its margins may show.
537
+ const changedPages = !last || pages.some((p) => !p.kept) || numbered.some((p) => p.kept && p.kept.laid.counter !== p.counter);
538
+ const reads = new Map();
539
+ let targets;
540
+ const targetsOf = () => {
541
+ if (targets)
542
+ return targets;
543
+ targets = new Map();
544
+ for (const p of numbered)
545
+ for (const el of p.element.querySelectorAll('[id]'))
546
+ if (!targets.has(el.id))
547
+ targets.set(el.id, p.counter);
548
+ return targets;
549
+ };
338
550
  const result = numbered.map((p) => {
339
- background(p.element, p.box, p.style);
340
- const margins = makeMarginBoxes(p.element, p.box, p.style, marginContext(p.b, p.counter, numbered.length, targets), {
341
- fonts: opts.fonts, ...(opts.hyphenator ? { hyphenator: opts.hyphenator } : {}),
551
+ const k = p.kept;
552
+ // A page kept as it was, if its number, its side and the page count are; else renumbered, its margin boxes made again.
553
+ if (k && k.laid.counter === p.counter && k.laid.label === p.label && k.laid.number === p.b.number && k.folio === p.folio && k.prefix === p.prefix &&
554
+ (k.total === numbered.length || !k.reads.total) && !(k.reads.targets && changedPages)) {
555
+ reads.set(k.laid, k.reads);
556
+ return k.laid;
557
+ }
558
+ let element = p.element;
559
+ // A page of the other side is the same page where its box and background are (#180: a page more renumbers every page after it).
560
+ const sideChanged = k !== undefined && k.laid.side !== p.context.side &&
561
+ backgroundOf(styles.style({ ...p.context, side: k.laid.side })) !== backgroundOf(p.style);
562
+ if (k && (sideChanged || k.laid.name !== p.context.name || !sameBox(k.laid.box, p.box))) {
563
+ // Its text area goes into a page of its new side, as its lines are.
564
+ element = reshell(k.laid.element, p.box, lang, opts.pageClass, p.b.blank, p.context.name);
565
+ }
566
+ else if (k) {
567
+ for (const m of k.laid.margins)
568
+ m.remove();
569
+ }
570
+ element.dataset.pwPageNumber = String(p.counter);
571
+ element.dataset.pwPageStyle = p.folio;
572
+ element.dataset.pwPagePrefix = p.prefix;
573
+ presentation(element, p.style);
574
+ if (!k || element !== k.laid.element)
575
+ background(element, p.box, p.style);
576
+ // What its margin boxes read beyond the page, so that a later layout knows when to make them again.
577
+ const read = { total: false, targets: false };
578
+ // A page of another PDF (pdfpages') fills the sheet, without the book's running heads and folios.
579
+ const included = includedPage(p.b);
580
+ if (included)
581
+ fillTrimBox(included, element, p.box);
582
+ const context = marginContext(p.b, p.counter, numbered.length, targetsOf);
583
+ const margins = included ? [] : makeMarginBoxes(element, p.box, p.style, {
584
+ ...context,
585
+ counter: (name) => {
586
+ if (name === 'pages')
587
+ read.total = true;
588
+ return context.counter(name);
589
+ },
590
+ target: (id, name) => {
591
+ read.targets = true;
592
+ return context.target(id, name);
593
+ },
594
+ }, {
595
+ fonts: opts.fonts, ...(opts.hyphenator ? { hyphenator: opts.hyphenator } : {}), ...(opts.cache ? { cache: opts.cache.margins } : {}),
342
596
  });
343
- printerMarks(p.element, p.box);
344
- return {
345
- element: p.element, number: p.b.number, label: p.label, blank: p.b.blank, built: p.b, lines: p.lines,
597
+ if (!k || element !== k.laid.element)
598
+ printerMarks(element, p.box);
599
+ const laid = {
600
+ element, number: p.b.number, label: p.label, blank: p.b.blank, built: p.b, lines: p.lines,
346
601
  name: p.context.name, side: p.context.side, counter: p.counter, box: p.box, margins,
347
602
  };
603
+ reads.set(laid, read);
604
+ opts.cache?.revise(element);
605
+ return laid;
348
606
  });
349
607
  measuring.page.remove();
608
+ if (opts.cache)
609
+ opts.cache.pages = keepLayout(result, numbered, reads, signatures ?? [], builder, restart, stop, last, search);
350
610
  return { pages: result, warnings: [...warnings, ...styles.warnings] };
351
611
  }
612
+ /**
613
+ * A lookahead search a layout left to finish (#180): the session that
614
+ * built it runs it on in the browser's idle time (`run`), and the next
615
+ * layout of the same list (`signatures`) follows what it found (`result`).
616
+ * When it finishes, `done` is told.
617
+ */
618
+ export class PendingSearch {
619
+ signatures;
620
+ steps;
621
+ result;
622
+ done;
623
+ constructor(signatures, steps) {
624
+ this.signatures = signatures;
625
+ this.steps = steps;
626
+ }
627
+ /** Searches on, a slice at a time, while `more` says to: whether it has finished. */
628
+ run(more = () => true) {
629
+ while (!this.result) {
630
+ if (!more())
631
+ return false;
632
+ const next = this.steps.next();
633
+ if (next.done) {
634
+ this.result = next.value;
635
+ this.done?.(next.value);
636
+ }
637
+ }
638
+ return true;
639
+ }
640
+ }
641
+ /**
642
+ * The breaks of a run of a swap (#199): the finished search's (`exact`)
643
+ * where they are the last layout's, then for `run` pages more, then the
644
+ * last layout's again where the builder takes them up (`approximateBreaks`,
645
+ * a page of the same number first, as a preview does). The search's own
646
+ * plan if the rest of its pages are within the run, or if the last
647
+ * layout's breaks are not taken up again before the end.
648
+ */
649
+ function swapRun(last, search, exact, flow, opts, matcher, alike, run) {
650
+ const at = resumeAt(last, search, exact, flow.length) ?? { state: last.states.get(0), steps: 0 };
651
+ if (at.steps + run >= exact.length)
652
+ return exact;
653
+ const steps = new Map([...search.fired].map(([k, pages]) => [pages, k]));
654
+ const byNext = new Map();
655
+ for (const s of last.states.values())
656
+ if (s.pages > at.state.pages)
657
+ byNext.set(s.next, [...(byNext.get(s.next) ?? []), s]);
658
+ const approx = approximateBreaks(flow, opts, at.state, (state, made) => {
659
+ const o = (byNext.get(state.next) ?? []).find((o) => matcher.same(state, o, alike));
660
+ return o && (o.number === state.number || made > RENUMBER_AFTER) ? steps.get(o.pages) : undefined;
661
+ }, exact.slice(at.steps, at.steps + run));
662
+ if (approx.rejoined === undefined)
663
+ return exact;
664
+ return [...exact.slice(0, at.steps), ...approx.steps, ...search.plan.slice(approx.rejoined)];
665
+ }
666
+ /**
667
+ * How many pages a preview (`approximateBreaks`) makes before it takes up
668
+ * the last layout's breaks on a page of another number, which numbers every
669
+ * page after again: a page more or less is not worth that sooner.
670
+ */
671
+ const RENUMBER_AFTER = 8;
672
+ /** Whether two lists' signatures are the same. */
673
+ function sameList(a, b) {
674
+ return a === b || (a.length === b.length && a.every((x, i) => x === b[i]));
675
+ }
676
+ /** Where two layouts' items differ: the first place, and the place in the new from which they are the same to the end, `delta` after the old's. */
677
+ function differ(old, signatures) {
678
+ const n = Math.min(old.length, signatures.length);
679
+ let first = 0;
680
+ while (first < n && old[first] === signatures[first])
681
+ first++;
682
+ // The same lists: the same from the start.
683
+ if (first === n && old.length === signatures.length)
684
+ return { first, same: 0, delta: 0 };
685
+ let common = 0;
686
+ while (common < n - first && old[old.length - 1 - common] === signatures[signatures.length - 1 - common])
687
+ common++;
688
+ return { first, same: signatures.length - common, delta: signatures.length - old.length };
689
+ }
690
+ /**
691
+ * Where a lookahead layout's builder starts again: after the most of the
692
+ * last plan's breaks that begin `plan` too, at a state of the last
693
+ * layout's before the first page that looked as far as `first` (nothing
694
+ * held over or made from there). None: from the start.
695
+ */
696
+ function resumeAt(last, search, plan, first) {
697
+ let shared = 0;
698
+ while (shared < plan.length && shared < search.plan.length && plan[shared] === search.plan[shared])
699
+ shared++;
700
+ let r = last.looked.findIndex((s) => s >= first);
701
+ if (r < 0)
702
+ r = last.pages.length;
703
+ for (let k = shared; k > 0; k--) {
704
+ const pages = search.fired.get(k);
705
+ if (pages === undefined || pages > r)
706
+ continue;
707
+ const s = last.states.get(pages);
708
+ if (s && s.next <= first && s.held.every((h) => h.index < first) && s.made.every((m) => m.before < first))
709
+ return { state: s, steps: k };
710
+ }
711
+ return undefined;
712
+ }
713
+ /** The search the next layout starts from: the plan, and the builder's pages after each break, the last's before the restart and after the stop, renumbered. */
714
+ function keepSearch(old, base, lag, stop, plan, fired, exact, approximate) {
715
+ const kept = new Map(old ? [...old.fired].filter(([s]) => s < base) : []);
716
+ for (const [s, p] of fired)
717
+ kept.set(s, p);
718
+ if (old && stop) {
719
+ const pages = stop.state.pages - stop.last.pages;
720
+ const stopped = Math.max(...fired.keys());
721
+ for (const [s, p] of old.fired)
722
+ if (s - lag > stopped)
723
+ kept.set(s - lag, p + pages);
724
+ }
725
+ return { plan, fired: kept, exact, approximate };
726
+ }
727
+ /**
728
+ * Where to start again: the last layout's state before the first page that
729
+ * looked as far as the first item that differs (its inserts held over and
730
+ * what the builder made all before that item). A page ends as one of the
731
+ * last layout's when the items after it are the last layout's (the same
732
+ * from the end), with the same inserts held over, the same marks, and the
733
+ * page numbers of the same parity, or of either if left and right pages
734
+ * are alike and no break after asks for a side.
735
+ */
736
+ function restartFrom(last, signatures) {
737
+ // Items from `same` on are the last layout's from `same - delta` on.
738
+ const { first, same, delta } = differ(last.signatures, signatures);
739
+ let r = last.looked.findIndex((s) => s >= first);
740
+ if (r < 0)
741
+ r = last.pages.length;
742
+ let state;
743
+ for (; r >= 0 && !state; r--) {
744
+ const s = last.states.get(r);
745
+ if (s && s.next <= first && s.held.every((h) => h.index < first) && s.made.every((m) => m.before < first))
746
+ state = s;
747
+ }
748
+ const start = state ?? last.states.get(0);
749
+ const byNext = new Map();
750
+ for (const s of last.states.values())
751
+ if (s.pages > start.pages)
752
+ byNext.set(s.next, [...(byNext.get(s.next) ?? []), s]);
753
+ // A place in this layout's items as the last layout's, where they are the same.
754
+ const was = (i) => (i < first ? i : i >= same ? i - delta : undefined);
755
+ const sig = new Signatures();
756
+ const markSig = (m) => [m.top, m.first, m.bot].map((x) => (x ? sig.item(x) : '')).join('\0');
757
+ const alike = (state, o, sidesAlike) => {
758
+ if (o.held.length !== state.held.length || o.made.length !== state.made.length || o.marks.size !== state.marks.size)
759
+ return false;
760
+ if (!state.held.every((h, k) => {
761
+ const x = o.held[k];
762
+ return was(h.index) === x.index && h.list.length === x.list.length && h.continued === x.continued && Math.abs(h.height - x.height) < 1e-9;
763
+ }))
764
+ return false;
765
+ if (!state.made.every((m, k) => was(m.before) === o.made[k].before && sig.item(m.item) === sig.item(o.made[k].item)))
766
+ return false;
767
+ if (![...state.marks].every(([name, m]) => o.marks.has(name) && markSig(m) === markSig(o.marks.get(name))))
768
+ return false;
769
+ return (state.number - o.number) % 2 === 0 || sidesAlike(state.next);
770
+ };
771
+ return {
772
+ state: start,
773
+ matches(state, sidesAlike) {
774
+ if (state.next < same)
775
+ return undefined;
776
+ return (byNext.get(state.next - delta) ?? []).find((o) => alike(state, o, sidesAlike));
777
+ },
778
+ same(state, o, sidesAlike) {
779
+ return state.next >= same && state.next - delta === o.next && alike(state, o, sidesAlike);
780
+ },
781
+ };
782
+ }
783
+ /** The state the next layout starts from: the pages kept and those made, and the page builder's states and how far each page looked, renumbered after the stop. */
784
+ function keepLayout(pages, numbered, reads, signatures, builder, restart, stop, last, search) {
785
+ const kept = pages.map((laid, i) => {
786
+ const p = numbered[i];
787
+ return { laid, name: p.context.name, resets: p.resets, total: pages.length, folio: p.folio, prefix: p.prefix, reads: reads.get(laid) ?? { total: true, targets: true } };
788
+ });
789
+ const states = new Map();
790
+ const from = restart?.state.pages ?? 0;
791
+ const looked = [];
792
+ if (last && restart) {
793
+ looked.push(...last.looked.slice(0, from));
794
+ for (const [k, s] of last.states)
795
+ if (k <= from)
796
+ states.set(k, s);
797
+ }
798
+ looked.push(...builder.looked);
799
+ for (const [k, s] of builder.states)
800
+ states.set(k, s);
801
+ if (last && stop) {
802
+ const delta = signatures.length - last.signatures.length;
803
+ const pagesShift = stop.state.pages - stop.last.pages;
804
+ const numberShift = stop.state.number - stop.last.number;
805
+ looked.push(...last.looked.slice(stop.last.pages).map((s) => (s < 0 ? s : s + delta)));
806
+ for (const [k, s] of last.states) {
807
+ if (k <= stop.last.pages)
808
+ continue;
809
+ states.set(k + pagesShift, {
810
+ ...s, pages: s.pages + pagesShift, number: s.number + numberShift, next: s.next + delta,
811
+ held: s.held.map((h) => ({ ...h, index: h.index + delta })), made: s.made.map((m) => ({ ...m, before: m.before + delta })),
812
+ });
813
+ }
814
+ }
815
+ return { signatures, pages: kept, looked, states, ...(search ? { search } : {}) };
816
+ }
817
+ /** Every element placed before `next` in the items, and the root: what started on the pages kept before a restart. */
818
+ function placedBefore(items, next, root) {
819
+ const out = new Set([root]);
820
+ const add = (item) => {
821
+ if (item.type === 'insert')
822
+ item.list.forEach(add);
823
+ if (item.type !== 'box' || item.kind === 'null')
824
+ return;
825
+ for (const c of item.containers)
826
+ out.add(c);
827
+ out.add(item.element);
828
+ };
829
+ for (let i = 0; i < next && i < items.length; i++)
830
+ add(items[i]);
831
+ return out;
832
+ }
833
+ /** Whether a left and a right page are alike for the page builder, from `from` on: the same height, and no break that asks for a side. */
834
+ function sidesAlike(styles, items, from) {
835
+ if (!styles.sidesAlike())
836
+ return false;
837
+ for (let i = from; i < items.length; i++) {
838
+ const item = items[i];
839
+ if (item.type === 'penalty' && item.side)
840
+ return false;
841
+ }
842
+ return true;
843
+ }
844
+ /** A page kept from the last layout made again for its new side: its text area, as it was, in a page of the new box. */
845
+ function reshell(old, box, lang, pageClass, blank, name) {
846
+ const { page, area } = shell(box, lang, `${pageClass ?? ''}${blank ? ' pw-blank' : ''}`.trim());
847
+ if (name)
848
+ page.dataset.pwPageName = name;
849
+ if (box.offset > 0) {
850
+ const o = box.offset;
851
+ page.dataset.pwTrimBox = `${o} ${o} ${box.width} ${box.height}`;
852
+ page.dataset.pwBleedBox = `${o - box.bleed} ${o - box.bleed} ${box.width + 2 * box.bleed} ${box.height + 2 * box.bleed}`;
853
+ }
854
+ const was = old.querySelector(':scope > .pw-area');
855
+ if (was) {
856
+ was.style.cssText = area.style.cssText;
857
+ area.replaceWith(was);
858
+ }
859
+ else {
860
+ area.remove();
861
+ }
862
+ old.replaceWith(page);
863
+ return page;
864
+ }
865
+ /** Two page boxes alike. */
866
+ function sameBox(a, b) {
867
+ return a.width === b.width && a.height === b.height && a.offset === b.offset && a.bleed === b.bleed &&
868
+ a.margin.top === b.margin.top && a.margin.right === b.margin.right && a.margin.bottom === b.margin.bottom && a.margin.left === b.margin.left &&
869
+ a.marks.crop === b.marks.crop && a.marks.cross === b.marks.cross;
870
+ }
871
+ /** An object's number, for signatures that tell objects apart. */
872
+ const ids = new WeakMap();
873
+ let lastId = 0;
874
+ /**
875
+ * Signatures of what the page builder is given: two items made from the
876
+ * same thing (the same HTML, with the same keys, laid out alike) have the
877
+ * same signature, made again or reused from the last layout, so an
878
+ * incremental layout knows where its items differ from the last's. An
879
+ * element's HTML is read the first time it is signed, before the pages
880
+ * change it, and kept with it.
881
+ */
882
+ class Signatures {
883
+ static html = new WeakMap();
884
+ chains = new Map();
885
+ shallow = new Map();
886
+ of(items) {
887
+ return items.map((i) => this.item(i));
888
+ }
889
+ /** Marks' values, by name. */
890
+ marks(marks) {
891
+ return [...marks].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
892
+ .map(([name, m]) => `${name}\0${[m.top, m.first, m.bot].map((x) => (x ? this.item(x) : '')).join('\0')}`).join('\n');
893
+ }
894
+ item(i) {
895
+ switch (i.type) {
896
+ case 'glue': return `g${i.width},${i.stretch},${i.stretchOrder ?? 0},${i.shrink}`;
897
+ case 'penalty': return `p${i.penalty}${i.side ?? ''}`;
898
+ case 'mark': return i.kind === 'string' ? `m${i.name}\0${i.text}` : `r${i.name}\0${this.html(i.element)}`;
899
+ case 'insert': return `i${i.class},${i.height},${this.attributes(i.element)}[${i.list.map((x) => this.item(x)).join(';')}]`;
900
+ case 'box': {
901
+ if (i.kind === 'null')
902
+ return `n${i.height},${i.depth}`;
903
+ const size = `${i.height},${i.depth},${i.width},${i.shift}`;
904
+ const what = i.kind === 'edge' ? `${i.side}${this.attributes(i.element)}` : this.html(i.element);
905
+ const extra = i.kind === 'columns' && i.columns ? `${i.height}:${i.columns.map((c) => c.items.length).join(',')}` : '';
906
+ return `b${i.kind}${size}|${this.chain(i.containers)}|${what}${extra}`;
907
+ }
908
+ }
909
+ }
910
+ html(el) {
911
+ let s = Signatures.html.get(el);
912
+ if (s === undefined)
913
+ Signatures.html.set(el, (s = el.outerHTML));
914
+ return s;
915
+ }
916
+ attributes(el) {
917
+ let s = this.shallow.get(el);
918
+ if (s === undefined) {
919
+ s = el.localName;
920
+ for (const name of el.getAttributeNames())
921
+ s += ` ${name}=${el.getAttribute(name)}`;
922
+ this.shallow.set(el, s);
923
+ }
924
+ return s;
925
+ }
926
+ chain(containers) {
927
+ let s = this.chains.get(containers);
928
+ if (s === undefined)
929
+ this.chains.set(containers, (s = containers.map((c) => this.attributes(c)).join('>')));
930
+ return s;
931
+ }
932
+ }
933
+ /** The included PDF page a page shows (`img.pw-pdf-page`, from `{.pages}`), if it is one. */
934
+ function includedPage(b) {
935
+ for (const item of b.items) {
936
+ if (item.type !== 'box' || item.kind === 'null')
937
+ continue;
938
+ const el = item.element;
939
+ if (el instanceof HTMLImageElement && el.classList.contains('pw-pdf-page'))
940
+ return el;
941
+ }
942
+ return undefined;
943
+ }
944
+ /**
945
+ * Puts an included page over the sheet's trim box, scaled to fit it and
946
+ * centred, as pdfpages puts one on the paper; in the flow it took no room.
947
+ */
948
+ function fillTrimBox(img, page, box) {
949
+ const parent = img.offsetParent ?? page;
950
+ const sheet = page.getBoundingClientRect();
951
+ const at = parent.getBoundingClientRect();
952
+ Object.assign(img.style, {
953
+ position: 'absolute', margin: '0', objectFit: 'contain',
954
+ left: `${sheet.left + box.offset - at.left}px`, top: `${sheet.top + box.offset - at.top}px`,
955
+ width: `${box.width}px`, height: `${box.height}px`,
956
+ });
957
+ }
352
958
  /**
353
959
  * Lays each element whose page name gives another measure out at that
354
960
  * measure, by moving its right margin, until the list is built; returns
@@ -402,9 +1008,24 @@ function marginContext(b, counter, total, targets) {
402
1008
  return m?.kind === 'string' ? m.text : '';
403
1009
  },
404
1010
  element: (name, policy) => pick(name, policy, 'running')?.element,
405
- target: (id, name) => (name === 'page' ? targets.get(id) : undefined),
1011
+ target: (id, name) => (name === 'page' ? targets().get(id) : undefined),
406
1012
  };
407
1013
  }
1014
+ /**
1015
+ * What a viewer does with the page, from its `@page` rules, for the PDF
1016
+ * (`pdf/structure/presentation.ts` reads them): `--pw-page-rotate`,
1017
+ * `--pw-page-duration` and `--pw-page-transition`, as written, in
1018
+ * `data-pw-page-rotate`, `-duration` and `-transition`.
1019
+ */
1020
+ function presentation(element, style) {
1021
+ for (const [prop, data] of [['--pw-page-rotate', 'pwPageRotate'], ['--pw-page-duration', 'pwPageDuration'], ['--pw-page-transition', 'pwPageTransition']]) {
1022
+ const v = valueOf(style.page, prop)?.trim();
1023
+ if (v)
1024
+ element.dataset[data] = v;
1025
+ else
1026
+ delete element.dataset[data];
1027
+ }
1028
+ }
408
1029
  /** A page's `counter-reset: page <n>` or `counter-set`, from its `@page` rules or, failing them, the last element starting on it to set one. */
409
1030
  function pageCounterReset(style, elements) {
410
1031
  const own = (prop) => {
@@ -420,17 +1041,6 @@ function pageCounterIncrement(style) {
420
1041
  const v = valueOf(style.page, 'counter-increment');
421
1042
  return (v === undefined ? undefined : counterValue(v, 'page', 1)) ?? 1;
422
1043
  }
423
- /** A counter's value in a `counter-reset`-like list (`page 3 chapter`); `fallback` when it has none. */
424
- function counterValue(value, name, fallback = 0) {
425
- const ws = value.trim().split(/\s+/);
426
- for (let i = 0; i < ws.length; i++) {
427
- if (ws[i] !== name)
428
- continue;
429
- const n = ws[i + 1] !== undefined && /^[-+]?\d+$/.test(ws[i + 1]) ? Number.parseInt(ws[i + 1], 10) : fallback;
430
- return n;
431
- }
432
- return undefined;
433
- }
434
1044
  /** The style a page's margin boxes write its number in, if any of them does. */
435
1045
  function folioStyle(style) {
436
1046
  for (const decls of style.margins.values()) {
@@ -445,6 +1055,10 @@ function unquote(s) {
445
1055
  return m ? m[2].replace(/\\(.)/g, '$1') : s.trim();
446
1056
  }
447
1057
  /** The page context's background, to the bleed's edge. */
1058
+ /** A page style's background, as `background` paints it. */
1059
+ function backgroundOf(style) {
1060
+ return style.page.filter((d) => d.prop.startsWith('background')).map((d) => `${d.prop}:${d.value}`).join(';');
1061
+ }
448
1062
  function background(page, box, style) {
449
1063
  const decls = style.page.filter((d) => d.prop.startsWith('background'));
450
1064
  if (!decls.length)
@@ -462,7 +1076,7 @@ function background(page, box, style) {
462
1076
  page.prepend(el);
463
1077
  }
464
1078
  /** Crop marks' and cross marks' sizes, in px: 0.5pt lines, 3pt from the bleed, 18pt long; a cross 18pt wide in a 12pt circle. */
465
- const MARK = { line: 2 / 3, gap: 4, length: 24, cross: 24, circle: 16 };
1079
+ export const MARK = { line: 2 / 3, gap: 4, length: 24, cross: 24, circle: 16 };
466
1080
  /**
467
1081
  * CSS's `marks`: crop marks at the trim's corners, outside the bleed, and
468
1082
  * cross marks (registration targets) at the middle of each side, in the
@@ -556,7 +1170,7 @@ function floatRegion(area, cls) {
556
1170
  * `\vspace*` keeps it: an empty box before it, held to it by `\nobreak`;
557
1171
  * so is space that is only stretch, `--pw-space-before: 0pt plus 1fil`.
558
1172
  */
559
- function contributions(items, floatSkip, names) {
1173
+ function contributions(items, floatSkip, names, customInserts) {
560
1174
  const out = [];
561
1175
  let kept = true;
562
1176
  let name;
@@ -585,52 +1199,71 @@ function contributions(items, floatSkip, names) {
585
1199
  continue;
586
1200
  }
587
1201
  const list = [{ type: 'penalty', penalty: 100 }, ...item.list];
588
- if (item.class === 'top')
1202
+ const customRegion = customInserts?.get(item.class)?.region;
1203
+ if (item.class === 'top' || customRegion === 'top')
589
1204
  list.push({ type: 'penalty', penalty: 10000 }, { type: 'glue', ...floatSkip });
590
1205
  out.push({ ...item, list, height: natural(list) });
591
1206
  }
592
1207
  return out;
593
1208
  }
594
1209
  /**
595
- * Gives the page builder the list, breaking each multi-column box into rows
596
- * of columns as it comes, as LaTeX's `multicols` does: the first row fills
597
- * what is left of its page (`builder.room()`), each next row a page, and
598
- * the last is balanced, its columns as short as holds what is left. Each
599
- * column is broken from the list as TeX's `\vsplit` breaks it
600
- * (`vertBreak`), its last line's depth inside it. When the page has too
601
- * little room left for what must stay with the columns (a heading before
602
- * them, held to them by a +10000 penalty) and two lines of them, the page
603
- * is broken before that, as `multicols` breaks it when less than
604
- * `\premulticols` is left.
1210
+ * Breaks each multi-column box into rows as it comes, as `contribute` does,
1211
+ * from `start` on. `out` collects the rows, so a lookahead search can break
1212
+ * the list the greedy builder's room produced without asking the page's
1213
+ * room again.
605
1214
  */
606
- function contribute(builder, items) {
607
- let from = 0;
608
- for (const [i, item] of items.entries()) {
1215
+ function feedColumns(items, sink, out, start = 0) {
1216
+ const give = (chunk, from) => {
1217
+ out?.push(...chunk);
1218
+ sink.contribute(chunk, from);
1219
+ };
1220
+ let from = start;
1221
+ for (let i = start; i < items.length && !sink.stopped; i++) {
1222
+ const item = items[i];
609
1223
  if (item.type !== 'box' || item.kind !== 'columns')
610
1224
  continue;
611
- const k = lastBreakpoint(items, from, i);
612
- builder.contribute(items.slice(from, k));
1225
+ let k = lastBreakpoint(items, from, i);
1226
+ // Straight after another multi-column box's rows (a spanner between
1227
+ // them), the builder must meet the breakpoint after the rows before the
1228
+ // room is read: there it ends the page they fill.
1229
+ if (k === from && from > start && from < i && breaksAt(items, from))
1230
+ k = from + 1;
1231
+ give(items.slice(from, k), from);
613
1232
  const kept = items.slice(k, i);
614
- if (builder.room() < natural(kept) + opening(item.list))
615
- builder.contribute([{ type: 'penalty', penalty: EJECT_PENALTY }]);
616
- builder.contribute(kept);
617
- builder.contribute(columnRows(item, builder.room(), (k) => builder.vsizeAfter(k)));
1233
+ if (sink.room() < natural(kept) + opening(item.list))
1234
+ give([{ type: 'penalty', penalty: EJECT_PENALTY }]);
1235
+ give(kept, k);
1236
+ give(columnRows(item, sink.room(), (ahead) => sink.vsizeAfter(ahead)));
1237
+ sink.skip?.(i + 1);
618
1238
  from = i + 1;
619
1239
  }
620
- builder.contribute(items.slice(from));
1240
+ give(items.slice(from), from);
1241
+ }
1242
+ function contribute(builder, items, start = 0) {
1243
+ feedColumns(items, builder, undefined, start);
1244
+ }
1245
+ /** The list with each multi-column box replaced by the rows the greedy builder would give it. */
1246
+ function expandColumns(items, opts) {
1247
+ const scratch = new PageBuilder(opts);
1248
+ const out = [];
1249
+ feedColumns(items, scratch, out);
1250
+ return out;
621
1251
  }
622
1252
  /** Where the page could last break before `end`: a penalty under 10000, or glue after a box. `from` if nowhere. */
623
1253
  function lastBreakpoint(items, from, end) {
624
- for (let k = end - 1; k > from; k--) {
625
- const p = items[k];
626
- if (p.type === 'penalty' && p.penalty < INFINITE_VPENALTY)
627
- return k;
628
- const before = items[k - 1];
629
- if (p.type === 'glue' && (before.type === 'box' || before.type === 'mark' || before.type === 'insert'))
1254
+ for (let k = end - 1; k > from; k--)
1255
+ if (breaksAt(items, k))
630
1256
  return k;
631
- }
632
1257
  return from;
633
1258
  }
1259
+ /** Whether the page could break at `items[k]`: a penalty under 10000, or glue after a box. */
1260
+ function breaksAt(items, k) {
1261
+ const p = items[k];
1262
+ if (p.type === 'penalty')
1263
+ return p.penalty < INFINITE_VPENALTY;
1264
+ const before = items[k - 1];
1265
+ return p.type === 'glue' && (before?.type === 'box' || before?.type === 'mark' || before?.type === 'insert');
1266
+ }
634
1267
  /** The height of a column's first two boxes, and what is between them: the least a row of columns may start a page's foot with. */
635
1268
  function opening(list) {
636
1269
  const start = pruneTop(list, ZERO);
@@ -651,27 +1284,6 @@ const EPSILON = 1e-6;
651
1284
  */
652
1285
  function columnRows(box, room, vsizeAfter) {
653
1286
  const out = [];
654
- const sp = (t, s) => badness(Math.round(t * SP_PER_PX), Math.round(s * SP_PER_PX));
655
- /** The list broken into `box.count` columns of height `h`, and what is left. */
656
- const split = (list, h) => {
657
- const columns = [];
658
- let rest = list;
659
- for (let c = 0; c < box.count; c++) {
660
- if (!rest.some((p) => p.type === 'box')) {
661
- columns.push([]);
662
- continue;
663
- }
664
- const at = vertBreak(rest, h, 0, sp).at;
665
- columns.push(at === undefined ? [...rest] : rest.slice(0, at));
666
- rest = at === undefined ? [] : pruneTop(rest.slice(at), ZERO);
667
- }
668
- return { columns, rest };
669
- };
670
- /** Whether the list goes in one row `h` high, no column overfull. */
671
- const fits = (list, h) => {
672
- const { columns, rest } = split(list, h);
673
- return !rest.some((p) => p.type === 'box') && columns.every((c) => natural(c) <= h + EPSILON);
674
- };
675
1287
  const row = (columns, h, set) => ({
676
1288
  ...box, height: Math.max(0, h - EPSILON), depth: 0,
677
1289
  columns: columns.map((items) => ({ items: items, glue: set ? vpack(items, h, 0).glue : NATURAL })),
@@ -682,25 +1294,13 @@ function columnRows(box, room, vsizeAfter) {
682
1294
  for (let guard = 0; rest.some((p) => p.type === 'box'); guard++) {
683
1295
  if (guard > 10000)
684
1296
  throw new Error('a multi-column box never ends: its columns take nothing');
685
- if (fits(rest, h)) {
686
- // The last row: the shortest height that holds the rest.
687
- let lo = natural(rest) / box.count;
688
- let hi = h;
689
- if (fits(rest, lo))
690
- hi = lo;
691
- else
692
- for (let n = 0; n < 30 && hi - lo > 1 / 64; n++) {
693
- const mid = (lo + hi) / 2;
694
- if (fits(rest, mid))
695
- hi = mid;
696
- else
697
- lo = mid;
698
- }
699
- const { columns } = split(rest, hi);
1297
+ const balanced = balancedColumnHeight(rest, box.count, h);
1298
+ if (balanced !== undefined) {
1299
+ const { columns } = splitColumns(rest, box.count, balanced);
700
1300
  out.push(row(columns, Math.max(...columns.map((c) => natural(c))), false));
701
1301
  break;
702
1302
  }
703
- const { columns, rest: left } = split(rest, h);
1303
+ const { columns, rest: left } = splitColumns(rest, box.count, h);
704
1304
  if (h < vsizeAfter(ahead) && columns.some((c) => natural(c) > h)) {
705
1305
  // Not even a line fits what is left of the page: the columns start on the next.
706
1306
  out.push({ type: 'penalty', penalty: EJECT_PENALTY });
@@ -723,9 +1323,11 @@ function fixTables(root) {
723
1323
  const rows = [...table.rows];
724
1324
  if (!rows.length)
725
1325
  continue;
726
- const row = rows.reduce((a, r) => (r.cells.length > a.cells.length ? r : a));
727
- const widths = [...row.cells].flatMap((c) => Array.from({ length: c.colSpan }, () => c.getBoundingClientRect().width / c.colSpan));
1326
+ const widths = columnWidths(rows);
728
1327
  const width = table.getBoundingClientRect().width;
1328
+ // The author's widths (`colgroup`) are in those the browser gave.
1329
+ for (const group of table.querySelectorAll(':scope > colgroup'))
1330
+ group.remove();
729
1331
  const group = document.createElement('colgroup');
730
1332
  group.className = 'pw-columns';
731
1333
  for (const w of widths) {
@@ -738,18 +1340,76 @@ function fixTables(root) {
738
1340
  table.style.width = `${width}px`;
739
1341
  }
740
1342
  }
1343
+ /**
1344
+ * The widths of a table's columns, from its cells as they stand on its
1345
+ * grid (cells spanning rows above leave a row's later cells further
1346
+ * right): each column's from a cell of its own, else its share of a cell
1347
+ * spanning it and others.
1348
+ */
1349
+ function columnWidths(rows) {
1350
+ const own = [];
1351
+ const shared = [];
1352
+ const taken = rows.map(() => new Set());
1353
+ rows.forEach((row, r) => {
1354
+ let column = 0;
1355
+ for (const cell of row.cells) {
1356
+ while (taken[r].has(column))
1357
+ column++;
1358
+ const w = cell.getBoundingClientRect().width;
1359
+ for (let k = 0; k < cell.colSpan; k++) {
1360
+ if (cell.colSpan === 1)
1361
+ own[column] ??= w;
1362
+ else
1363
+ shared[column + k] ??= w / cell.colSpan;
1364
+ for (let i = 0; i < cell.rowSpan && r + i < rows.length; i++)
1365
+ taken[r + i].add(column + k);
1366
+ }
1367
+ column += cell.colSpan;
1368
+ }
1369
+ });
1370
+ return Array.from({ length: Math.max(own.length, shared.length) }, (_, c) => own[c] ?? shared[c] ?? 0);
1371
+ }
741
1372
  /** A table's header rows, repeated at the top of each page it continues on. */
742
1373
  class HeaderRows {
743
1374
  rows = new Map();
744
1375
  repeat(last, next) {
745
1376
  if (last?.type !== 'box' || last.kind !== 'row' || next.type !== 'box' || next.kind !== 'row' || next.header)
746
1377
  return [];
747
- const t = next.containers.indexOf([...next.containers].reverse().find((c) => c instanceof HTMLTableElement));
748
- const table = next.containers[t];
749
- if (!table?.tHead || !last.containers.includes(table))
1378
+ const table = this.tableOf(next);
1379
+ if (!table || !last.containers.includes(table))
750
1380
  return [];
1381
+ const rows = this.measure(table, next);
1382
+ // Each time a fresh copy of each row, without ids, kept with the next.
1383
+ const out = [];
1384
+ for (const { row, box } of rows) {
1385
+ const clone = row.cloneNode(true);
1386
+ for (const el of [clone, ...clone.querySelectorAll('[id]')])
1387
+ el.removeAttribute('id');
1388
+ clone.dataset.pwRepeated = '';
1389
+ clone.dataset.pwGenerated = 'repeated';
1390
+ out.push({ ...box, element: clone }, { type: 'penalty', penalty: 10000 });
1391
+ }
1392
+ return out;
1393
+ }
1394
+ /** Measures every table's header in `items` that a page could repeat: a search left to finish (#180) may repeat one after the layout has moved it. */
1395
+ prime(items) {
1396
+ for (const item of items) {
1397
+ if (item.type !== 'box' || item.kind !== 'row' || item.header)
1398
+ continue;
1399
+ const table = this.tableOf(item);
1400
+ if (table)
1401
+ this.measure(table, item);
1402
+ }
1403
+ }
1404
+ /** A row's innermost table, if it has a header. */
1405
+ tableOf(row) {
1406
+ const table = [...row.containers].reverse().find((c) => c instanceof HTMLTableElement);
1407
+ return table?.tHead ? table : undefined;
1408
+ }
1409
+ measure(table, next) {
751
1410
  let rows = this.rows.get(table);
752
1411
  if (!rows) {
1412
+ const t = next.containers.indexOf(table);
753
1413
  const containers = [...next.containers.slice(0, t + 1), table.tHead];
754
1414
  rows = [...table.tHead.rows].map((row) => {
755
1415
  const r = row.getBoundingClientRect();
@@ -757,16 +1417,559 @@ class HeaderRows {
757
1417
  });
758
1418
  this.rows.set(table, rows);
759
1419
  }
760
- // Each time a fresh copy of each row, without ids, kept with the next.
1420
+ return rows;
1421
+ }
1422
+ }
1423
+ /** Default gap between a margin insert region and the text area: 12pt in px. */
1424
+ const DEFAULT_MARGIN_GAP = 16;
1425
+ /** Width of one margin-placed insert class on a page of `box` and `side`. */
1426
+ function marginInsertWidth(def, box, em, side) {
1427
+ if (def.width)
1428
+ return Math.max(16, parseLength(def.width, em));
1429
+ const region = def.region ?? 'margin-outer';
1430
+ const gap = def.gap ? parseLength(def.gap, em) : DEFAULT_MARGIN_GAP;
1431
+ const marginSide = region === 'margin-left' ? 'left'
1432
+ : region === 'margin-right' ? 'right'
1433
+ : region === 'margin-inner' ? (side === 'left' ? 'right' : 'left')
1434
+ : side;
1435
+ const avail = marginSide === 'left' ? box.margin.left : box.margin.right;
1436
+ return Math.max(16, avail - gap * 1.5);
1437
+ }
1438
+ /** Measuring widths for every margin-placed custom insert class. */
1439
+ function marginInsertWidths(customInserts, box, em) {
1440
+ const widths = new Map();
1441
+ for (const [name, def] of customInserts) {
1442
+ const region = def.region ?? 'margin-outer';
1443
+ if (region === 'top' || region === 'bottom')
1444
+ continue;
1445
+ widths.set(name, marginInsertWidth(def, box, em, 'right'));
1446
+ }
1447
+ return widths;
1448
+ }
1449
+ /** Adds a plugin's insert classes to the page builder's registers. Margin classes do not shrink the text area. */
1450
+ function addCustomInserts(inserts, customInserts, em, vsize, maxDepth, floatSkip, zero) {
1451
+ if (!customInserts)
1452
+ return;
1453
+ for (const [name, def] of customInserts) {
1454
+ const region = def.region ?? 'margin-outer';
1455
+ const occupiesMain = region === 'top' || region === 'bottom';
1456
+ inserts[name] = {
1457
+ skip: def.skip ? parseGlue(def.skip, em) : region === 'bottom' ? floatSkip : zero,
1458
+ maxHeight: def.maxHeight ? parseLength(def.maxHeight, em) : vsize,
1459
+ floatingPenalty: def.floatingPenalty ?? 0,
1460
+ splitTopSkip: def.splitTopSkip ? parseGlue(def.splitTopSkip, em) : zero,
1461
+ splitMaxDepth: def.splitMaxDepth ? parseLength(def.splitMaxDepth, em) : maxDepth,
1462
+ occupiesMain,
1463
+ };
1464
+ }
1465
+ }
1466
+ /** Reads TeX's page-builder parameters (`--pw-top-skip`, `--pw-max-depth`, insert skips/limits) from a flow's root. */
1467
+ function readFlowParams(root, vsize, customInserts) {
1468
+ const cs = getComputedStyle(root);
1469
+ const em = Number.parseFloat(cs.fontSize) || 16;
1470
+ const glue = (prop, fallback) => parseGlue(cs.getPropertyValue(prop).trim() || fallback, em);
1471
+ const length = (prop, fallback) => {
1472
+ const v = cs.getPropertyValue(prop).trim();
1473
+ return v && v !== 'none' ? parseLength(v, em) : fallback;
1474
+ };
1475
+ const maxDepth = length('--pw-max-depth', 0);
1476
+ const floatSkip = glue('--pw-float-skip', BIGSKIP);
1477
+ const zero = { width: 0, stretch: 0, shrink: 0 };
1478
+ const floats = { skip: zero, maxHeight: vsize, floatingPenalty: 0, splitTopSkip: zero, splitMaxDepth: Number.MAX_SAFE_INTEGER };
1479
+ const inserts = {
1480
+ footnote: {
1481
+ skip: glue('--pw-footnote-skip', BIGSKIP), maxHeight: length('--pw-footnote-max-height', vsize), floatingPenalty: 20000,
1482
+ splitTopSkip: zero, splitMaxDepth: maxDepth,
1483
+ },
1484
+ top: floats,
1485
+ bottom: { ...floats, skip: floatSkip },
1486
+ };
1487
+ addCustomInserts(inserts, customInserts, em, vsize, maxDepth, floatSkip, zero);
1488
+ return { maxDepth, topSkip: glue('--pw-top-skip', '0px'), floatSkip, inserts };
1489
+ }
1490
+ /**
1491
+ * A box taller than its page or region is placed alone, overfull, and cut off:
1492
+ * named before it moves. (A page a little over its goal, as TeX's can be after
1493
+ * an insert is split, is no such loss.)
1494
+ */
1495
+ function overfullWarnings(built) {
1496
+ return built.flatMap((b) => {
1497
+ if (b.overfull <= VFUZZ)
1498
+ return [];
1499
+ const tallest = b.items.reduce((t, i) => i.type === 'box' && i.kind !== 'null' && (!t || i.height + i.depth > t.height + t.depth) ? i : t, undefined);
1500
+ if (!tallest || tallest.height + tallest.depth <= b.height + VFUZZ)
1501
+ return [];
1502
+ const element = tallest.element.closest('[data-pw-key]') ?? tallest.element;
1503
+ return [{
1504
+ code: 'overfull-page',
1505
+ message: `page ${b.number} is ${(b.overfull * 0.75).toFixed(1)}pt overfull: a ${element.localName} is taller than the page, and is cut off`,
1506
+ elements: [element],
1507
+ }];
1508
+ });
1509
+ }
1510
+ /** Reads `counter-reset: page` / `counter-set: page` on elements starting on each page before they move. */
1511
+ function collectPageResets(built, root) {
1512
+ const started = new Set();
1513
+ return built.map((b, i) => {
761
1514
  const out = [];
762
- for (const { row, box } of rows) {
763
- const clone = row.cloneNode(true);
764
- for (const el of [clone, ...clone.querySelectorAll('[id]')])
765
- el.removeAttribute('id');
766
- clone.dataset.pwRepeated = '';
767
- out.push({ ...box, element: clone }, { type: 'penalty', penalty: 10000 });
1515
+ const starts = (el) => {
1516
+ if (started.has(el))
1517
+ return;
1518
+ started.add(el);
1519
+ const cs = getComputedStyle(el);
1520
+ const n = counterValue(cs.getPropertyValue('counter-set'), 'page') ?? counterValue(cs.counterReset, 'page');
1521
+ if (n !== undefined)
1522
+ out.push(n);
1523
+ };
1524
+ if (i === 0)
1525
+ starts(root);
1526
+ for (const item of b.items) {
1527
+ if (item.type !== 'box' || item.kind === 'null')
1528
+ continue;
1529
+ for (const el of item.containers)
1530
+ starts(el);
1531
+ if (item.kind !== 'line')
1532
+ starts(item.element);
768
1533
  }
769
1534
  return out;
1535
+ });
1536
+ }
1537
+ /** Places one region's main text, top/bottom floats and footnotes inside `host`, sharing one region builder across single-region pages and page templates. */
1538
+ function placeRegionContent(host, main, root, b, inserts, fragments, lines, customInserts) {
1539
+ main.style.height = `${b.height}px`;
1540
+ new Region(main, root, fragments, lines).build(b.items, b.glue);
1541
+ const placed = (cls) => (b.inserts[cls] ?? []).filter((x) => x.list.some((i) => i.type === 'box'));
1542
+ const top = placed('top');
1543
+ const bottom = placed('bottom');
1544
+ const notes = placed('footnote');
1545
+ let topHeight = 0;
1546
+ if (top.length) {
1547
+ const region = floatRegion(host, 'pw-top-floats');
1548
+ region.style.top = '0';
1549
+ new Region(region, root, fragments, lines).build(top.flatMap((x) => x.list), NATURAL);
1550
+ topHeight = natural(top.flatMap((x) => x.list));
1551
+ }
1552
+ const sortedCustom = customInserts ? [...customInserts.entries()].sort(([a], [c]) => a.localeCompare(c)) : [];
1553
+ for (const [cls, def] of sortedCustom) {
1554
+ if (def.region !== 'top')
1555
+ continue;
1556
+ const items = placed(cls);
1557
+ if (!items.length)
1558
+ continue;
1559
+ const region = floatRegion(host, `pw-top-floats pw-insert-${cls}`);
1560
+ region.dataset.pwInsert = cls;
1561
+ region.style.top = `${topHeight}px`;
1562
+ const flat = items.flatMap((x) => x.list);
1563
+ new Region(region, root, fragments, lines).build(flat, NATURAL);
1564
+ topHeight += natural(flat) + (inserts[cls]?.skip.width ?? 0);
1565
+ }
1566
+ if (topHeight > 0)
1567
+ main.style.top = `${topHeight}px`;
1568
+ let bottomOffset = 0;
1569
+ if (notes.length) {
1570
+ const region = floatRegion(host, 'pw-footnotes');
1571
+ region.style.bottom = '0';
1572
+ const rule = document.createElement('div');
1573
+ rule.className = 'pw-footnote-rule';
1574
+ rule.style.cssText = 'position:absolute;left:0;bottom:100%';
1575
+ region.append(rule);
1576
+ new Region(region, root, fragments, lines).build(notes.flatMap((x) => x.list), NATURAL);
1577
+ bottomOffset = natural(notes.flatMap((x) => x.list)) + (inserts.footnote?.skip.width ?? 0);
1578
+ }
1579
+ if (bottom.length) {
1580
+ const region = floatRegion(host, 'pw-bottom-floats');
1581
+ region.style.bottom = `${bottomOffset}px`;
1582
+ const flat = bottom.flatMap((x) => x.list);
1583
+ new Region(region, root, fragments, lines).build(flat, NATURAL);
1584
+ bottomOffset += natural(flat) + (inserts.bottom?.skip.width ?? 0);
1585
+ }
1586
+ for (const [cls, def] of sortedCustom) {
1587
+ if (def.region !== 'bottom')
1588
+ continue;
1589
+ const items = placed(cls);
1590
+ if (!items.length)
1591
+ continue;
1592
+ const region = floatRegion(host, `pw-bottom-floats pw-insert-${cls}`);
1593
+ region.dataset.pwInsert = cls;
1594
+ region.style.bottom = `${bottomOffset}px`;
1595
+ const flat = items.flatMap((x) => x.list);
1596
+ new Region(region, root, fragments, lines).build(flat, NATURAL);
1597
+ bottomOffset += natural(flat) + (inserts[cls]?.skip.width ?? 0);
1598
+ }
1599
+ }
1600
+ /** Places plugin-defined margin insert classes (`margin-left`, `margin-right`, `margin-outer`, `margin-inner`) in the page's margins. */
1601
+ function placeMarginInserts(page, box, side, root, b, customInserts, em, fragments, lines) {
1602
+ const offset = { left: 0, right: 0 };
1603
+ const sorted = [...customInserts.entries()].sort(([a], [c]) => a.localeCompare(c));
1604
+ for (const [cls, def] of sorted) {
1605
+ const placement = def.region ?? 'margin-outer';
1606
+ if (placement === 'top' || placement === 'bottom')
1607
+ continue;
1608
+ const items = (b.inserts[cls] ?? []).filter((x) => x.list.some((i) => i.type === 'box'));
1609
+ if (!items.length)
1610
+ continue;
1611
+ const targetSide = placement === 'margin-left' ? 'left'
1612
+ : placement === 'margin-right' ? 'right'
1613
+ : placement === 'margin-inner' ? (side === 'left' ? 'right' : 'left')
1614
+ : side;
1615
+ const gap = def.gap ? parseLength(def.gap, em) : DEFAULT_MARGIN_GAP;
1616
+ const width = marginInsertWidth(def, box, em, side);
1617
+ const left = targetSide === 'left'
1618
+ ? box.offset + Math.max(0, box.margin.left - gap - width)
1619
+ : box.offset + box.width - box.margin.right + gap;
1620
+ const top = box.offset + box.margin.top + offset[targetSide];
1621
+ const region = document.createElement('div');
1622
+ region.className = `pw-margin-insert pw-insert-${cls}`;
1623
+ region.dataset.pwInsert = cls;
1624
+ region.style.cssText = `position:absolute;left:${left}px;top:${top}px;width:${width}px`;
1625
+ page.append(region);
1626
+ const flat = items.flatMap((x) => x.list);
1627
+ new Region(region, root, fragments, lines).build(flat, NATURAL);
1628
+ offset[targetSide] += natural(flat) + (def.skip ? parseGlue(def.skip, em).width : 0);
1629
+ }
1630
+ }
1631
+ /** Numbers pages, resolves folios, paints backgrounds, builds margin boxes and printer marks, and removes the measuring shell. */
1632
+ function finishPages(pages, styles, opts, firstPage, warnings, measuringPage) {
1633
+ let counter = firstPage - 1;
1634
+ const folios = pages.map((p) => {
1635
+ const style = styles.style(p.context);
1636
+ const own = folioStyle(style);
1637
+ return { style, own, folio: own ?? folioStyle(styles.style({ ...p.context, first: false, blank: false })) };
1638
+ });
1639
+ let lastStyle = folios.find((f) => f.folio)?.folio ?? 'decimal';
1640
+ const numbered = pages.map((p, i) => {
1641
+ const { style } = folios[i];
1642
+ const reset = pageCounterReset(style, p.resets);
1643
+ counter = reset ?? counter + pageCounterIncrement(style);
1644
+ const folio = (p.b.blank && i > 0 ? folios[i].own : folios[i].folio) ?? lastStyle;
1645
+ lastStyle = folio;
1646
+ const label = opts.label?.(p.b.number) ?? formatCounter(counter, folio);
1647
+ p.element.dataset.pwPageNumber = String(counter);
1648
+ p.element.dataset.pwPageStyle = folio;
1649
+ const prefix = valueOf(style.page, '--pw-page-prefix');
1650
+ p.element.dataset.pwPagePrefix = prefix === undefined ? '' : unquote(prefix);
1651
+ presentation(p.element, style);
1652
+ return { ...p, style, counter, label };
1653
+ });
1654
+ const targets = new Map();
1655
+ for (const p of numbered)
1656
+ for (const el of p.element.querySelectorAll('[id]'))
1657
+ if (!targets.has(el.id))
1658
+ targets.set(el.id, p.counter);
1659
+ const result = numbered.map((p) => {
1660
+ background(p.element, p.box, p.style);
1661
+ const margins = makeMarginBoxes(p.element, p.box, p.style, marginContext(p.b, p.counter, numbered.length, () => targets), {
1662
+ fonts: opts.fonts, ...(opts.hyphenator ? { hyphenator: opts.hyphenator } : {}),
1663
+ });
1664
+ printerMarks(p.element, p.box);
1665
+ return {
1666
+ element: p.element, number: p.b.number, label: p.label, blank: p.b.blank, built: p.b, lines: p.lines,
1667
+ name: p.context.name, side: p.context.side, counter: p.counter, box: p.box, margins,
1668
+ ...(p.regions ? { regions: p.regions } : {}),
1669
+ };
1670
+ });
1671
+ measuringPage.remove();
1672
+ return { pages: result, warnings: [...warnings, ...styles.warnings] };
1673
+ }
1674
+ /** Parses lowered `--pw-flow-into` (`<name>` or `<name> content|element`). */
1675
+ function flowIntoOf(cs) {
1676
+ const raw = cs.getPropertyValue('--pw-flow-into').trim();
1677
+ if (!raw || raw.toLowerCase() === 'none')
1678
+ return undefined;
1679
+ const parts = raw.split(/\s+/);
1680
+ const name = parts[0];
1681
+ if (!name || name.toLowerCase() === 'none')
1682
+ return undefined;
1683
+ const mode = parts[1]?.toLowerCase() === 'content' ? 'content' : 'element';
1684
+ return { name, mode };
1685
+ }
1686
+ /**
1687
+ * Extracts elements with `flow-into: <name>` out of `root` in document order,
1688
+ * preserving each element's ancestor wrapper chain inside its flow's cloned
1689
+ * root so CSS selectors and inherited properties still match.
1690
+ */
1691
+ function extractNamedFlows(root, pluginFlows) {
1692
+ const flows = new Map();
1693
+ const selectors = pluginFlows
1694
+ ? [...pluginFlows.entries()].filter(([, d]) => d.selector).sort(([a], [b]) => a.localeCompare(b))
1695
+ : [];
1696
+ const flowRoot = (name) => {
1697
+ let r = flows.get(name);
1698
+ if (!r) {
1699
+ r = root.cloneNode(false);
1700
+ r.removeAttribute('id');
1701
+ r.style.marginTop = r.style.marginBottom = r.style.paddingTop = r.style.paddingBottom = '0';
1702
+ flows.set(name, r);
1703
+ }
1704
+ return r;
1705
+ };
1706
+ const wrapAncestors = (target, ancestors) => {
1707
+ let cur = target;
1708
+ for (const a of ancestors) {
1709
+ const clone = a.cloneNode(false);
1710
+ clone.removeAttribute('id');
1711
+ clone.style.marginTop = clone.style.marginBottom = '0';
1712
+ clone.style.paddingTop = clone.style.paddingBottom = '0';
1713
+ clone.style.borderTopWidth = clone.style.borderBottomWidth = '0';
1714
+ cur.append(clone);
1715
+ cur = clone;
1716
+ }
1717
+ return cur;
1718
+ };
1719
+ const matchPluginFlow = (el) => {
1720
+ for (const [name, def] of selectors) {
1721
+ if (def.selector && el.matches(def.selector))
1722
+ return { name, mode: def.mode ?? 'element' };
1723
+ }
1724
+ return undefined;
1725
+ };
1726
+ const walk = (parent, ancestors) => {
1727
+ for (const child of [...parent.children]) {
1728
+ const flow = flowIntoOf(getComputedStyle(child)) ?? matchPluginFlow(child);
1729
+ // Walk descendants first so nested `flow-into` moves out before its ancestor moves.
1730
+ walk(child, [...ancestors, child]);
1731
+ if (!flow)
1732
+ continue;
1733
+ const into = wrapAncestors(flowRoot(flow.name), ancestors);
1734
+ if (flow.mode === 'content') {
1735
+ into.append(...child.childNodes);
1736
+ child.remove();
1737
+ }
1738
+ else {
1739
+ into.append(child);
1740
+ }
1741
+ }
1742
+ };
1743
+ walk(root, []);
1744
+ return flows;
1745
+ }
1746
+ /**
1747
+ * Multi-flow and page-template layout: each flow (the default `main` flow and
1748
+ * every named flow) has its own vertical list measured at its region's width
1749
+ * and its own `PageBuilder` state (inserts, marks, pending breaks). Each page
1750
+ * resolves its `@page` template's `@region`s and steps each region's flow.
1751
+ */
1752
+ function layoutTemplatedPages(root, namedFlows, opts, styles, measuring, lang, plainWidth, vsize, firstPage, sideOf, listOpts) {
1753
+ const warnings = [];
1754
+ const flows = new Map();
1755
+ const customInserts = opts.inserts;
1756
+ const rootEm = Number.parseFloat(getComputedStyle(root).fontSize) || 16;
1757
+ const prepareFlow = (name, flowRoot, attached) => {
1758
+ const region = styles.firstRegionFor(name);
1759
+ const width = region ? region.width : plainWidth;
1760
+ const height = region ? region.height : vsize;
1761
+ let holder;
1762
+ if (attached) {
1763
+ holder = measuring.main;
1764
+ holder.style.width = `${width}px`;
1765
+ }
1766
+ else {
1767
+ holder = document.createElement('div');
1768
+ holder.className = 'pw-main';
1769
+ holder.style.cssText = `position:relative;width:${width}px`;
1770
+ measuring.area.append(holder);
1771
+ holder.append(flowRoot);
1772
+ }
1773
+ warnings.push(...writeFirstLetters(flowRoot));
1774
+ const names = new PageNames(flowRoot, styles.named);
1775
+ const restore = styles.named && !region ? measureNamedPages(flowRoot, names, styles) : () => { };
1776
+ const list = buildVerticalList(flowRoot, listOpts);
1777
+ const params = readFlowParams(flowRoot, height, customInserts);
1778
+ fixTables(flowRoot);
1779
+ restore();
1780
+ const headers = new HeaderRows();
1781
+ const builder = new PageBuilder({
1782
+ vsize: height, maxDepth: params.maxDepth, topSkip: params.topSkip, inserts: params.inserts,
1783
+ unit: SP_PER_PX, firstPage,
1784
+ continuation: (last, next) => headers.repeat(last, next),
1785
+ });
1786
+ const items = expandFlowColumns(contributions(list.items, params.floatSkip, names, customInserts), height);
1787
+ builder.enqueue(items);
1788
+ flows.set(name, { name, root: flowRoot, params, names, builder });
1789
+ };
1790
+ prepareFlow(DEFAULT_FLOW, root, true);
1791
+ for (const [name, flowRoot] of namedFlows)
1792
+ prepareFlow(name, flowRoot, false);
1793
+ const stepped = [];
1794
+ const lastMarks = new Map();
1795
+ const anyActive = () => [...flows.values()].some((f) => f.builder.hasMore());
1796
+ for (let i = 0; anyActive(); i++) {
1797
+ if (i > 10000)
1798
+ throw new Error('the templated page layout never ends');
1799
+ const pageNum = firstPage + i;
1800
+ const side = sideOf(pageNum);
1801
+ // Determine the page's name from the first active flow's next box (preferring `main`).
1802
+ const primary = flows.get(DEFAULT_FLOW)?.builder.hasMore()
1803
+ ? flows.get(DEFAULT_FLOW)
1804
+ : [...flows.values()].find((f) => f.builder.hasMore());
1805
+ const peek = primary?.builder.peekFirstBox();
1806
+ const pageName = primary && peek && peek.type === 'box' && peek.kind !== 'null' ? primary.names.ofBox(peek) : '';
1807
+ const context = { name: pageName, first: i === 0, blank: false, side };
1808
+ const box = styles.box(context);
1809
+ const templateRegions = styles.regions(context);
1810
+ const areaW = Math.max(0, box.width - box.margin.left - box.margin.right);
1811
+ const areaH = Math.max(0, box.height - box.margin.top - box.margin.bottom);
1812
+ const regions = templateRegions.length > 0
1813
+ ? templateRegions
1814
+ : [{ name: DEFAULT_FLOW, flow: DEFAULT_FLOW, left: 0, top: 0, width: areaW, height: areaH, declarations: [] }];
1815
+ // Stop if no region on this page receives any flow that still has content.
1816
+ if (!regions.some((r) => flows.get(r.flow)?.builder.hasMore()))
1817
+ break;
1818
+ // Precompute balanced heights for multi-column `@region` groups whose flow's tail fits on this page.
1819
+ const balancedHeights = new Map();
1820
+ for (let k = 0; k < regions.length; k++) {
1821
+ const r = regions[k];
1822
+ if (!r.column || r.column.index !== 0 || !r.column.balance)
1823
+ continue;
1824
+ const f = flows.get(r.flow);
1825
+ if (!f?.builder.hasMore())
1826
+ continue;
1827
+ const rem = f.builder.peekRemainingItems();
1828
+ if (!rem)
1829
+ continue;
1830
+ const h = balancedColumnHeight(pruneTop(rem, ZERO), r.column.count, r.height);
1831
+ if (h !== undefined)
1832
+ balancedHeights.set(`${r.column.group}\u0000${r.flow}`, Math.min(r.height, h + 1 / 64));
1833
+ }
1834
+ const placed = [];
1835
+ for (const r of regions) {
1836
+ const f = flows.get(r.flow);
1837
+ if (!f?.builder.hasMore())
1838
+ continue;
1839
+ const bal = r.column ? balancedHeights.get(`${r.column.group}\u0000${r.flow}`) : undefined;
1840
+ const slice = f.builder.step(bal ?? r.height, pageNum);
1841
+ if (slice)
1842
+ placed.push({ box: r, flow: f, slice });
1843
+ }
1844
+ if (placed.length === 0)
1845
+ break;
1846
+ const blank = placed.every((p) => p.slice.blank);
1847
+ const merged = mergePageContent(pageNum, blank, areaH, placed.map((p) => p.slice), lastMarks);
1848
+ for (const p of placed)
1849
+ if (!p.slice.blank)
1850
+ warnings.push(...overfullWarnings([{ ...p.slice, number: pageNum }]));
1851
+ stepped.push({
1852
+ number: pageNum,
1853
+ context: { ...context, blank },
1854
+ box,
1855
+ regions: placed,
1856
+ built: merged,
1857
+ templated: templateRegions.length > 0,
1858
+ });
770
1859
  }
1860
+ const resetsOn = collectPageResets(stepped.map((s) => s.built), root);
1861
+ const fragments = new Set();
1862
+ const pages = [];
1863
+ for (const [i, s] of stepped.entries()) {
1864
+ const { page, area, main } = shell(s.box, lang, `${opts.pageClass ?? ''}${s.context.blank ? ' pw-blank' : ''}`.trim());
1865
+ if (s.context.name)
1866
+ page.dataset.pwPageName = s.context.name;
1867
+ if (s.box.offset > 0) {
1868
+ const o = s.box.offset;
1869
+ page.dataset.pwTrimBox = `${o} ${o} ${s.box.width} ${s.box.height}`;
1870
+ page.dataset.pwBleedBox = `${o - s.box.bleed} ${o - s.box.bleed} ${s.box.width + 2 * s.box.bleed} ${s.box.height + 2 * s.box.bleed}`;
1871
+ }
1872
+ opts.container.append(page);
1873
+ const lines = [];
1874
+ if (s.context.blank) {
1875
+ area.remove();
1876
+ pages.push({ b: s.built, element: page, context: s.context, box: s.box, lines, resets: resetsOn[i], ...(s.templated ? { regions: [] } : {}) });
1877
+ continue;
1878
+ }
1879
+ if (!s.templated && s.regions.length === 1) {
1880
+ const only = s.regions[0];
1881
+ placeRegionContent(area, main, only.flow.root, only.slice, only.flow.params.inserts, fragments, lines, customInserts);
1882
+ if (customInserts?.size)
1883
+ placeMarginInserts(page, s.box, s.context.side, only.flow.root, only.slice, customInserts, rootEm, fragments, lines);
1884
+ pages.push({ b: s.built, element: page, context: s.context, box: s.box, lines, resets: resetsOn[i] });
1885
+ continue;
1886
+ }
1887
+ main.remove();
1888
+ const laidRegions = [];
1889
+ for (const p of s.regions) {
1890
+ if (p.slice.blank)
1891
+ continue;
1892
+ const regionEl = document.createElement('div');
1893
+ regionEl.className = p.box.column ? 'pw-region pw-column' : 'pw-region';
1894
+ regionEl.dataset.pwRegion = p.box.name;
1895
+ regionEl.dataset.pwFlow = p.box.flow;
1896
+ regionEl.style.cssText = `position:absolute;left:${p.box.left}px;top:${p.box.top}px;width:${p.box.width}px;height:${p.box.height}px`;
1897
+ for (const d of p.box.declarations)
1898
+ regionEl.style.setProperty(d.prop, d.value);
1899
+ const regionMain = document.createElement('div');
1900
+ regionMain.className = 'pw-main';
1901
+ regionMain.style.cssText = 'position:absolute;left:0;top:0;width:100%';
1902
+ regionEl.append(regionMain);
1903
+ area.append(regionEl);
1904
+ placeRegionContent(regionEl, regionMain, p.flow.root, p.slice, p.flow.params.inserts, fragments, lines, customInserts);
1905
+ if (customInserts?.size)
1906
+ placeMarginInserts(page, s.box, s.context.side, p.flow.root, p.slice, customInserts, rootEm, fragments, lines);
1907
+ laidRegions.push({ name: p.box.name, flow: p.box.flow, box: p.box, element: regionEl, built: p.slice });
1908
+ }
1909
+ pages.push({ b: s.built, element: page, context: s.context, box: s.box, lines, resets: resetsOn[i], regions: laidRegions });
1910
+ }
1911
+ return finishPages(pages, styles, opts, firstPage, warnings, measuring.page);
1912
+ }
1913
+ /** Expands any `ColumnsBox` inside a flow's items against that flow's region height. */
1914
+ function expandFlowColumns(items, regionHeight) {
1915
+ if (!items.some((i) => i.type === 'box' && i.kind === 'columns'))
1916
+ return [...items];
1917
+ const out = [];
1918
+ for (const item of items) {
1919
+ if (item.type === 'box' && item.kind === 'columns')
1920
+ out.push(...columnRows(item, regionHeight, () => regionHeight));
1921
+ else
1922
+ out.push(item);
1923
+ }
1924
+ return out;
1925
+ }
1926
+ /** Merges the slices placed on one templated page into a single `PageContent`, carrying marks across pages even after a flow finishes. */
1927
+ function mergePageContent(number, blank, areaHeight, slices, lastMarks) {
1928
+ const nonBlank = slices.filter((s) => !s.blank);
1929
+ if (nonBlank.length === 1 && lastMarks.size === 0) {
1930
+ const only = nonBlank[0];
1931
+ for (const [name, m] of only.marks)
1932
+ if (m.bot)
1933
+ lastMarks.set(name, m.bot);
1934
+ return { ...only, number };
1935
+ }
1936
+ const items = [];
1937
+ const inserts = {};
1938
+ const ownByName = new Map();
1939
+ for (const s of nonBlank) {
1940
+ items.push(...s.items);
1941
+ for (const [cls, list] of Object.entries(s.inserts)) {
1942
+ ;
1943
+ (inserts[cls] ??= []).push(...list);
1944
+ }
1945
+ for (const [name, m] of s.marks) {
1946
+ if (m.all.length)
1947
+ ownByName.set(name, [...(ownByName.get(name) ?? []), ...m.all]);
1948
+ }
1949
+ }
1950
+ const marks = new Map();
1951
+ const names = new Set([...lastMarks.keys(), ...ownByName.keys()]);
1952
+ for (const name of names) {
1953
+ const top = lastMarks.get(name);
1954
+ const all = ownByName.get(name) ?? [];
1955
+ const first = all[0] ?? top;
1956
+ const bot = all.at(-1) ?? top;
1957
+ if (bot)
1958
+ lastMarks.set(name, bot);
1959
+ marks.set(name, { ...(top ? { top } : {}), ...(first ? { first } : {}), ...(bot ? { bot } : {}), all });
1960
+ }
1961
+ return {
1962
+ number,
1963
+ blank,
1964
+ items,
1965
+ height: nonBlank.length === 1 ? nonBlank[0].height : areaHeight,
1966
+ depth: nonBlank.length === 1 ? nonBlank[0].depth : 0,
1967
+ glue: nonBlank.length === 1 ? nonBlank[0].glue : NATURAL,
1968
+ overfull: Math.max(0, ...nonBlank.map((s) => s.overfull)),
1969
+ badness: Math.max(0, ...nonBlank.map((s) => s.badness)),
1970
+ penalty: nonBlank.at(-1)?.penalty ?? INFINITE_VPENALTY,
1971
+ inserts,
1972
+ marks,
1973
+ };
771
1974
  }
772
1975
  //# sourceMappingURL=pages.js.map