pulpweaver4 0.0.88 → 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 (540) hide show
  1. package/dist/ast/djot.d.ts +2 -1
  2. package/dist/ast/djot.js +31 -2
  3. package/dist/ast/djot.js.map +1 -1
  4. package/dist/ast/index.d.ts +1 -0
  5. package/dist/ast/index.js +1 -0
  6. package/dist/ast/index.js.map +1 -1
  7. package/dist/ast/nodes.d.ts +72 -9
  8. package/dist/ast/nodes.js +8 -0
  9. package/dist/ast/nodes.js.map +1 -1
  10. package/dist/ast/table.d.ts +27 -0
  11. package/dist/ast/table.js +32 -0
  12. package/dist/ast/table.js.map +1 -0
  13. package/dist/browser.js +2420 -0
  14. package/dist/citations/book.d.ts +2 -0
  15. package/dist/citations/book.js +17 -6
  16. package/dist/citations/book.js.map +1 -1
  17. package/dist/citations/collect.d.ts +5 -1
  18. package/dist/citations/collect.js +5 -1
  19. package/dist/citations/collect.js.map +1 -1
  20. package/dist/citations/index.d.ts +1 -1
  21. package/dist/citations/index.js +1 -1
  22. package/dist/citations/index.js.map +1 -1
  23. package/dist/citations/notes.js +54 -11
  24. package/dist/citations/notes.js.map +1 -1
  25. package/dist/citations/positions.js +4 -4
  26. package/dist/citations/positions.js.map +1 -1
  27. package/dist/citations/project.d.ts +12 -2
  28. package/dist/citations/project.js +21 -7
  29. package/dist/citations/project.js.map +1 -1
  30. package/dist/colour/images.d.ts +11 -2
  31. package/dist/colour/images.js +53 -3
  32. package/dist/colour/images.js.map +1 -1
  33. package/dist/colour/ink-limit.d.ts +2 -2
  34. package/dist/colour/ink-limit.js +6 -0
  35. package/dist/colour/ink-limit.js.map +1 -1
  36. package/dist/colour/intents.d.ts +10 -0
  37. package/dist/colour/intents.js +10 -0
  38. package/dist/colour/intents.js.map +1 -1
  39. package/dist/colour/previews.d.ts +8 -4
  40. package/dist/colour/previews.js +11 -8
  41. package/dist/colour/previews.js.map +1 -1
  42. package/dist/config/config.d.ts +99 -6
  43. package/dist/config/config.js +217 -6
  44. package/dist/config/config.js.map +1 -1
  45. package/dist/config/project-schema.d.ts +0 -8
  46. package/dist/config/project-schema.js +221 -12
  47. package/dist/config/project-schema.js.map +1 -1
  48. package/dist/config/schema.js +10 -0
  49. package/dist/config/schema.js.map +1 -1
  50. package/dist/config/secrets.d.ts +11 -0
  51. package/dist/config/secrets.js +19 -0
  52. package/dist/config/secrets.js.map +1 -0
  53. package/dist/csl/processor.d.ts +3 -1
  54. package/dist/csl/processor.js +19 -13
  55. package/dist/csl/processor.js.map +1 -1
  56. package/dist/csl/project.d.ts +19 -4
  57. package/dist/csl/project.js +31 -11
  58. package/dist/csl/project.js.map +1 -1
  59. package/dist/djot/djot.js/src/ast.d.ts +4 -1
  60. package/dist/djot/djot.js/src/ast.js +8 -1
  61. package/dist/djot/djot.js/src/ast.js.map +1 -1
  62. package/dist/djot/djot.js/src/djot-renderer.js +3 -3
  63. package/dist/djot/djot.js/src/djot-renderer.js.map +1 -1
  64. package/dist/djot/djot.js/src/html.js +2 -1
  65. package/dist/djot/djot.js/src/html.js.map +1 -1
  66. package/dist/djot/djot.js/src/inline.d.ts +1 -1
  67. package/dist/djot/djot.js/src/inline.js +25 -12
  68. package/dist/djot/djot.js/src/inline.js.map +1 -1
  69. package/dist/djot/djot.js/src/pandoc.js +81 -11
  70. package/dist/djot/djot.js/src/pandoc.js.map +1 -1
  71. package/dist/djot/djot.js/src/parse.js +12 -3
  72. package/dist/djot/djot.js/src/parse.js.map +1 -1
  73. package/dist/fonts/index.d.ts +1 -1
  74. package/dist/fonts/index.js +1 -1
  75. package/dist/fonts/index.js.map +1 -1
  76. package/dist/fonts/lint.d.ts +51 -0
  77. package/dist/fonts/lint.js +101 -16
  78. package/dist/fonts/lint.js.map +1 -1
  79. package/dist/fonts/walk.d.ts +13 -0
  80. package/dist/fonts/walk.js +50 -33
  81. package/dist/fonts/walk.js.map +1 -1
  82. package/dist/html/css.d.ts +4 -0
  83. package/dist/html/css.js +11 -3
  84. package/dist/html/css.js.map +1 -1
  85. package/dist/html/dom.d.ts +6 -1
  86. package/dist/html/dom.js +28 -6
  87. package/dist/html/dom.js.map +1 -1
  88. package/dist/html/generated.d.ts +17 -0
  89. package/dist/html/generated.js +21 -0
  90. package/dist/html/generated.js.map +1 -0
  91. package/dist/html/images.d.ts +18 -0
  92. package/dist/html/images.js +49 -2
  93. package/dist/html/images.js.map +1 -1
  94. package/dist/html/index.d.ts +1 -0
  95. package/dist/html/index.js +1 -0
  96. package/dist/html/index.js.map +1 -1
  97. package/dist/html/render.d.ts +5 -4
  98. package/dist/html/render.js +34 -9
  99. package/dist/html/render.js.map +1 -1
  100. package/dist/hyphenation/exceptions.d.ts +5 -0
  101. package/dist/hyphenation/exceptions.js +11 -0
  102. package/dist/hyphenation/exceptions.js.map +1 -1
  103. package/dist/hyphenation/index.d.ts +1 -1
  104. package/dist/hyphenation/index.js +1 -1
  105. package/dist/hyphenation/index.js.map +1 -1
  106. package/dist/import/convert.d.ts +21 -0
  107. package/dist/import/convert.js +65 -0
  108. package/dist/import/convert.js.map +1 -0
  109. package/dist/incremental/cache.d.ts +59 -0
  110. package/dist/incremental/cache.js +64 -0
  111. package/dist/incremental/cache.js.map +1 -0
  112. package/dist/incremental/index.d.ts +3 -0
  113. package/dist/incremental/index.js +4 -0
  114. package/dist/incremental/index.js.map +1 -0
  115. package/dist/incremental/keys.d.ts +27 -0
  116. package/dist/incremental/keys.js +89 -0
  117. package/dist/incremental/keys.js.map +1 -0
  118. package/dist/incremental/session.d.ts +180 -0
  119. package/dist/incremental/session.js +401 -0
  120. package/dist/incremental/session.js.map +1 -0
  121. package/dist/index.d.ts +6 -0
  122. package/dist/index.js +6 -0
  123. package/dist/index.js.map +1 -1
  124. package/dist/indexes/layout.d.ts +8 -2
  125. package/dist/indexes/layout.js +6 -4
  126. package/dist/indexes/layout.js.map +1 -1
  127. package/dist/layout/cache.d.ts +174 -0
  128. package/dist/layout/cache.js +150 -0
  129. package/dist/layout/cache.js.map +1 -0
  130. package/dist/layout/converge.d.ts +28 -0
  131. package/dist/layout/converge.js +102 -9
  132. package/dist/layout/converge.js.map +1 -1
  133. package/dist/layout/counters.d.ts +4 -0
  134. package/dist/layout/counters.js +15 -0
  135. package/dist/layout/counters.js.map +1 -1
  136. package/dist/layout/index.d.ts +5 -2
  137. package/dist/layout/index.js +3 -0
  138. package/dist/layout/index.js.map +1 -1
  139. package/dist/layout/lists.d.ts +52 -3
  140. package/dist/layout/lists.js +513 -46
  141. package/dist/layout/lists.js.map +1 -1
  142. package/dist/layout/lookahead.d.ts +151 -0
  143. package/dist/layout/lookahead.js +581 -0
  144. package/dist/layout/lookahead.js.map +1 -0
  145. package/dist/layout/margin-boxes.d.ts +11 -1
  146. package/dist/layout/margin-boxes.js +24 -1
  147. package/dist/layout/margin-boxes.js.map +1 -1
  148. package/dist/layout/page-box.d.ts +2 -0
  149. package/dist/layout/page-box.js +6 -4
  150. package/dist/layout/page-box.js.map +1 -1
  151. package/dist/layout/page-rules.d.ts +8 -1
  152. package/dist/layout/page-rules.js +46 -2
  153. package/dist/layout/page-rules.js.map +1 -1
  154. package/dist/layout/page.js +4 -2
  155. package/dist/layout/page.js.map +1 -1
  156. package/dist/layout/pagebuilder.d.ts +248 -3
  157. package/dist/layout/pagebuilder.js +512 -19
  158. package/dist/layout/pagebuilder.js.map +1 -1
  159. package/dist/layout/pages.d.ts +116 -3
  160. package/dist/layout/pages.js +1396 -162
  161. package/dist/layout/pages.js.map +1 -1
  162. package/dist/layout/paragraph.d.ts +14 -0
  163. package/dist/layout/paragraph.js +304 -31
  164. package/dist/layout/paragraph.js.map +1 -1
  165. package/dist/layout/pre.js +4 -0
  166. package/dist/layout/pre.js.map +1 -1
  167. package/dist/layout/protrusion.d.ts +26 -0
  168. package/dist/layout/protrusion.js +39 -0
  169. package/dist/layout/protrusion.js.map +1 -0
  170. package/dist/layout/ranges.d.ts +2 -0
  171. package/dist/layout/ranges.js +22 -0
  172. package/dist/layout/ranges.js.map +1 -0
  173. package/dist/layout/region.d.ts +2 -1
  174. package/dist/layout/region.js +9 -5
  175. package/dist/layout/region.js.map +1 -1
  176. package/dist/layout/templates.d.ts +71 -0
  177. package/dist/layout/templates.js +290 -0
  178. package/dist/layout/templates.js.map +1 -0
  179. package/dist/layout/vlist.d.ts +3 -3
  180. package/dist/linebreak/items.d.ts +27 -2
  181. package/dist/linebreak/items.js +10 -3
  182. package/dist/linebreak/items.js.map +1 -1
  183. package/dist/linebreak/knuth-plass.d.ts +20 -0
  184. package/dist/linebreak/knuth-plass.js +68 -16
  185. package/dist/linebreak/knuth-plass.js.map +1 -1
  186. package/dist/lint/book.d.ts +13 -0
  187. package/dist/lint/book.js +52 -0
  188. package/dist/lint/book.js.map +1 -0
  189. package/dist/lint/config.d.ts +9 -0
  190. package/dist/lint/config.js +40 -6
  191. package/dist/lint/config.js.map +1 -1
  192. package/dist/lint/linter.js +1 -0
  193. package/dist/lint/linter.js.map +1 -1
  194. package/dist/lint/project.js +1 -1
  195. package/dist/lint/project.js.map +1 -1
  196. package/dist/lint/rules/layout.d.ts +3 -1
  197. package/dist/lint/rules/layout.js +8 -6
  198. package/dist/lint/rules/layout.js.map +1 -1
  199. package/dist/lint/rules/source.d.ts +3 -1
  200. package/dist/lint/rules/source.js +9 -4
  201. package/dist/lint/rules/source.js.map +1 -1
  202. package/dist/lint/testing.js +1 -0
  203. package/dist/lint/testing.js.map +1 -1
  204. package/dist/measure/bidi-data.d.ts +14 -0
  205. package/dist/measure/bidi-data.js +69 -0
  206. package/dist/measure/bidi-data.js.map +1 -0
  207. package/dist/measure/bidi.d.ts +70 -0
  208. package/dist/measure/bidi.js +225 -0
  209. package/dist/measure/bidi.js.map +1 -0
  210. package/dist/measure/css.d.ts +5 -0
  211. package/dist/measure/css.js +2 -0
  212. package/dist/measure/css.js.map +1 -1
  213. package/dist/measure/measurer.d.ts +36 -2
  214. package/dist/measure/measurer.js +220 -22
  215. package/dist/measure/measurer.js.map +1 -1
  216. package/dist/measure/model.d.ts +20 -2
  217. package/dist/measure/model.js +13 -6
  218. package/dist/measure/model.js.map +1 -1
  219. package/dist/measure/script-data.d.ts +6 -0
  220. package/dist/measure/script-data.js +34 -0
  221. package/dist/measure/script-data.js.map +1 -0
  222. package/dist/measure/scripts.d.ts +36 -0
  223. package/dist/measure/scripts.js +293 -0
  224. package/dist/measure/scripts.js.map +1 -0
  225. package/dist/output/output.d.ts +35 -3
  226. package/dist/output/output.js +26 -4
  227. package/dist/output/output.js.map +1 -1
  228. package/dist/paint/backgrounds.js +7 -20
  229. package/dist/paint/backgrounds.js.map +1 -1
  230. package/dist/paint/blend.d.ts +33 -13
  231. package/dist/paint/blend.js +73 -21
  232. package/dist/paint/blend.js.map +1 -1
  233. package/dist/paint/cache.d.ts +80 -0
  234. package/dist/paint/cache.js +537 -0
  235. package/dist/paint/cache.js.map +1 -0
  236. package/dist/paint/canvas.d.ts +4 -13
  237. package/dist/paint/canvas.js +45 -5
  238. package/dist/paint/canvas.js.map +1 -1
  239. package/dist/paint/context.d.ts +2 -0
  240. package/dist/paint/emphasis.js +1 -1
  241. package/dist/paint/emphasis.js.map +1 -1
  242. package/dist/paint/flatten.d.ts +24 -2
  243. package/dist/paint/flatten.js +55 -12
  244. package/dist/paint/flatten.js.map +1 -1
  245. package/dist/paint/forms.d.ts +64 -0
  246. package/dist/paint/forms.js +319 -0
  247. package/dist/paint/forms.js.map +1 -0
  248. package/dist/paint/images.d.ts +4 -1
  249. package/dist/paint/images.js +13 -2
  250. package/dist/paint/images.js.map +1 -1
  251. package/dist/paint/layers.d.ts +64 -0
  252. package/dist/paint/layers.js +137 -0
  253. package/dist/paint/layers.js.map +1 -0
  254. package/dist/paint/painter.d.ts +19 -6
  255. package/dist/paint/painter.js +15 -135
  256. package/dist/paint/painter.js.map +1 -1
  257. package/dist/paint/stacking.d.ts +1 -1
  258. package/dist/paint/stacking.js +9 -2
  259. package/dist/paint/stacking.js.map +1 -1
  260. package/dist/paint/text.d.ts +14 -3
  261. package/dist/paint/text.js +25 -4
  262. package/dist/paint/text.js.map +1 -1
  263. package/dist/paint/vertical.js +2 -2
  264. package/dist/paint/vertical.js.map +1 -1
  265. package/dist/pdf/encoded.d.ts +16 -0
  266. package/dist/pdf/encoded.js +35 -0
  267. package/dist/pdf/encoded.js.map +1 -0
  268. package/dist/pdf/include/colour.d.ts +105 -0
  269. package/dist/pdf/include/colour.js +349 -0
  270. package/dist/pdf/include/colour.js.map +1 -0
  271. package/dist/pdf/include/functions.d.ts +17 -0
  272. package/dist/pdf/include/functions.js +389 -0
  273. package/dist/pdf/include/functions.js.map +1 -0
  274. package/dist/pdf/include/pages.d.ts +14 -0
  275. package/dist/pdf/include/pages.js +27 -0
  276. package/dist/pdf/include/pages.js.map +1 -0
  277. package/dist/pdf/include/pdfjs/LICENSE +177 -0
  278. package/dist/pdf/include/pdfjs/pdf.min.mjs +27 -0
  279. package/dist/pdf/include/pdfjs/pdf.worker.min.mjs +27 -0
  280. package/dist/pdf/include/pdfjs/standard_fonts/FoxitDingbats.pfb +0 -0
  281. package/dist/pdf/include/pdfjs/standard_fonts/FoxitFixed.pfb +0 -0
  282. package/dist/pdf/include/pdfjs/standard_fonts/FoxitFixedBold.pfb +0 -0
  283. package/dist/pdf/include/pdfjs/standard_fonts/FoxitFixedBoldItalic.pfb +0 -0
  284. package/dist/pdf/include/pdfjs/standard_fonts/FoxitFixedItalic.pfb +0 -0
  285. package/dist/pdf/include/pdfjs/standard_fonts/FoxitSerif.pfb +0 -0
  286. package/dist/pdf/include/pdfjs/standard_fonts/FoxitSerifBold.pfb +0 -0
  287. package/dist/pdf/include/pdfjs/standard_fonts/FoxitSerifBoldItalic.pfb +0 -0
  288. package/dist/pdf/include/pdfjs/standard_fonts/FoxitSerifItalic.pfb +0 -0
  289. package/dist/pdf/include/pdfjs/standard_fonts/FoxitSymbol.pfb +0 -0
  290. package/dist/pdf/include/pdfjs/standard_fonts/LICENSE_FOXIT +27 -0
  291. package/dist/pdf/include/pdfjs/standard_fonts/LICENSE_LIBERATION +363 -0
  292. package/dist/pdf/include/pdfjs/standard_fonts/LiberationSans-Bold.ttf +0 -0
  293. package/dist/pdf/include/pdfjs/standard_fonts/LiberationSans-BoldItalic.ttf +0 -0
  294. package/dist/pdf/include/pdfjs/standard_fonts/LiberationSans-Italic.ttf +0 -0
  295. package/dist/pdf/include/pdfjs/standard_fonts/LiberationSans-Regular.ttf +0 -0
  296. package/dist/pdf/include/pdfjs/wasm/LICENSE_JBIG2 +196 -0
  297. package/dist/pdf/include/pdfjs/wasm/LICENSE_OPENJPEG +39 -0
  298. package/dist/pdf/include/pdfjs/wasm/LICENSE_PDFJS_JBIG2 +13 -0
  299. package/dist/pdf/include/pdfjs/wasm/LICENSE_PDFJS_OPENJPEG +22 -0
  300. package/dist/pdf/include/pdfjs/wasm/LICENSE_PDFJS_QCMS +19 -0
  301. package/dist/pdf/include/pdfjs/wasm/LICENSE_QCMS +21 -0
  302. package/dist/pdf/include/pdfjs/wasm/jbig2.wasm +0 -0
  303. package/dist/pdf/include/pdfjs/wasm/openjpeg.wasm +0 -0
  304. package/dist/pdf/include/pdfjs/wasm/qcms_bg.wasm +0 -0
  305. package/dist/pdf/include/pdfjs/wasm/quickjs-eval.wasm +0 -0
  306. package/dist/pdf/include/prepare.d.ts +58 -0
  307. package/dist/pdf/include/prepare.js +266 -0
  308. package/dist/pdf/include/prepare.js.map +1 -0
  309. package/dist/pdf/include/preview.d.ts +38 -0
  310. package/dist/pdf/include/preview.js +101 -0
  311. package/dist/pdf/include/preview.js.map +1 -0
  312. package/dist/pdf/include/rewrite.d.ts +57 -0
  313. package/dist/pdf/include/rewrite.js +803 -0
  314. package/dist/pdf/include/rewrite.js.map +1 -0
  315. package/dist/pdf/include/serialize.d.ts +32 -0
  316. package/dist/pdf/include/serialize.js +158 -0
  317. package/dist/pdf/include/serialize.js.map +1 -0
  318. package/dist/pdf/include/testing.d.ts +26 -0
  319. package/dist/pdf/include/testing.js +50 -0
  320. package/dist/pdf/include/testing.js.map +1 -0
  321. package/dist/pdf/index.d.ts +1 -0
  322. package/dist/pdf/index.js +1 -0
  323. package/dist/pdf/index.js.map +1 -1
  324. package/dist/pdf/structure/annotations.d.ts +33 -0
  325. package/dist/pdf/structure/annotations.js +112 -0
  326. package/dist/pdf/structure/annotations.js.map +1 -0
  327. package/dist/pdf/structure/forms.d.ts +10 -0
  328. package/dist/pdf/structure/forms.js +46 -0
  329. package/dist/pdf/structure/forms.js.map +1 -0
  330. package/dist/pdf/structure/index.d.ts +41 -5
  331. package/dist/pdf/structure/index.js +40 -5
  332. package/dist/pdf/structure/index.js.map +1 -1
  333. package/dist/pdf/structure/links.d.ts +2 -0
  334. package/dist/pdf/structure/links.js +1 -1
  335. package/dist/pdf/structure/links.js.map +1 -1
  336. package/dist/pdf/structure/presentation.d.ts +28 -0
  337. package/dist/pdf/structure/presentation.js +79 -0
  338. package/dist/pdf/structure/presentation.js.map +1 -0
  339. package/dist/pdf/structure/tags.d.ts +34 -2
  340. package/dist/pdf/structure/tags.js +117 -14
  341. package/dist/pdf/structure/tags.js.map +1 -1
  342. package/dist/pdf/types.d.ts +378 -15
  343. package/dist/pdf/wasm/pulpweaver4_pdf.d.ts +44 -2
  344. package/dist/pdf/wasm/pulpweaver4_pdf.js +191 -2
  345. package/dist/pdf/wasm/pulpweaver4_pdf_bg.wasm +0 -0
  346. package/dist/pdf/writer.d.ts +13 -1
  347. package/dist/pdf/writer.js +26 -1
  348. package/dist/pdf/writer.js.map +1 -1
  349. package/dist/plugin/define.d.ts +200 -15
  350. package/dist/plugin/define.js +124 -15
  351. package/dist/plugin/define.js.map +1 -1
  352. package/dist/plugin/failure.d.ts +1 -1
  353. package/dist/plugin/index.d.ts +5 -4
  354. package/dist/plugin/index.js +5 -4
  355. package/dist/plugin/index.js.map +1 -1
  356. package/dist/plugin/reference.d.ts +38 -0
  357. package/dist/plugin/reference.js +287 -0
  358. package/dist/plugin/reference.js.map +1 -0
  359. package/dist/plugin/register.d.ts +39 -7
  360. package/dist/plugin/register.js +83 -2
  361. package/dist/plugin/register.js.map +1 -1
  362. package/dist/preflight/index.d.ts +1 -1
  363. package/dist/preflight/index.js +1 -1
  364. package/dist/preflight/index.js.map +1 -1
  365. package/dist/preflight/pdfx.d.ts +35 -0
  366. package/dist/preflight/pdfx.js +37 -4
  367. package/dist/preflight/pdfx.js.map +1 -1
  368. package/dist/preflight/reader.d.ts +10 -3
  369. package/dist/preflight/reader.js +86 -5
  370. package/dist/preflight/reader.js.map +1 -1
  371. package/dist/print/impose.d.ts +66 -0
  372. package/dist/print/impose.js +331 -0
  373. package/dist/print/impose.js.map +1 -0
  374. package/dist/print/output.js +426 -60
  375. package/dist/print/output.js.map +1 -1
  376. package/dist/problem.js +4 -3
  377. package/dist/problem.js.map +1 -1
  378. package/dist/profile/index.d.ts +1 -0
  379. package/dist/profile/index.js +1 -0
  380. package/dist/profile/index.js.map +1 -1
  381. package/dist/profile/lint.d.ts +1 -1
  382. package/dist/profile/lint.js +29 -1
  383. package/dist/profile/lint.js.map +1 -1
  384. package/dist/profile/list-table.d.ts +51 -0
  385. package/dist/profile/list-table.js +137 -0
  386. package/dist/profile/list-table.js.map +1 -0
  387. package/dist/profile/metadata.js +3 -0
  388. package/dist/profile/metadata.js.map +1 -1
  389. package/dist/profile/profile.d.ts +3 -0
  390. package/dist/profile/profile.js +9 -1
  391. package/dist/profile/profile.js.map +1 -1
  392. package/dist/project.js +3 -0
  393. package/dist/project.js.map +1 -1
  394. package/dist/qpdf/index.d.ts +2 -0
  395. package/dist/qpdf/index.js +3 -0
  396. package/dist/qpdf/index.js.map +1 -0
  397. package/dist/qpdf/qpdf.d.ts +125 -0
  398. package/dist/qpdf/qpdf.js +205 -0
  399. package/dist/qpdf/qpdf.js.map +1 -0
  400. package/dist/qpdf/testing.d.ts +12 -0
  401. package/dist/qpdf/testing.js +9 -0
  402. package/dist/qpdf/testing.js.map +1 -0
  403. package/dist/qpdf/wasm/LICENSE-qpdf +202 -0
  404. package/dist/qpdf/wasm/LICENSE-zlib +22 -0
  405. package/dist/qpdf/wasm/NOTICE-qpdf.md +42 -0
  406. package/dist/qpdf/wasm/qpdf.wasm +0 -0
  407. package/dist/render/index.d.ts +3 -0
  408. package/dist/render/index.js +2 -0
  409. package/dist/render/index.js.map +1 -0
  410. package/dist/render/render.d.ts +98 -0
  411. package/dist/render/render.js +243 -0
  412. package/dist/render/render.js.map +1 -0
  413. package/dist/reproducible/clock.d.ts +4 -5
  414. package/dist/reproducible/clock.js +4 -5
  415. package/dist/reproducible/clock.js.map +1 -1
  416. package/dist/spike/spike-page.chromium.json +4 -4
  417. package/dist/style/colours.d.ts +7 -2
  418. package/dist/style/colours.js +24 -2
  419. package/dist/style/colours.js.map +1 -1
  420. package/dist/style/compile.js +1 -1
  421. package/dist/style/compile.js.map +1 -1
  422. package/dist/style/defaults.d.ts +9 -3
  423. package/dist/style/defaults.js +14 -2
  424. package/dist/style/defaults.js.map +1 -1
  425. package/dist/style/gcpm.d.ts +1 -1
  426. package/dist/style/gcpm.js +17 -5
  427. package/dist/style/gcpm.js.map +1 -1
  428. package/dist/style/properties.js +84 -0
  429. package/dist/style/properties.js.map +1 -1
  430. package/dist/test/book.d.ts +22 -2
  431. package/dist/test/book.js +35 -2
  432. package/dist/test/book.js.map +1 -1
  433. package/dist/test/build.d.ts +23 -0
  434. package/dist/test/build.js +86 -33
  435. package/dist/test/build.js.map +1 -1
  436. package/dist/test/layout.js +132 -22
  437. package/dist/test/layout.js.map +1 -1
  438. package/dist/test/limits.d.ts +8 -0
  439. package/dist/test/limits.js +9 -0
  440. package/dist/test/limits.js.map +1 -0
  441. package/dist/test/pipeline.d.ts +26 -0
  442. package/dist/test/pipeline.js +4 -2
  443. package/dist/test/pipeline.js.map +1 -1
  444. package/dist/test/render.d.ts +26 -3
  445. package/dist/test/render.js +151 -23
  446. package/dist/test/render.js.map +1 -1
  447. package/dist/test/runner.d.ts +6 -3
  448. package/dist/test/runner.js +172 -105
  449. package/dist/test/runner.js.map +1 -1
  450. package/dist/test/text.js +2 -2
  451. package/dist/test/text.js.map +1 -1
  452. package/dist/text/output.js +2 -2
  453. package/dist/text/output.js.map +1 -1
  454. package/dist/text/render.d.ts +4 -3
  455. package/dist/text/render.js +128 -6
  456. package/dist/text/render.js.map +1 -1
  457. package/dist/transform/index.d.ts +1 -1
  458. package/dist/transform/index.js +1 -1
  459. package/dist/transform/index.js.map +1 -1
  460. package/dist/transform/run.d.ts +2 -0
  461. package/dist/transform/run.js +32 -16
  462. package/dist/transform/run.js.map +1 -1
  463. package/dist/web/output.js +116 -10
  464. package/dist/web/output.js.map +1 -1
  465. package/dist/web/runtime/justify.js.txt +2 -2
  466. package/dist/web/site.d.ts +2 -0
  467. package/dist/web/site.js +8 -1
  468. package/dist/web/site.js.map +1 -1
  469. package/docs/README.md +6 -1
  470. package/docs/manual/chapters/front.dj +34 -0
  471. package/docs/manual/chapters/guides/citations.dj +426 -0
  472. package/docs/manual/chapters/guides/colour-and-prepress.dj +261 -0
  473. package/docs/manual/chapters/guides/editions.dj +329 -0
  474. package/docs/manual/chapters/guides/in-a-web-page.dj +143 -0
  475. package/docs/manual/chapters/guides/lines-and-pages.dj +681 -0
  476. package/docs/manual/chapters/guides/lint-rules.dj +355 -0
  477. package/docs/manual/chapters/guides/pdfs.dj +501 -0
  478. package/docs/manual/chapters/guides/plugins.dj +425 -0
  479. package/docs/manual/chapters/guides/testing.dj +264 -0
  480. package/docs/manual/chapters/guides/writing-in-djot.dj +537 -0
  481. package/docs/manual/chapters/start/for-latex-users.dj +256 -0
  482. package/docs/manual/chapters/start/getting-started.dj +167 -0
  483. package/docs/manual/chapters/start/your-first-book.dj +426 -0
  484. package/docs/manual/fonts/CrimsonPro-Italic-VF.ttf +0 -0
  485. package/docs/manual/fonts/CrimsonPro-VF.ttf +0 -0
  486. package/docs/manual/fonts/JetBrainsMono-Regular.otf +0 -0
  487. package/docs/manual/fonts/NotoSansSymbols2-Boxes.ttf +0 -0
  488. package/docs/manual/fonts/OFL.txt +95 -0
  489. package/docs/manual/pulpweaver4.toml +39 -0
  490. package/docs/manual/styles/manual.css +137 -0
  491. package/docs/reference/css-properties/index.md +9 -0
  492. package/docs/reference/css-properties/pw-expansion.md +31 -0
  493. package/docs/reference/css-properties/pw-flow-into.md +31 -0
  494. package/docs/reference/css-properties/pw-knockout.md +26 -0
  495. package/docs/reference/css-properties/pw-layer.md +24 -0
  496. package/docs/reference/css-properties/pw-page-breaking.md +30 -0
  497. package/docs/reference/css-properties/pw-page-duration.md +28 -0
  498. package/docs/reference/css-properties/pw-page-rotate.md +29 -0
  499. package/docs/reference/css-properties/pw-page-transition.md +29 -0
  500. package/docs/reference/css-properties/pw-protrusion.md +31 -0
  501. package/docs/reference/lint-rules/ibid-across-page.md +2 -2
  502. package/docs/reference/lint-rules/unused-entry.md +3 -1
  503. package/docs/reference/plugin-api/capabilities.md +2 -2
  504. package/docs/reference/plugin-api/claim-kind.md +1 -1
  505. package/docs/reference/plugin-api/combine-exceptions.md +19 -0
  506. package/docs/reference/plugin-api/element-break-context.md +34 -0
  507. package/docs/reference/plugin-api/element-break-item.md +24 -0
  508. package/docs/reference/plugin-api/element-breaker.md +24 -0
  509. package/docs/reference/plugin-api/flow-definition.md +30 -0
  510. package/docs/reference/plugin-api/generated-reference.md +32 -0
  511. package/docs/reference/plugin-api/index-definition.md +32 -0
  512. package/docs/reference/plugin-api/index-titles.md +18 -0
  513. package/docs/reference/plugin-api/index.md +27 -3
  514. package/docs/reference/plugin-api/insert-class-definition.md +46 -0
  515. package/docs/reference/plugin-api/insert-placement.md +22 -0
  516. package/docs/reference/plugin-api/insert-placements.md +18 -0
  517. package/docs/reference/plugin-api/layout-definition.md +9 -5
  518. package/docs/reference/plugin-api/layout-slot.md +6 -16
  519. package/docs/reference/plugin-api/lint-context.md +3 -1
  520. package/docs/reference/plugin-api/lint-definition.md +1 -1
  521. package/docs/reference/plugin-api/lint-edition.md +2 -0
  522. package/docs/reference/plugin-api/page-builder-event.md +22 -0
  523. package/docs/reference/plugin-api/page-builder-hook.md +7 -3
  524. package/docs/reference/plugin-api/page-builder-page-event.md +30 -0
  525. package/docs/reference/plugin-api/page-template-definition.md +34 -0
  526. package/docs/reference/plugin-api/page-template-region-definition.md +46 -0
  527. package/docs/reference/plugin-api/plugin-definition.md +5 -1
  528. package/docs/reference/plugin-api/plugin-reference-options.md +32 -0
  529. package/docs/reference/plugin-api/plugin-reference.md +22 -0
  530. package/docs/reference/plugin-api/plugin-registry.md +15 -5
  531. package/docs/reference/plugin-api/plugin-stage.md +1 -1
  532. package/docs/reference/plugin-api/plugin.md +9 -2
  533. package/docs/reference/plugin-api/reference-page.md +34 -0
  534. package/docs/reference/plugin-api/render-reference-page.md +18 -0
  535. package/docs/reference/plugin-api/renderers.md +1 -1
  536. package/docs/reference/pulpweaver4-toml/editions.md +253 -2
  537. package/docs/reference/pulpweaver4-toml/index.md +57 -1
  538. package/docs/reference/pulpweaver4-toml/inks.md +15 -4
  539. package/docs/reference/pulpweaver4-toml/lint.md +1 -1
  540. 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
  }
