pdf-kalem 0.1.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +33 -5
  3. package/dist/{Page-DqmtN2a2.d.ts → Page-Co_MgZDL.d.ts} +5 -1
  4. package/dist/{PdfDoc-KL5rp6kh.d.ts → PdfDoc-jjqPxRSC.d.ts} +20 -18
  5. package/dist/PdfPageSurface-1DVsuYJ2.d.ts +34 -0
  6. package/dist/{PdfRenderContext-DW6IqQ5q.d.ts → PdfRenderContext-C12DDr-w.d.ts} +20 -4
  7. package/dist/{Table-_ld_cPdR.d.ts → Table-DevmMUtU.d.ts} +1 -1
  8. package/dist/{doc-sizes-B1rAm5Po.d.ts → Widget-DzXseZEZ.d.ts} +68 -54
  9. package/dist/{chunk-4JABW7CO.js → chunk-5ZRRZRCD.js} +129 -359
  10. package/dist/chunk-5ZRRZRCD.js.map +1 -0
  11. package/dist/{chunk-PMF5IICV.js → chunk-6VRKPGB5.js} +75 -15
  12. package/dist/chunk-6VRKPGB5.js.map +1 -0
  13. package/dist/chunk-C4NWXBGN.js +58 -0
  14. package/dist/chunk-C4NWXBGN.js.map +1 -0
  15. package/dist/chunk-CGBZYXXD.js +81 -0
  16. package/dist/chunk-CGBZYXXD.js.map +1 -0
  17. package/dist/chunk-IGVDPDCZ.js +258 -0
  18. package/dist/chunk-IGVDPDCZ.js.map +1 -0
  19. package/dist/{chunk-FMU2QMVG.js → chunk-JU7VYYBJ.js} +10 -5
  20. package/dist/chunk-JU7VYYBJ.js.map +1 -0
  21. package/dist/chunk-LYSHPJ3R.js +107 -0
  22. package/dist/chunk-LYSHPJ3R.js.map +1 -0
  23. package/dist/{chunk-IAF6RHAY.js → chunk-OS4HN6KV.js} +62 -111
  24. package/dist/chunk-OS4HN6KV.js.map +1 -0
  25. package/dist/chunk-PCKIGCEJ.js +198 -0
  26. package/dist/chunk-PCKIGCEJ.js.map +1 -0
  27. package/dist/{chunk-AYT6JHLZ.js → chunk-PIBYCKYY.js} +15 -2
  28. package/dist/chunk-PIBYCKYY.js.map +1 -0
  29. package/dist/{chunk-4RZQEYIL.js → chunk-SEKYHTYU.js} +224 -81
  30. package/dist/chunk-SEKYHTYU.js.map +1 -0
  31. package/dist/doc-output-NLO_E7Qr.d.ts +34 -0
  32. package/dist/doc-sizes-BP4GVKGs.d.ts +14 -0
  33. package/dist/edit.d.ts +10 -3
  34. package/dist/edit.js +21 -5
  35. package/dist/edit.js.map +1 -1
  36. package/dist/forms.d.ts +294 -0
  37. package/dist/forms.js +324 -0
  38. package/dist/forms.js.map +1 -0
  39. package/dist/image-format-Dvz7_MH4.d.ts +8 -0
  40. package/dist/index.d.ts +10 -21
  41. package/dist/index.js +18 -13
  42. package/dist/index.js.map +1 -1
  43. package/dist/internals.d.ts +54 -10
  44. package/dist/internals.js +32 -5
  45. package/dist/markdown.d.ts +11 -13
  46. package/dist/markdown.js +75 -48
  47. package/dist/markdown.js.map +1 -1
  48. package/dist/preview.d.ts +38 -0
  49. package/dist/preview.js +76 -0
  50. package/dist/preview.js.map +1 -0
  51. package/dist/surface-hkLPm11r.d.ts +23 -0
  52. package/dist/{types-CWGD5wJk.d.ts → types-ChQa4dgU.d.ts} +5 -1
  53. package/dist/utils/color-utils.js +1 -1
  54. package/dist/widgets.d.ts +152 -25
  55. package/dist/widgets.js +170 -19
  56. package/dist/widgets.js.map +1 -1
  57. package/package.json +26 -4
  58. package/dist/chunk-4JABW7CO.js.map +0 -1
  59. package/dist/chunk-4RZQEYIL.js.map +0 -1
  60. package/dist/chunk-AYT6JHLZ.js.map +0 -1
  61. package/dist/chunk-B3LBPGQP.js +0 -112
  62. package/dist/chunk-B3LBPGQP.js.map +0 -1
  63. package/dist/chunk-FMU2QMVG.js.map +0 -1
  64. package/dist/chunk-IAF6RHAY.js.map +0 -1
  65. package/dist/chunk-PMF5IICV.js.map +0 -1
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 alaypanov
3
+ Copyright (c) 2026 A Laypanov
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -15,6 +15,7 @@ The design is heavily inspired by [Flutter](https://flutter.dev)'s widget-tree m
15
15
  - Builds page-based layouts with Yoga (flexbox: `Row`, `Column`, `gap`, `flexGrow`, `%` widths, absolute positioning).
16
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 })`.
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-DzXseZEZ.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-DzXseZEZ.js';
2
+ import { P as PdfRenderContext } from './PdfRenderContext-C12DDr-w.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-DzXseZEZ.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-DzXseZEZ.js';
3
+ import { P as PdfPageSurface } from './PdfPageSurface-1DVsuYJ2.js';
4
+ import { P as PdfFormSurface } from './surface-hkLPm11r.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-DzXseZEZ.js';
2
2
 
3
3
  interface TableOptions extends WidgetOptions {
4
4
  head?: TableHeadWidget;
@@ -8,6 +8,10 @@ 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';
11
15
  lineHeight?: number;
12
16
  underline?: boolean;
13
17
  }
@@ -35,6 +39,8 @@ interface Theme {
35
39
  container?: ThemeContainerStyle;
36
40
  }
37
41
  declare function createTheme(theme?: Theme): Theme;
42
+ /** @internal — test isolation for the warn-once state. Exported via internals. */
43
+ declare function resetThemeWarningsForTests(): void;
38
44
  declare function resolveThemeColor(theme: Theme | undefined, value?: ThemeColorValue): ColorValue | undefined;
39
45
  declare function resolveThemeFont(theme: Theme | undefined, font?: string): string | undefined;
40
46
  declare function resolveThemeTextStyle(theme: Theme | undefined, variantNames: string[]): ThemeTextStyle | undefined;
@@ -106,9 +112,10 @@ interface LinkAnnotationArgs {
106
112
  * Backend-neutral render context.
107
113
  *
108
114
  * 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.
115
+ * backend supplies a {@link PdfRenderContext}; this is the polymorphism
116
+ * point that lets the same widget tree render to different output formats —
117
+ * and, load-bearing today, the seam pagination's `PageScope` composes
118
+ * through (ADR 0001).
112
119
  *
113
120
  * The interface is split into three concerns:
114
121
  *
@@ -116,9 +123,13 @@ interface LinkAnnotationArgs {
116
123
  * 2. **Measurement** — font metrics. The signatures are shared, but each
117
124
  * backend implements them against its own font system (pdf-lib's
118
125
  * `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.).
