pdf-kalem 0.1.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +34 -6
  2. package/dist/{Page-DqmtN2a2.d.ts → Page-CsUKWyUj.d.ts} +5 -1
  3. package/dist/{PdfDoc-KL5rp6kh.d.ts → PdfDoc-BrQ03kn0.d.ts} +20 -18
  4. package/dist/PdfPageSurface-Dzx68rek.d.ts +34 -0
  5. package/dist/{PdfRenderContext-DW6IqQ5q.d.ts → PdfRenderContext-DdmsufQc.d.ts} +20 -4
  6. package/dist/{Table-_ld_cPdR.d.ts → Table-B1JgJINU.d.ts} +1 -1
  7. package/dist/{doc-sizes-B1rAm5Po.d.ts → Widget-D-wA9-fw.d.ts} +71 -54
  8. package/dist/{chunk-PMF5IICV.js → chunk-2P5P7KF5.js} +230 -15
  9. package/dist/chunk-2P5P7KF5.js.map +1 -0
  10. package/dist/{chunk-4JABW7CO.js → chunk-2RBUCDMS.js} +129 -359
  11. package/dist/chunk-2RBUCDMS.js.map +1 -0
  12. package/dist/{chunk-4RZQEYIL.js → chunk-AITTHKEP.js} +243 -119
  13. package/dist/chunk-AITTHKEP.js.map +1 -0
  14. package/dist/chunk-C4NWXBGN.js +58 -0
  15. package/dist/chunk-C4NWXBGN.js.map +1 -0
  16. package/dist/chunk-CGBZYXXD.js +81 -0
  17. package/dist/chunk-CGBZYXXD.js.map +1 -0
  18. package/dist/chunk-CKBKBBHC.js +105 -0
  19. package/dist/chunk-CKBKBBHC.js.map +1 -0
  20. package/dist/{chunk-FMU2QMVG.js → chunk-JU7VYYBJ.js} +10 -5
  21. package/dist/chunk-JU7VYYBJ.js.map +1 -0
  22. package/dist/chunk-MBZC4ZQH.js +457 -0
  23. package/dist/chunk-MBZC4ZQH.js.map +1 -0
  24. package/dist/{chunk-AYT6JHLZ.js → chunk-SBH3Y5H7.js} +27 -15
  25. package/dist/chunk-SBH3Y5H7.js.map +1 -0
  26. package/dist/{chunk-IAF6RHAY.js → chunk-TWNM3K3Y.js} +62 -111
  27. package/dist/chunk-TWNM3K3Y.js.map +1 -0
  28. package/dist/doc-output-NLO_E7Qr.d.ts +34 -0
  29. package/dist/doc-sizes-BP4GVKGs.d.ts +14 -0
  30. package/dist/edit.d.ts +10 -3
  31. package/dist/edit.js +20 -5
  32. package/dist/edit.js.map +1 -1
  33. package/dist/forms.d.ts +294 -0
  34. package/dist/forms.js +322 -0
  35. package/dist/forms.js.map +1 -0
  36. package/dist/image-format-Dvz7_MH4.d.ts +8 -0
  37. package/dist/index.d.ts +10 -21
  38. package/dist/index.js +17 -13
  39. package/dist/index.js.map +1 -1
  40. package/dist/internals.d.ts +62 -10
  41. package/dist/internals.js +32 -5
  42. package/dist/markdown.d.ts +11 -13
  43. package/dist/markdown.js +74 -48
  44. package/dist/markdown.js.map +1 -1
  45. package/dist/preview.d.ts +45 -0
  46. package/dist/preview.js +86 -0
  47. package/dist/preview.js.map +1 -0
  48. package/dist/surface-BJ7MIOTD.d.ts +23 -0
  49. package/dist/{types-CWGD5wJk.d.ts → types-ChQa4dgU.d.ts} +5 -1
  50. package/dist/utils/color-utils.js +1 -1
  51. package/dist/widgets.d.ts +165 -31
  52. package/dist/widgets.js +81 -41
  53. package/dist/widgets.js.map +1 -1
  54. package/package.json +26 -4
  55. package/dist/chunk-4JABW7CO.js.map +0 -1
  56. package/dist/chunk-4RZQEYIL.js.map +0 -1
  57. package/dist/chunk-AYT6JHLZ.js.map +0 -1
  58. package/dist/chunk-B3LBPGQP.js +0 -112
  59. package/dist/chunk-B3LBPGQP.js.map +0 -1
  60. package/dist/chunk-FMU2QMVG.js.map +0 -1
  61. package/dist/chunk-IAF6RHAY.js.map +0 -1
  62. package/dist/chunk-PMF5IICV.js.map +0 -1