@@ -54,12 +92,52 @@ class PageStyles {
54
92
  const style = this.style(context);
55
93
  let box = this.boxes.get(style);
56
94
  if (!box) {
57
- const { geometry, bleed, marks } = this.opts;
58
- box = pageBox(style.page, { geometry, ...(bleed !== undefined ? { bleed } : {}), ...(marks ? { marks } : {}) }, this.rootFontSize);
95
+ const { geometry, bleed, marks, fixed = [] } = this.opts;
96
+ const defaults = { geometry, ...(bleed !== undefined ? { bleed } : {}), ...(marks ? { marks } : {}) };
97
+ const kept = (d) => !fixed.includes(d.prop) || style.named.has(d);
98
+ const page = style.page.filter(kept);
99
+ box = pageBox(page, defaults, this.rootFontSize);
100
+ if (page.length < style.page.length)
101
+ this.overridden(style.page.filter((d) => !kept(d)), pageBox(style.page, defaults, this.rootFontSize), box);
59
102
  this.boxes.set(style, box);
60
103
  }
61
104
  return box;
62
105
  }
106
+ /** What the edition's page, bleed and marks overrode, each property once: `page-overridden` where the author's would have made another box. */
107
+ warnings = [];
108
+ warned = new Set();
109
+ overridden(dropped, authored, box) {
110
+ const pt = (px) => `${Number((px * 0.75).toFixed(2))}pt`;
111
+ const marks = (m) => [m.crop && 'crop', m.cross && 'cross'].filter(Boolean).join(' ') || 'none';
112
+ const differs = {
113
+ size: authored.width !== box.width || authored.height !== box.height
114
+ ? [`${pt(box.width)} × ${pt(box.height)}`, `${pt(authored.width)} × ${pt(authored.height)}`] : undefined,
115
+ bleed: authored.bleed !== box.bleed ? [pt(box.bleed), pt(authored.bleed)] : undefined,
116
+ marks: marks(authored.marks) !== marks(box.marks) ? [marks(box.marks), marks(authored.marks)] : undefined,
117
+ };
118
+ for (const prop of ['size', 'bleed', 'marks']) {
119
+ const value = valueOf(dropped, prop);
120
+ const d = differs[prop];
121
+ if (value === undefined || !d || this.warned.has(prop))
122
+ continue;
123
+ this.warned.add(prop);
124
+ const what = prop === 'size' ? 'page' : prop;
125
+ this.warnings.push({
126
+ code: 'page-overridden',
127
+ message: `@page { ${prop}: ${value} } isn't the edition's ${what}, which win${prop === 'marks' ? '' : 's'}: ${d[0]}, not ${d[1]}`,
128
+ elements: [],
129
+ });
130
+ }
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;
63
141
  /** The width of the text area of a right page of the name, not the first: the measure its content is set at. */
64
142
  measure(name) {
65
143
  const b = this.box({ name, first: false, blank: false, side: 'right' });
@@ -126,13 +204,46 @@ export function layoutPages(root, opts) {
126
204
  opts.container.append(measuring.page);
127
205
  measuring.main.append(root);
128
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
+ }
129
234
  // A styled `::first-letter` is a span of its own, which a float can be.
130
- const firstLetters = writeFirstLetters(root);
235
+ const firstLetters = opts.firstLetters === false ? [] : writeFirstLetters(root);
131
236
  const names = new PageNames(root, styles.named);
132
237
  const restore = styles.named ? measureNamedPages(root, names, styles) : () => { };
133
- 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.
134
240
  const list = buildVerticalList(root, {
135
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 } : {}),
136
247
  });