126
+ * 3. **Drawing + geometry** — backend-specific drawing primitives and the
127
+ * layout-box mapping.
128
+ *
129
+ * Page lifecycle (addPage/current-page/adopt) is deliberately NOT here —
130
+ * it is backend mechanics, not something a scope-like adapter must answer.
131
+ * The PDF-typed surface lives in {@link PdfPageSurface} (ADR 0001: PDF
132
+ * features get PDF-typed modules, never interface widening).
122
133
  *
123
134
  * Note: {@link getLayoutBox} returns a box in yoga coordinates (top-left
124
135
  * origin, y grows down). Backends that need a different origin (e.g. PDF,
@@ -150,21 +161,6 @@ interface RenderContext {
150
161
  * it's typed as `RenderImage` for now but will become backend-neutral in v2.
151
162
  */
152
163
  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
164
  getPageHeight(): number;
169
165
  getPageWidth(): number;
170
166
  getDimensions(): [number, number];
@@ -279,15 +275,16 @@ interface Pagination {
279
275
  readonly overflow: boolean;
280
276
  }
281
277
 
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
- }
278
+ /**
279
+ * The Yoga style interpreter — the one shared styling seam between widgets
280
+ * and Yoga (ARCHITECTURE.md #8). Extracted from the `Widget` base class so
281
+ * the base interface stops growing with each style key and the dispatch is
282
+ * testable against a bare node: no widget, no context, no layout tree.
283
+ *
284
+ * `applyYogaStyle` is the only entry: typed dispatch on `YogaStyle` keys.
285
+ * Unknown keys are a compile error at typed call sites (no silent no-ops);
286
+ * undefined/null values are skipped.
287
+ */
291
288
  type YogaStyleValue = number | 'auto' | `${number}%`;
292
289
  /** Dimension value for min/max constraints — Yoga rejects 'auto' there. */
293
290
  type YogaDimensionValue = number | `${number}%`;
@@ -322,6 +319,38 @@ interface YogaStyle {
322
319
  bottom?: number;
323
320
  left?: number;
324
321
  }
322
+ declare function applyYogaStyle(node: Node, style: YogaStyle): void;
323
+
324
+ /**
325
+ * The shared spacing vocabulary (I11): one type for padding and margin
326
+ * everywhere. A `number` applies to all four sides; the object form sets
327
+ * sides individually, with unset sides falling back to the caller's default.
328
+ *
329
+ * Deliberately minimal: no CSS shorthand sugar (`horizontal`/`vertical`) and
330
+ * no margin collapsing — Yoga resolves margins as plain box geometry.
331
+ */
332
+ type Spacing = number | {
333
+ top?: number;
334
+ right?: number;
335
+ bottom?: number;
336
+ left?: number;
337
+ };
338
+
339
+ interface WidgetOptions {
340
+ children?: Widget[];
341
+ /**
342
+ * Keep-together opt-out: never split this widget's box across pages; move
343
+ * it whole to the next page (clip if it is taller than a full page).
344
+ * Default: undefined — breakability is decided by structure.
345
+ */
346
+ breakable?: boolean;
347
+ /**
348
+ * Outer spacing around the widget's box (I11). CSS-like per-side object
349
+ * or a number for all sides. No margin collapsing — Yoga resolves it as
350
+ * plain box geometry, and pagination break offsets already carry it.
351
+ */
352
+ margin?: Spacing;
353
+ }
325
354
  declare abstract class Widget {
326
355
  protected children: Widget[];
327
356
  protected node: Node;
@@ -341,18 +370,11 @@ declare abstract class Widget {
341
370
  */
342
371
  calculateLayout(width?: number, height?: number, direction?: Direction): void;
343
372
  /**
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.
373
+ * The single styling entry — a thin delegation to the Yoga style
374
+ * interpreter (src/lib/yoga-style.ts), which owns the dispatch and the
375
+ * dimension parsing. Subclasses keep this ergonomic protected form.
347
376
  */
348
377
  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
378
  /**
357
379
  * Post-layout computed size (0 before layout). Widgets with meaningful
358
380
  * intrinsics override — Text (measured lines), Table (row sums), and their
@@ -374,6 +396,11 @@ declare abstract class Widget {
374
396
  };
375
397
  getParent(): Widget | undefined;
376
398
  getChildWidgets(): Widget[];
399
+ /**
400
+ * @internal — package-internal: position this widget's node absolutely
401
+ * within its parent (Stack aligns its non-positioned children this way).
402
+ */
403
+ positionAbsolute(): void;
377
404
  /** @internal — package-internal: append a child after construction (edit module overlays). */
378
405
  appendWidgetChild(widget: Widget): void;
379
406
  /** Flow geometry from the last Yoga layout (positions are parent-border-box-relative). */
@@ -412,17 +439,4 @@ declare abstract class Widget {
412
439
  getBreakUnits(): BreakUnit[] | null;
413
440
  }
414
441
 
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 };
442
+ 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 };