package/README.md CHANGED
@@ -13,8 +13,9 @@ The design is heavily inspired by [Flutter](https://flutter.dev)'s widget-tree m
13
13
  ## What It Does
14
14
 
15
15
  - Builds page-based layouts with Yoga (flexbox: `Row`, `Column`, `gap`, `flexGrow`, `%` widths, absolute positioning).
16
- - **Pagination**: content taller than one page automatically flows onto additional pages. Text blocks split by line, table rows stay whole and headers repeat, and each `Page` re-renders its chrome per output page. Opt out per page with `Page({ overflow: false })` or keep a text block together with `Text(..., { breakable: false })`.
16
+ - **Pagination**: content taller than one page automatically flows onto additional pages. Text blocks split by line, table rows stay whole and headers repeat, and each `Page` re-renders its chrome per output page; whitespace-only pages (an overflowing trailing `Spacer`) are dropped. Opt out per page with `Page({ overflow: false })` or keep a text block together with `Text(..., { breakable: false })`.
17
17
  - **Edits existing PDFs** via `pdf-kalem/edit`: load a PDF as Page widgets, overlay widgets on its pages, restructure/merge, save — original content, annotations, and form fields preserved.
18
+ - **Builds fillable forms** via `pdf-kalem/forms`: text fields, checkboxes, dropdowns, radio groups, and buttons as widget-tree nodes — real AcroForm fields in the output, with `formData` data binding (template + data).
18
19
  - Exports PDFs through `pdf-lib` with metadata, custom fonts, link annotations, and SVG paths.
19
20
  - Provides a shared text engine (powered by [`@chenglou/pretext`](https://github.com/chenglou/pretext)) with grapheme-aware wrapping, `maxLines`, and `ellipsis` overflow.
20
21
  - Supports document-scoped themes (color tokens, font aliases, text variants, table/container defaults) with per-widget overrides.
@@ -50,7 +51,8 @@ The [`examples/`](./examples) folder holds self-contained, copyable projects —
50
51
 
51
52
  ```bash
52
53
  pnpm build # examples import the built library
53
- pnpm examples # run every example; each writes its PDF next to its code
54
+ pnpm example # run every example; each writes its PDF next to its code
55
+ # or: pnpm example invoice — just one
54
56
  ```
55
57
 
56
58
  See [`examples/README.md`](./examples/README.md) for what each one demonstrates and how to copy one.
@@ -177,9 +179,9 @@ import { Text, Link } from 'pdf-kalem/widgets';
177
179
  Text(
178
180
  [
179
181
  { text: 'Revenue grew ' },
180
- { text: '12%', bold: true },
182
+ { text: '12%', fontWeight: 700 },
181
183
  { text: ' quarter over quarter' },
182
- { text: ' (audited)', italic: true, color: '#666666' },
184
+ { text: ' (audited)', fontStyle: 'italic', color: '#666666' },
183
185
  ],
184
186
  { size: 12 }
185
187
  );
@@ -193,7 +195,7 @@ Text([{ text: 'Read the ' }, { text: 'full report', href: 'https://example.com'
193
195
  Text([{ text: 'const x = 1', mono: true }]);
194
196
  ```
195
197
 
196
- Run flags: `bold`, `italic`, `strike`, `href`, `mono`, `font`, `color`. Faces resolve through the run's family with the usual fallback chain, so `{ bold: true }` in an `inter` text uses `inter-bold` when loaded and falls back with a warning otherwise. Words that span run boundaries (`he` + `**llo**`) never break internally; wrapping, `maxLines`, and `ellipsis` all work across runs.
198
+ Run fields: `fontWeight`, `fontStyle`, `strike`, `href`, `mono`, `font`, `color`. Weight follows CSS matching — 100–500 renders regular, 600–900 renders bold — and each axis replaces the base style (an explicit `fontWeight: 400` un-bolds a bold base). Faces resolve through the run's family with the usual fallback chain, so `{ fontWeight: 700 }` in an `inter` text uses `inter-bold` when loaded and falls back with a warning otherwise. Words that span run boundaries (`he` + `**llo**`) never break internally; wrapping, `maxLines`, and `ellipsis` all work across runs.
197
199
 
198
200
  ## Fonts
199
201
 
@@ -261,6 +263,32 @@ Styling is theme-driven: headings resolve the `h1`..`h6` text variants, links re
261
263
 
262
264
  A copyable converter project ships in [`examples/markdown/`](./examples/markdown) — a small CLI that turns any markdown file (or an embedded sample) into a paginated PDF.
263
265
 
266
+ ## Forms
267
+
268
+ The `pdf-kalem/forms` subpath adds **real AcroForm fields** to the widget tree — the saved PDF is fillable in any PDF reader:
269
+
270
+ ```ts
271
+ import { TextField, CheckBox, Dropdown, RadioGroup, Radio, Button, Signature } from 'pdf-kalem/forms';
272
+
273
+ Page({
274
+ padding: 48,
275
+ children: [
276
+ TextField('email', { height: 28 }),
277
+ Dropdown('country', { options: ['Germany', 'Kazakhstan'] }),
278
+ RadioGroup('plan', { children: [Radio('basic'), Radio('pro')] }),
279
+ CheckBox('consent'),
280
+ Button('submit', { label: 'Register' }), // visual only — pdf-lib has no action API
281
+ Signature(), // drawn signing line, not a field
282
+ ],
283
+ });
284
+ ```
285
+
286
+ Every field takes a unique `name` (the AcroForm field name), ships a usable default size, and is atomic — on overflow it moves whole to the next page. Labels are plain `Text` widgets you compose yourself.
287
+
288
+ **Data binding**: `new PdfDoc({ children, formData })` applies values by field name, winning over per-widget `value`/`checked` options — the same tree-builder with different `formData` produces filled variants of one template. Type mismatches throw at construction; keys matching no field warn.
289
+
290
+ A copyable form project ships in [`examples/forms/`](./examples/forms) (blank template + filled variant). See the [form widgets guide](https://alaypanov.github.io/pdf-kalem/guide/forms) for the full field set and limitations (field text is Helvetica; buttons carry no actions; `Signature` is a drawn placeholder, not a signature field).
291
+
264
292
  ## Theme
265
293
 
266
294
  You can define document-scoped theme tokens and widget defaults on the document itself.
@@ -324,7 +352,7 @@ The `RenderContext` seam stays because it is load-bearing, not as a backend hook
324
352
  ## Scripts
325
353
 
326
354
  - `pnpm build` builds the npm package into `dist/`.
327
- - `pnpm examples` builds the package and runs every example (each writes its PDF next to its code).
355
+ - `pnpm example` builds the package and runs every example (each writes its PDF next to its code); pass names to run a subset: `pnpm example invoice report`.
328
356
  - `pnpm typecheck` runs TypeScript without emitting files.
329
357
  - `pnpm docs:dev` runs the documentation site.
330
358
 
@@ -1,4 +1,5 @@
1
- import { W as Widget, t as WidgetOptions, e as PageSize, R as RenderContext, s as LayoutBox } from './doc-sizes-B1rAm5Po.js';
1
+ import { W as Widget, a as WidgetOptions, R as RenderContext, s as LayoutBox } from './Widget-D-wA9-fw.js';
2
+ import { a as PageSize } from './doc-sizes-BP4GVKGs.js';
2
3
 
3
4
  interface PageOptions extends WidgetOptions {
4
5
  padding?: number;
@@ -28,6 +29,9 @@ declare class PageWidget extends Widget {
28
29
  * Opens the backend surface this page paints onto. LoadedPage overrides
29
30
  * this to a no-op — its surface is an adopted existing page, opened in
30
31
  * render() before the layout pass.
32
+ *
33
+ * Page lifecycle is PDF mechanics (PdfPageSurface), not part of the
34
+ * neutral RenderContext — pages are where drawing surfaces are created.
31
35
  */
32
36
  protected openPage(context: RenderContext, dimensions: [number, number]): Promise<void>;
33
37
  render(context: RenderContext): Promise<void>;
@@ -1,10 +1,11 @@
1
- import { e as PageSize, T as Theme, W as Widget, t as WidgetOptions } from './doc-sizes-B1rAm5Po.js';
2
- import { P as PdfRenderContext } from './PdfRenderContext-DW6IqQ5q.js';
1
+ import { T as Theme, W as Widget, a as WidgetOptions } from './Widget-D-wA9-fw.js';
2
+ import { P as PdfRenderContext } from './PdfRenderContext-DdmsufQc.js';
3
+ import { a as PageSize } from './doc-sizes-BP4GVKGs.js';
3
4
  import { PDFDocument } from 'pdf-lib';
4
- import { F as FontSet } from './types-CWGD5wJk.js';
5
+ import { F as FontSet } from './types-ChQa4dgU.js';
6
+ import { N as NodeBufferLike } from './doc-output-NLO_E7Qr.js';
5
7
 
6
8
  type Awaitable<T> = T | Promise<T>;
7
- type NodeBufferLike = Uint8Array;
8
9
  interface PdfDocOptions extends WidgetOptions {
9
10
  size?: PageSize;
10
11
  dimensions?: [number, number];
@@ -16,6 +17,15 @@ interface PdfDocOptions extends WidgetOptions {
16
17
  * is never mutated) and resolved doc-scoped during rendering.
17
18
  */
18
19
  fonts?: FontSet;
20
+ /**
21
+ * Data binding: values applied to the tree's form widgets (`pdf-kalem/forms`)
22
+ * by AcroForm field name — the widgets' `name`. Applied in the constructor;
23
+ * wins over per-widget `value`/`checked` options. Type mismatches throw
24
+ * (text wants a string, checkbox a boolean, dropdown/radio a declared
25
+ * option); keys matching no field warn. The same tree-builder with
26
+ * different `formData` produces filled variants of one template.
27
+ */
28
+ formData?: Record<string, string | boolean>;
19
29
  /** Enables drawing colored debug outlines around every widget. */
20
30
  debug?: boolean;
21
31
  meta?: PdfDocMeta;
@@ -47,12 +57,11 @@ interface PdfDocAfterSaveArgs {
47
57
  /**
48
58
  * PdfDoc is the document model: it owns the page tree, theme, metadata, and
49
59
  * lifecycle hooks. It is intentionally not a Widget — a document is not a
50
- * layout node. Rendering is delegated to {@link PdfRenderer}, and runtime
51
- * helpers (blob/download/buffer/file) live on PdfDoc as convenience methods.
60
+ * layout node. Rendering is the save-time walk over the page tree; output
61
+ * mechanics (blob/download/buffer/file) delegate to the runtime adapters in
62
+ * `doc-output.ts`.
52
63
  */
53
64
  declare class PdfDoc {
54
- private static globalBeforeCreate;
55
- private static globalAfterSave;
56
65
  /**
57
66
  * Registers a font from `url`, stores its bytes in {@link FontRegistry},
58
67
  * and loads it into the browser font set (for canvas-based measurement via
@@ -70,9 +79,6 @@ declare class PdfDoc {
70
79
  */
71
80
  static registerFont(fontName: string, fontData: Uint8Array | ArrayBuffer): void;
72
81
  static registerFontkit(fontkit: any): void;
73
- static beforeCreate(hook: (args: PdfDocBeforeCreateArgs) => Awaitable<void>): void;
74
- static afterSave(hook: (args: PdfDocAfterSaveArgs) => Awaitable<void>): void;
75
- static clearHooks(): void;
76
82
  protected size?: PageSize;
77
83
  protected dimensions?: [number, number];
78
84
  protected layout: 'portrait' | 'landscape';
@@ -115,13 +121,9 @@ declare class PdfDoc {
115
121
  getBlob(): Promise<Blob>;
116
122
  download(fileName?: string): Promise<void>;
117
123
  /**
118
- * Opens the browser's print dialog with the generated PDF: the blob is
119
- * loaded into a hidden iframe and the iframe's print is triggered once it
120
- * finishes loading. Browser-only.
121
- *
122
- * Known limitation: Safari's PDF viewer doesn't support programmatic
123
- * printing — the dialog may print blank there. Downloading and printing
124
- * manually is the reliable fallback.
124
+ * Opens the browser's print dialog with the generated PDF. Browser-only.
125
+ * See `printBytes` in `doc-output.ts` for the mechanics and the Safari
126
+ * caveat.
125
127
  */
126
128
  print(): Promise<void>;
127
129
  getBuffer(): Promise<NodeBufferLike>;
@@ -0,0 +1,34 @@
1
+ import { PDFPage, PDFDocument } from 'pdf-lib';
2
+ import { R as RenderContext } from './Widget-D-wA9-fw.js';
3
+
4
+ /**
5
+ * The PDF-specific page-lifecycle surface (ARCHITECTURE #10).
6
+ *
7
+ * ADR 0001's rule is "PDF-specific features get PDF-typed modules, never
8
+ * interface widening" — but `adoptPage` and the page-handle members lived on
9
+ * the "backend-neutral" `RenderContext`, typed `unknown` to hide that they
10
+ * are pdf-lib mechanics. This interface moves them where they belong: the
11
+ * PDF-typed layer.
12
+ *
13
+ * `PdfRenderContext` implements both interfaces (it already had every
14
+ * method); the edit module's `LoadedPage` — the one consumer of adoption —
15
+ * narrows to this surface at render time.
16
+ */
17
+ interface PdfPageSurface {
18
+ /** Adds a page of the given dimensions; returns the pdf-lib page handle. */
19
+ addPage(dimensions: [number, number]): PDFPage;
20
+ getCurrentPage(): PDFPage | null;
21
+ setCurrentPage(page: PDFPage): void;
22
+ /**
23
+ * Adopts a page from a foreign `PDFDocument` as the current drawing
24
+ * surface: the page object is copied into the output document — content
25
+ * streams, annotations, links, and form fields come along — so subsequent
26
+ * drawing lands on top of the original content. Used by the edit module
27
+ * (`pdf-kalem/edit`).
28
+ */
29
+ adoptPage(source: PDFDocument, pageIndex: number): Promise<void>;
30
+ }
31
+ /** Structural check: does this context expose the full PDF page surface (adoption included)? */
32
+ declare function isPdfPageSurface(context: RenderContext): context is RenderContext & PdfPageSurface;
33
+
34
+ export { type PdfPageSurface as P, isPdfPageSurface as i };
@@ -1,6 +1,8 @@
1
- import { PDFDocument, PDFPage, StandardFonts, PDFFont } from 'pdf-lib';
2
- import { R as RenderContext, g as RenderContextOptions, T as Theme, W as Widget, h as RenderImage, b as DrawRectangleArgs, d as DrawTextArgs, a as DrawLineArgs, D as DrawImageArgs, c as DrawSvgPathArgs, L as LinkAnnotationArgs } from './doc-sizes-B1rAm5Po.js';
3
- import { F as FontSet } from './types-CWGD5wJk.js';
1
+ import { PDFDocument, PDFForm, PDFPage, StandardFonts, PDFFont } from 'pdf-lib';
2
+ import { R as RenderContext, h as RenderContextOptions, T as Theme, W as Widget, i as RenderImage, d as DrawRectangleArgs, f as DrawTextArgs, c as DrawLineArgs, D as DrawImageArgs, e as DrawSvgPathArgs, L as LinkAnnotationArgs } from './Widget-D-wA9-fw.js';
3
+ import { P as PdfPageSurface } from './PdfPageSurface-Dzx68rek.js';
4
+ import { P as PdfFormSurface } from './surface-BJ7MIOTD.js';
5
+ import { F as FontSet } from './types-ChQa4dgU.js';
4
6
 
5
7
  /**
6
8
  * PDF backend for {@link RenderContext}. Drives a `pdf-lib` `PDFDocument`:
@@ -12,7 +14,7 @@ import { F as FontSet } from './types-CWGD5wJk.js';
12
14
  * backend-specific nature explicit and frees the `RenderContext` name for
13
15
  * the backend-neutral interface that widgets depend on.
14
16
  */
15
- declare class PdfRenderContext implements RenderContext {
17
+ declare class PdfRenderContext implements RenderContext, PdfPageSurface, PdfFormSurface {
16
18
  private options;
17
19
  private theme?;
18
20
  private doc?;
@@ -23,6 +25,12 @@ declare class PdfRenderContext implements RenderContext {
23
25
  private fontkitRegisteredOnDoc;
24
26
  private fontkitInstance?;
25
27
  private fonts?;
28
+ /** User-space origin of the current page's MediaBox (0,0 for generated pages). */
29
+ private pageOrigin;
30
+ /** Embedded images for the current document, keyed on the bytes identity. */
31
+ private imageCache;
32
+ /** Copiers for adopted foreign documents (reset with the document). */
33
+ private pageCopiers;
26
34
  constructor(options: RenderContextOptions);
27
35
  setDebug(enabled: boolean): void;
28
36
  setTheme(theme?: Theme): void;
@@ -50,6 +58,13 @@ declare class PdfRenderContext implements RenderContext {
50
58
  static registerFontkit(fontkit: any): void;
51
59
  setDocument(doc: PDFDocument): void;
52
60
  getDocument(): PDFDocument;
61
+ /**
62
+ * The document's interactive form (created in the catalog on first use).
63
+ * Form widgets (`src/lib/forms/`) narrow to {@link PdfFormSurface} at render
64
+ * time and create their fields through it — PDF-typed per ADR 0001, never
65
+ * part of the neutral `RenderContext`.
66
+ */
67
+ getForm(): PDFForm;
53
68
  addPage(dimensions: [number, number]): PDFPage;
54
69
  getCurrentPage(): PDFPage | null;
55
70
  setCurrentPage(currentPage: PDFPage): void;
@@ -60,6 +75,7 @@ declare class PdfRenderContext implements RenderContext {
60
75
  * page, so subsequent drawing lands on top of the original content.
61
76
  */
62
77
  adoptPage(source: unknown, pageIndex: number): Promise<void>;
78
+ private copierFor;
63
79
  getPageHeight(): number;
64
80
  getPageWidth(): number;
65
81
  getDimensions(): [number, number];
@@ -1,4 +1,4 @@
1
- import { t as WidgetOptions, W as Widget, i as ThemeColorValue, Y as YogaStyleValue, R as RenderContext, f as RenderColor, B as BreakUnit } from './doc-sizes-B1rAm5Po.js';
1
+ import { a as WidgetOptions, W as Widget, b as ThemeColorValue, Y as YogaStyleValue, R as RenderContext, g as RenderColor, B as BreakUnit } from './Widget-D-wA9-fw.js';
2
2
 
3
3
  interface TableOptions extends WidgetOptions {
4
4
  head?: TableHeadWidget;
@@ -8,7 +8,14 @@ interface ThemeTextStyle {
8
8
  color?: ThemeColorValue;
9
9
  align?: 'left' | 'center' | 'right';
10
10
  font?: string;
11
+ /** CSS-like weight: 100–900, 'normal', or 'bold'. Snaps to the family's two-weight model (100–500 → regular, 600–900 → bold). */
12
+ fontWeight?: number | 'normal' | 'bold';
13
+ /** CSS-like style. 'oblique' is intentionally absent — no synthetic slant yet. */
14
+ fontStyle?: 'normal' | 'italic';
15
+ /** Line height in POINTS (not a CSS multiplier — see TextOptions.lineHeight). */
11
16
  lineHeight?: number;
17
+ /** Line height as a multiplier of the font size (CSS `line-height: 1.4`). Ignored when `lineHeight` is set. */
18
+ lineHeightMultiplier?: number;
12
19
  underline?: boolean;
13
20
  }
14
21
  interface ThemeTableStyle {
@@ -35,6 +42,8 @@ interface Theme {
35
42
  container?: ThemeContainerStyle;
36
43
  }
37
44
  declare function createTheme(theme?: Theme): Theme;
45
+ /** @internal — test isolation for the warn-once state. Exported via internals. */
46
+ declare function resetThemeWarningsForTests(): void;
38
47
  declare function resolveThemeColor(theme: Theme | undefined, value?: ThemeColorValue): ColorValue | undefined;
39
48
  declare function resolveThemeFont(theme: Theme | undefined, font?: string): string | undefined;
40
49
  declare function resolveThemeTextStyle(theme: Theme | undefined, variantNames: string[]): ThemeTextStyle | undefined;
@@ -106,9 +115,10 @@ interface LinkAnnotationArgs {
106
115
  * Backend-neutral render context.
107
116
  *
108
117
  * Widgets depend on this interface, not on any concrete backend. The PDF
109
- * backend supplies a {@link PdfRenderContext}; future backends (image, HTML)
110
- * supply their own implementations. This is the polymorphism point that lets
111
- * the same widget tree render to different output formats.
118
+ * backend supplies a {@link PdfRenderContext}; this is the polymorphism
119
+ * point that lets the same widget tree render to different output formats —
120
+ * and, load-bearing today, the seam pagination's `PageScope` composes
121
+ * through (ADR 0001).
112
122
  *
113
123
  * The interface is split into three concerns:
114
124
  *
@@ -116,9 +126,13 @@ interface LinkAnnotationArgs {
116
126
  * 2. **Measurement** — font metrics. The signatures are shared, but each
117
127
  * backend implements them against its own font system (pdf-lib's
118
128
  * `PDFFont`, canvas `measureText`, etc.).
119
- * 3. **Drawing + page lifecycle** — backend-specific. `addPage` returns
120
- * `unknown` because the page handle type differs per backend (`PDFPage`
121
- * for PDF, `CanvasRenderingContext2D` for image, etc.).
129
+ * 3. **Drawing + geometry** — backend-specific drawing primitives and the
130
+ * layout-box mapping.
131
+ *
132
+ * Page lifecycle (addPage/current-page/adopt) is deliberately NOT here —
133
+ * it is backend mechanics, not something a scope-like adapter must answer.
134
+ * The PDF-typed surface lives in {@link PdfPageSurface} (ADR 0001: PDF
135
+ * features get PDF-typed modules, never interface widening).
122
136
  *
123
137
  * Note: {@link getLayoutBox} returns a box in yoga coordinates (top-left
124
138
  * origin, y grows down). Backends that need a different origin (e.g. PDF,
@@ -150,21 +164,6 @@ interface RenderContext {
150
164
  * it's typed as `RenderImage` for now but will become backend-neutral in v2.
151
165
  */
152
166
  embedImage(bytes: ArrayBuffer, format: 'png' | 'jpeg'): Promise<RenderImage>;
153
- /** Adds a new page/canvas/surface of the given dimensions. Returns the backend's page handle. */
154
- addPage(dimensions: [number, number]): unknown;
155
- /** Returns the current page handle (typed as `unknown` since it's backend-specific). */
156
- getCurrentPage(): unknown;
157
- /** Sets the current page handle. Implementations should accept their own page type. */
158
- setCurrentPage(page: unknown): void;
159
- /**
160
- * Adopts a page from a foreign document of the backend's native type
161
- * (typed `unknown`, like the page handles) as the current drawing surface.
162
- * The PDF backend copies the page object into the output document —
163
- * content streams, annotations, links, and form fields come along — and
164
- * points the current page at the copy, so subsequent drawing lands on top
165
- * of the original content. Used by the edit module (`pdf-kalem/edit`).
166
- */
167
- adoptPage(source: unknown, pageIndex: number): Promise<void>;
168
167
  getPageHeight(): number;
169
168
  getPageWidth(): number;
170
169
  getDimensions(): [number, number];
@@ -279,15 +278,16 @@ interface Pagination {
279
278
  readonly overflow: boolean;
280
279
  }
281
280
 
282
- interface WidgetOptions {
283
- children?: Widget[];
284
- /**
285
- * Keep-together opt-out: never split this widget's box across pages; move
286
- * it whole to the next page (clip if it is taller than a full page).
287
- * Default: undefined — breakability is decided by structure.
288
- */
289
- breakable?: boolean;
290
- }
281
+ /**
282
+ * The Yoga style interpreter — the one shared styling seam between widgets
283
+ * and Yoga (ARCHITECTURE.md #8). Extracted from the `Widget` base class so
284
+ * the base interface stops growing with each style key and the dispatch is
285
+ * testable against a bare node: no widget, no context, no layout tree.
286
+ *
287
+ * `applyYogaStyle` is the only entry: typed dispatch on `YogaStyle` keys.
288
+ * Unknown keys are a compile error at typed call sites (no silent no-ops);
289
+ * undefined/null values are skipped.
290
+ */
291
291
  type YogaStyleValue = number | 'auto' | `${number}%`;
292
292
  /** Dimension value for min/max constraints — Yoga rejects 'auto' there. */
293
293
  type YogaDimensionValue = number | `${number}%`;
@@ -322,6 +322,38 @@ interface YogaStyle {
322
322
  bottom?: number;
323
323
  left?: number;
324
324
  }
325
+ declare function applyYogaStyle(node: Node, style: YogaStyle): void;
326
+
327
+ /**
328
+ * The shared spacing vocabulary (I11): one type for padding and margin
329
+ * everywhere. A `number` applies to all four sides; the object form sets
330
+ * sides individually, with unset sides falling back to the caller's default.
331
+ *
332
+ * Deliberately minimal: no CSS shorthand sugar (`horizontal`/`vertical`) and
333
+ * no margin collapsing — Yoga resolves margins as plain box geometry.
334
+ */
335
+ type Spacing = number | {
336
+ top?: number;
337
+ right?: number;
338
+ bottom?: number;
339
+ left?: number;
340
+ };
341
+
342
+ interface WidgetOptions {
343
+ children?: Widget[];
344
+ /**
345
+ * Keep-together opt-out: never split this widget's box across pages; move
346
+ * it whole to the next page (clip if it is taller than a full page).
347
+ * Default: undefined — breakability is decided by structure.
348
+ */
349
+ breakable?: boolean;
350
+ /**
351
+ * Outer spacing around the widget's box (I11). CSS-like per-side object
352
+ * or a number for all sides. No margin collapsing — Yoga resolves it as
353
+ * plain box geometry, and pagination break offsets already carry it.
354
+ */
355
+ margin?: Spacing;
356
+ }
325
357
  declare abstract class Widget {
326
358
  protected children: Widget[];
327
359
  protected node: Node;
@@ -341,18 +373,11 @@ declare abstract class Widget {
341
373
  */
342
374
  calculateLayout(width?: number, height?: number, direction?: Direction): void;
343
375
  /**
344
- * The single styling entry: typed dispatch on `YogaStyle` keys. Unknown
345
- * keys are a compile error at typed call sites (no silent no-ops);
346
- * undefined/null values are skipped.
376
+ * The single styling entry — a thin delegation to the Yoga style
377
+ * interpreter (src/lib/yoga-style.ts), which owns the dispatch and the
378
+ * dimension parsing. Subclasses keep this ergonomic protected form.
347
379
  */
348
380
  protected setYogaStyle(style: YogaStyle): void;
349
- private applyStyle;
350
- /**
351
- * The one shared dimension parser: `number` | `` `${number}%` `` | 'auto'
352
- * routed to the matching Yoga setter. Percent/auto only apply where the
353
- * caller passed a setter for them.
354
- */
355
- private setDimension;
356
381
  /**
357
382
  * Post-layout computed size (0 before layout). Widgets with meaningful
358
383
  * intrinsics override — Text (measured lines), Table (row sums), and their
@@ -374,6 +399,11 @@ declare abstract class Widget {
374
399
  };
375
400
  getParent(): Widget | undefined;
376
401
  getChildWidgets(): Widget[];
402
+ /**
403
+ * @internal — package-internal: position this widget's node absolutely
404
+ * within its parent (Stack aligns its non-positioned children this way).
405
+ */
406
+ positionAbsolute(): void;
377
407
  /** @internal — package-internal: append a child after construction (edit module overlays). */
378
408
  appendWidgetChild(widget: Widget): void;
379
409
  /** Flow geometry from the last Yoga layout (positions are parent-border-box-relative). */
@@ -412,17 +442,4 @@ declare abstract class Widget {
412
442
  getBreakUnits(): BreakUnit[] | null;
413
443
  }
414
444
 
415
- declare enum PageSize {
416
- A4 = "A4",
417
- A3 = "A3",
418
- A5 = "A5",
419
- LETTER = "LETTER"
420
- }
421
- declare const PDFDocSize: {
422
- A4: number[];
423
- A3: number[];
424
- A5: number[];
425
- LETTER: number[];
426
- };
427
-
428
- export { type BreakUnit as B, type DrawImageArgs as D, type Fragment as F, type LinkAnnotationArgs as L, PDFDocSize as P, type RenderContext as R, type Theme as T, Widget as W, type YogaStyleValue as Y, type DrawLineArgs as a, type DrawRectangleArgs as b, type DrawSvgPathArgs as c, type DrawTextArgs as d, PageSize as e, type RenderColor as f, type RenderContextOptions as g, type RenderImage as h, type ThemeColorValue as i, type ThemeContainerStyle as j, type ThemeTableStyle as k, type ThemeTextStyle as l, createTheme as m, resolveThemeFont as n, resolveThemeTextStyle as o, type Pagination as p, type PagePlan as q, resolveThemeColor as r, type LayoutBox as s, type WidgetOptions as t, type YogaStyle as u };
445
+ export { type BreakUnit as B, type DrawImageArgs as D, type Fragment as F, type LinkAnnotationArgs as L, type Pagination as P, type RenderContext as R, type Spacing as S, type Theme as T, Widget as W, type YogaStyleValue as Y, type WidgetOptions as a, type ThemeColorValue as b, type DrawLineArgs as c, type DrawRectangleArgs as d, type DrawSvgPathArgs as e, type DrawTextArgs as f, type RenderColor as g, type RenderContextOptions as h, type RenderImage as i, type ThemeContainerStyle as j, type ThemeTableStyle as k, type ThemeTextStyle as l, createTheme as m, resolveThemeColor as n, resolveThemeFont as o, resolveThemeTextStyle as p, type PagePlan as q, resetThemeWarningsForTests as r, type LayoutBox as s, applyYogaStyle as t, type YogaStyle as u };