137
248
  const cs = getComputedStyle(root);
138
249
  const em = Number.parseFloat(cs.fontSize) || 16;
@@ -141,8 +252,6 @@ export function layoutPages(root, opts) {
141
252
  const v = cs.getPropertyValue(prop).trim();
142
253
  return v && v !== 'none' ? parseLength(v, em) : fallback;
143
254
  };
144
- const vsizeOf = (box) => box.height - box.margin.top - box.margin.bottom;
145
- const vsize = vsizeOf(plain);
146
255
  const maxDepth = length('--pw-max-depth', 0);
147
256
  const floatSkip = glue('--pw-float-skip', BIGSKIP);
148
257
  const zero = { width: 0, stretch: 0, shrink: 0 };
@@ -155,22 +264,156 @@ export function layoutPages(root, opts) {
155
264
  top: floats,
156
265
  bottom: { ...floats, skip: floatSkip },
157
266
  };
267
+ addCustomInserts(inserts, customInserts, em, vsize, maxDepth, floatSkip, zero);
158
268
  fixTables(root);
159
269
  restore();
160
- const firstPage = opts.firstPage ?? 1;
161
- const sideOf = (n) => (n % 2 === 1 ? 'right' : 'left');
162
270
  const headers = new HeaderRows();
163
- 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 = {
164
284
  vsize, maxDepth, topSkip: glue('--pw-top-skip', '0px'), inserts, unit: SP_PER_PX, firstPage,
165
285
  vsizeOf: (n, first) => vsizeOf(styles.box({
166
286
  name: first?.type === 'box' && first.kind !== 'null' ? names.ofBox(first) : '', first: n === firstPage, blank: false, side: sideOf(n),
167
287
  })),
168
- continuation: (last, next) => headers.repeat(last, next),
169
- });
170
- contribute(builder, contributions(list.items, floatSkip, names));
171
- // The book's end: \vfill\eject, so the last page's text sits at its top.
172
- builder.contribute([{ type: 'glue', width: 0, stretch: 1, shrink: 0, stretchOrder: 2 }, { type: 'penalty', penalty: -10000 }]);
173
- 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);
174
417
  // A box taller than the page is placed alone on one, overfull, and the
175
418
  // page's foot cuts it off: named before it moves. (A page a little over
176
419
  // its goal, as TeX's can be after an insert is split, is no such loss.)
@@ -188,23 +431,30 @@ export function layoutPages(root, opts) {
188
431
  }];
189
432
  })];
190
433
  // Each page's name is its first box's; a blank page takes the next page's.
191
- const pageNames = built.map((b) => {
192
- 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');
193
439
  return first ? names.ofBox(first) : undefined;
194
440
  });
195
441
  for (let i = pageNames.length - 1; i >= 0; i--)
196
442
  pageNames[i] ??= pageNames[i + 1] ?? pageNames[i - 1] ?? '';
197
443
  // Each page's elements that start on it, in order, with any `counter-reset: page` or
198
444
  // `counter-set: page`: read before the pages change the document, so styles are computed once.
199
- 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();
200
447
  const resetsOn = built.map((b, i) => {
448
+ const k = kept(i);
449
+ if (k)
450
+ return k.resets;
201
451
  const out = [];
202
452
  const starts = (el) => {
203
453
  if (started.has(el))
204
454
  return;
205
455
  started.add(el);
206
- const cs = getComputedStyle(el);
207
- 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);
208
458
  if (n !== undefined)
209
459
  out.push(n);
210
460
  };
@@ -220,11 +470,18 @@ export function layoutPages(root, opts) {
220
470
  }
221
471
  return out;
222
472
  });
223
- 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;
224
476
  const pages = [];
225
477
  for (const [i, b] of built.entries()) {
226
478
  const context = { name: pageNames[i], first: i === 0, blank: b.blank, side: sideOf(b.number) };
227
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
+ }
228
485
  const { page, area, main } = shell(box, lang, `${opts.pageClass ?? ''}${b.blank ? ' pw-blank' : ''}`.trim());
229
486
  if (context.name)
230
487
  page.dataset.pwPageName = context.name;
@@ -233,43 +490,23 @@ export function layoutPages(root, opts) {
233
490
  page.dataset.pwTrimBox = `${o} ${o} ${box.width} ${box.height}`;
234
491
  page.dataset.pwBleedBox = `${o - box.bleed} ${o - box.bleed} ${box.width + 2 * box.bleed} ${box.height + 2 * box.bleed}`;
235
492
  }
236
- opts.container.append(page);
493
+ opts.container.insertBefore(page, next?.parentNode === opts.container ? next : null);
237
494
  const lines = [];
238
495
  pages.push({ b, element: page, context, box, lines, resets: resetsOn[i] });
239
496
  if (b.blank) {
240
497
  area.remove();
241
498
  continue;
242
499
  }
243
- main.style.height = `${b.height}px`;
244
- new Region(main, root, fragments, lines).build(b.items, b.glue);
245
- const placed = (cls) => (b.inserts[cls] ?? []).filter((x) => x.list.some((i) => i.type === 'box'));
246
- const top = placed('top');
247
- const bottom = placed('bottom');
248
- const notes = placed('footnote');
249
- let topHeight = 0;
250
- if (top.length) {
251
- const region = floatRegion(area, 'pw-top-floats');
252
- region.style.top = '0';
253
- new Region(region, root, fragments, lines).build(top.flatMap((x) => x.list), NATURAL);
254
- topHeight = natural(top.flatMap((x) => x.list));
255
- main.style.top = `${topHeight}px`;
256
- }
257
- let bottomOffset = 0;
258
- if (notes.length) {
259
- const region = floatRegion(area, 'pw-footnotes');
260
- region.style.bottom = '0';
261
- const rule = document.createElement('div');
262
- rule.className = 'pw-footnote-rule';
263
- rule.style.cssText = 'position:absolute;left:0;bottom:100%';
264
- region.append(rule);
265
- new Region(region, root, fragments, lines).build(notes.flatMap((x) => x.list), NATURAL);
266
- bottomOffset = natural(notes.flatMap((x) => x.list)) + inserts.footnote.skip.width;
267
- }
268
- if (bottom.length) {
269
- const region = floatRegion(area, 'pw-bottom-floats');
270
- region.style.bottom = `${bottomOffset}px`;
271
- new Region(region, root, fragments, lines).build(bottom.flatMap((x) => x.list), NATURAL);
272
- }
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();
273
510
  }
274
511
  // Page numbers, now that every page is made, then what shows them. A
275
512
  // page without a folio is numbered in the style its page would have off
@@ -291,32 +528,432 @@ export function layoutPages(root, opts) {
291
528
  const folio = (p.b.blank && i > 0 ? folios[i].own : folios[i].folio) ?? lastStyle;
292
529
  lastStyle = folio;
293
530
  const label = opts.label?.(p.b.number) ?? formatCounter(counter, folio);
294
- p.element.dataset.pwPageNumber = String(counter);
295
- p.element.dataset.pwPageStyle = folio;
296
531
  // Every page says its prefix, empty where its rules give none, so one
297
532
  // set for some pages doesn't run on into the next (#92).
298
533
  const prefix = valueOf(style.page, '--pw-page-prefix');
299
- p.element.dataset.pwPagePrefix = prefix === undefined ? '' : unquote(prefix);
300
- return { ...p, style, counter, label };
534
+ return { ...p, style, counter, label, folio, prefix: prefix === undefined ? '' : unquote(prefix) };
301
535
  });
302
- const targets = new Map();
303
- for (const p of numbered)
304
- for (const el of p.element.querySelectorAll('[id]'))
305
- if (!targets.has(el.id))
306
- 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
+ };
307
550
  const result = numbered.map((p) => {
308
- background(p.element, p.box, p.style);
309
- const margins = makeMarginBoxes(p.element, p.box, p.style, marginContext(p.b, p.counter, numbered.length, targets), {
310
- 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 } : {}),
311
596
  });
312
- printerMarks(p.element, p.box);
313
- return {
314
- 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,
315
601
  name: p.context.name, side: p.context.side, counter: p.counter, box: p.box, margins,
316
602
  };
603
+ reads.set(laid, read);
604
+ opts.cache?.revise(element);
605
+ return laid;
317
606
  });
318
607
  measuring.page.remove();
319
- return { pages: result, warnings };
608
+ if (opts.cache)
609
+ opts.cache.pages = keepLayout(result, numbered, reads, signatures ?? [], builder, restart, stop, last, search);
610
+ return { pages: result, warnings: [...warnings, ...styles.warnings] };
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
+ });
320
957
  }
321
958
  /**
322
959
  * Lays each element whose page name gives another measure out at that
@@ -371,9 +1008,24 @@ function marginContext(b, counter, total, targets) {
371
1008
  return m?.kind === 'string' ? m.text : '';
372
1009
  },
373
1010
  element: (name, policy) => pick(name, policy, 'running')?.element,
374
- target: (id, name) => (name === 'page' ? targets.get(id) : undefined),
1011
+ target: (id, name) => (name === 'page' ? targets().get(id) : undefined),
375
1012
  };
376
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
+ }
377
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. */
378
1030
  function pageCounterReset(style, elements) {
379
1031
  const own = (prop) => {
@@ -389,17 +1041,6 @@ function pageCounterIncrement(style) {
389
1041
  const v = valueOf(style.page, 'counter-increment');
390
1042
  return (v === undefined ? undefined : counterValue(v, 'page', 1)) ?? 1;
391
1043
  }
392
- /** A counter's value in a `counter-reset`-like list (`page 3 chapter`); `fallback` when it has none. */
393
- function counterValue(value, name, fallback = 0) {
394
- const ws = value.trim().split(/\s+/);
395
- for (let i = 0; i < ws.length; i++) {
396
- if (ws[i] !== name)
397
- continue;
398
- const n = ws[i + 1] !== undefined && /^[-+]?\d+$/.test(ws[i + 1]) ? Number.parseInt(ws[i + 1], 10) : fallback;
399
- return n;
400
- }
401
- return undefined;
402
- }
403
1044
  /** The style a page's margin boxes write its number in, if any of them does. */
404
1045
  function folioStyle(style) {
405
1046
  for (const decls of style.margins.values()) {
@@ -414,6 +1055,10 @@ function unquote(s) {
414
1055
  return m ? m[2].replace(/\\(.)/g, '$1') : s.trim();
415
1056
  }
416
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
+ }
417
1062
  function background(page, box, style) {
418
1063
  const decls = style.page.filter((d) => d.prop.startsWith('background'));
419
1064
  if (!decls.length)
@@ -431,7 +1076,7 @@ function background(page, box, style) {
431
1076
  page.prepend(el);
432
1077
  }
433
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. */
434
- 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 };
435
1080
  /**
436
1081
  * CSS's `marks`: crop marks at the trim's corners, outside the bleed, and
437
1082
  * cross marks (registration targets) at the middle of each side, in the
@@ -525,7 +1170,7 @@ function floatRegion(area, cls) {
525
1170
  * `\vspace*` keeps it: an empty box before it, held to it by `\nobreak`;
526
1171
  * so is space that is only stretch, `--pw-space-before: 0pt plus 1fil`.
527
1172
  */
528
- function contributions(items, floatSkip, names) {
1173
+ function contributions(items, floatSkip, names, customInserts) {
529
1174
  const out = [];
530
1175
  let kept = true;
531
1176
  let name;
@@ -554,52 +1199,71 @@ function contributions(items, floatSkip, names) {
554
1199
  continue;
555
1200
  }
556
1201
  const list = [{ type: 'penalty', penalty: 100 }, ...item.list];
557
- if (item.class === 'top')
1202
+ const customRegion = customInserts?.get(item.class)?.region;
1203
+ if (item.class === 'top' || customRegion === 'top')
558
1204
  list.push({ type: 'penalty', penalty: 10000 }, { type: 'glue', ...floatSkip });
559
1205
  out.push({ ...item, list, height: natural(list) });
560
1206
  }
561
1207
  return out;
562
1208
  }
563
1209
  /**
564
- * Gives the page builder the list, breaking each multi-column box into rows
565
- * of columns as it comes, as LaTeX's `multicols` does: the first row fills
566
- * what is left of its page (`builder.room()`), each next row a page, and
567
- * the last is balanced, its columns as short as holds what is left. Each
568
- * column is broken from the list as TeX's `\vsplit` breaks it
569
- * (`vertBreak`), its last line's depth inside it. When the page has too
570
- * little room left for what must stay with the columns (a heading before
571
- * them, held to them by a +10000 penalty) and two lines of them, the page
572
- * is broken before that, as `multicols` breaks it when less than
573
- * `\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.
574
1214
  */
575
- function contribute(builder, items) {
576
- let from = 0;
577
- 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];
578
1223
  if (item.type !== 'box' || item.kind !== 'columns')
579
1224
  continue;
580
- const k = lastBreakpoint(items, from, i);
581
- 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);
582
1232
  const kept = items.slice(k, i);
583
- if (builder.room() < natural(kept) + opening(item.list))
584
- builder.contribute([{ type: 'penalty', penalty: EJECT_PENALTY }]);
585
- builder.contribute(kept);
586
- 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);
587
1238
  from = i + 1;
588
1239
  }
589
- 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;
590
1251
  }
591
1252
  /** Where the page could last break before `end`: a penalty under 10000, or glue after a box. `from` if nowhere. */
592
1253
  function lastBreakpoint(items, from, end) {
593
- for (let k = end - 1; k > from; k--) {
594
- const p = items[k];
595
- if (p.type === 'penalty' && p.penalty < INFINITE_VPENALTY)
596
- return k;
597
- const before = items[k - 1];
598
- 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))
599
1256
  return k;
600
- }
601
1257
  return from;
602
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
+ }
603
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. */
604
1268
  function opening(list) {
605
1269
  const start = pruneTop(list, ZERO);
@@ -620,27 +1284,6 @@ const EPSILON = 1e-6;
620
1284
  */
621
1285
  function columnRows(box, room, vsizeAfter) {
622
1286
  const out = [];
623
- const sp = (t, s) => badness(Math.round(t * SP_PER_PX), Math.round(s * SP_PER_PX));
624
- /** The list broken into `box.count` columns of height `h`, and what is left. */
625
- const split = (list, h) => {
626
- const columns = [];
627
- let rest = list;
628
- for (let c = 0; c < box.count; c++) {
629
- if (!rest.some((p) => p.type === 'box')) {
630
- columns.push([]);
631
- continue;
632
- }
633
- const at = vertBreak(rest, h, 0, sp).at;
634
- columns.push(at === undefined ? [...rest] : rest.slice(0, at));
635
- rest = at === undefined ? [] : pruneTop(rest.slice(at), ZERO);
636
- }
637
- return { columns, rest };
638
- };
639
- /** Whether the list goes in one row `h` high, no column overfull. */
640
- const fits = (list, h) => {
641
- const { columns, rest } = split(list, h);
642
- return !rest.some((p) => p.type === 'box') && columns.every((c) => natural(c) <= h + EPSILON);
643
- };
644
1287
  const row = (columns, h, set) => ({
645
1288
  ...box, height: Math.max(0, h - EPSILON), depth: 0,
646
1289
  columns: columns.map((items) => ({ items: items, glue: set ? vpack(items, h, 0).glue : NATURAL })),
@@ -651,25 +1294,13 @@ function columnRows(box, room, vsizeAfter) {
651
1294
  for (let guard = 0; rest.some((p) => p.type === 'box'); guard++) {
652
1295
  if (guard > 10000)
653
1296
  throw new Error('a multi-column box never ends: its columns take nothing');
654
- if (fits(rest, h)) {
655
- // The last row: the shortest height that holds the rest.
656
- let lo = natural(rest) / box.count;
657
- let hi = h;
658
- if (fits(rest, lo))
659
- hi = lo;
660
- else
661
- for (let n = 0; n < 30 && hi - lo > 1 / 64; n++) {
662
- const mid = (lo + hi) / 2;
663
- if (fits(rest, mid))
664
- hi = mid;
665
- else
666
- lo = mid;
667
- }
668
- 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);
669
1300
  out.push(row(columns, Math.max(...columns.map((c) => natural(c))), false));
670
1301
  break;
671
1302
  }
672
- const { columns, rest: left } = split(rest, h);
1303
+ const { columns, rest: left } = splitColumns(rest, box.count, h);
673
1304
  if (h < vsizeAfter(ahead) && columns.some((c) => natural(c) > h)) {
674
1305
  // Not even a line fits what is left of the page: the columns start on the next.
675
1306
  out.push({ type: 'penalty', penalty: EJECT_PENALTY });
@@ -692,9 +1323,11 @@ function fixTables(root) {
692
1323
  const rows = [...table.rows];
693
1324
  if (!rows.length)
694
1325
  continue;
695
- const row = rows.reduce((a, r) => (r.cells.length > a.cells.length ? r : a));
696
- const widths = [...row.cells].flatMap((c) => Array.from({ length: c.colSpan }, () => c.getBoundingClientRect().width / c.colSpan));
1326
+ const widths = columnWidths(rows);
697
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();
698
1331
  const group = document.createElement('colgroup');
699
1332
  group.className = 'pw-columns';
700
1333
  for (const w of widths) {
@@ -707,18 +1340,76 @@ function fixTables(root) {
707
1340
  table.style.width = `${width}px`;
708
1341
  }
709
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
+ }
710
1372
  /** A table's header rows, repeated at the top of each page it continues on. */
711
1373
  class HeaderRows {
712
1374
  rows = new Map();
713
1375
  repeat(last, next) {
714
1376
  if (last?.type !== 'box' || last.kind !== 'row' || next.type !== 'box' || next.kind !== 'row' || next.header)
715
1377
  return [];
716
- const t = next.containers.indexOf([...next.containers].reverse().find((c) => c instanceof HTMLTableElement));
717
- const table = next.containers[t];
718
- if (!table?.tHead || !last.containers.includes(table))
1378
+ const table = this.tableOf(next);
1379
+ if (!table || !last.containers.includes(table))
719
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) {
720
1410
  let rows = this.rows.get(table);
721
1411
  if (!rows) {
1412
+ const t = next.containers.indexOf(table);
722
1413
  const containers = [...next.containers.slice(0, t + 1), table.tHead];
723
1414
  rows = [...table.tHead.rows].map((row) => {
724
1415
  const r = row.getBoundingClientRect();
@@ -726,16 +1417,559 @@ class HeaderRows {
726
1417
  });
727
1418
  this.rows.set(table, rows);
728
1419
  }
729
- // 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) => {
730
1514
  const out = [];
731
- for (const { row, box } of rows) {
732
- const clone = row.cloneNode(true);
733
- for (const el of [clone, ...clone.querySelectorAll('[id]')])
734
- el.removeAttribute('id');
735
- clone.dataset.pwRepeated = '';
736
- 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);
737
1533
  }
738
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
+ });
739
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
+ };
740
1974
  }
741
1975
  //# sourceMappingURL=pages.js.map