@bendyline/squisq 2.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/{Doc-ylqWKDc_.d.ts → Doc-DynJleo-.d.ts} +159 -2
  2. package/dist/{ImageEditDoc-D828IXJ1.d.ts → ImageEditDoc-Ca4Tr9uN.d.ts} +1 -1
  3. package/dist/{chunk-PXLVXTLW.js → chunk-ILWDXLUK.js} +24 -6
  4. package/dist/chunk-ILWDXLUK.js.map +1 -0
  5. package/dist/{chunk-W4O2TX5I.js → chunk-JHZWYRSW.js} +569 -1
  6. package/dist/chunk-JHZWYRSW.js.map +1 -0
  7. package/dist/{chunk-X6DUONGT.js → chunk-JI77MGAK.js} +123 -10
  8. package/dist/chunk-JI77MGAK.js.map +1 -0
  9. package/dist/{chunk-TFJVXUHH.js → chunk-OTKVFVL6.js} +1403 -41
  10. package/dist/chunk-OTKVFVL6.js.map +1 -0
  11. package/dist/{chunk-MMPBOUK7.js → chunk-QUUPYOSP.js} +8 -2
  12. package/dist/chunk-QUUPYOSP.js.map +1 -0
  13. package/dist/chunk-VWCJ2WXC.js +215 -0
  14. package/dist/chunk-VWCJ2WXC.js.map +1 -0
  15. package/dist/{chunk-2PWOO4ZE.js → chunk-VYFRI7R6.js} +2 -2
  16. package/dist/{chunk-CY2R2VPR.js → chunk-XNLB57UD.js} +2 -2
  17. package/dist/doc/index.d.ts +144 -5
  18. package/dist/doc/index.js +24 -4
  19. package/dist/generate/index.d.ts +1 -1
  20. package/dist/imageEdit/index.d.ts +3 -3
  21. package/dist/index.d.ts +6 -5
  22. package/dist/index.js +66 -8
  23. package/dist/jsonForm/index.d.ts +1 -1
  24. package/dist/jsonForm/index.js +4 -4
  25. package/dist/materializePageSection-DDzubQXo.d.ts +223 -0
  26. package/dist/narration/index.d.ts +1 -1
  27. package/dist/narration/index.js +3 -3
  28. package/dist/schemas/index.d.ts +30 -5
  29. package/dist/schemas/index.js +41 -3
  30. package/dist/{themeLibrary-RjVgLpUi.d.ts → themeLibrary-B72m0W1y.d.ts} +1 -1
  31. package/dist/transform/index.d.ts +8 -9
  32. package/dist/transform/index.js +1 -1
  33. package/package.json +1 -1
  34. package/src/__tests__/materializeBlockLayers.test.ts +32 -0
  35. package/src/__tests__/materializePageSections.test.ts +404 -0
  36. package/src/__tests__/pageStyle.test.ts +258 -0
  37. package/src/__tests__/templateAnnotationParse.test.ts +13 -0
  38. package/src/doc/index.ts +34 -0
  39. package/src/doc/materializeBlockLayers.ts +170 -9
  40. package/src/doc/page/PageSection.ts +174 -0
  41. package/src/doc/page/materializePageSection.ts +616 -0
  42. package/src/doc/page/resolvePageBlock.ts +108 -0
  43. package/src/doc/page/sectionExtractors.ts +466 -0
  44. package/src/doc/pageCss.ts +628 -0
  45. package/src/doc/templateInputs.ts +1 -0
  46. package/src/schemas/Doc.ts +22 -1
  47. package/src/schemas/PageStyle.ts +213 -0
  48. package/src/schemas/Theme.ts +7 -0
  49. package/src/schemas/index.ts +2 -0
  50. package/src/schemas/pageStyleDefaults.ts +204 -0
  51. package/src/schemas/themeCompile.ts +7 -0
  52. package/src/schemas/themeValidator.ts +183 -0
  53. package/src/schemas/themes/bold.json +29 -0
  54. package/src/schemas/themes/cinematic.json +32 -0
  55. package/src/schemas/themes/documentary.json +29 -0
  56. package/src/schemas/themes/gezellig.json +30 -0
  57. package/src/schemas/themes/magazine.json +37 -0
  58. package/src/schemas/themes/minimalist.json +29 -0
  59. package/src/schemas/themes/morning-light.json +32 -0
  60. package/src/schemas/themes/standard-dark.json +24 -0
  61. package/src/schemas/themes/standard.json +24 -0
  62. package/src/schemas/themes/tech-dark.json +42 -0
  63. package/src/schemas/themes/warm-earth.json +24 -0
  64. package/src/transform/registry.ts +19 -0
  65. package/src/transform/styles/dataDriven.ts +1 -0
  66. package/src/transform/styles/documentary.ts +1 -0
  67. package/src/transform/styles/magazine.ts +1 -0
  68. package/src/transform/styles/minimal.ts +1 -0
  69. package/src/transform/styles/narrative.ts +1 -0
  70. package/src/transform/types.ts +7 -0
  71. package/dist/chunk-FVJUUTEM.js +0 -74
  72. package/dist/chunk-FVJUUTEM.js.map +0 -1
  73. package/dist/chunk-MMPBOUK7.js.map +0 -1
  74. package/dist/chunk-PXLVXTLW.js.map +0 -1
  75. package/dist/chunk-TFJVXUHH.js.map +0 -1
  76. package/dist/chunk-W4O2TX5I.js.map +0 -1
  77. package/dist/chunk-X6DUONGT.js.map +0 -1
  78. /package/dist/{chunk-2PWOO4ZE.js.map → chunk-VYFRI7R6.js.map} +0 -0
  79. /package/dist/{chunk-CY2R2VPR.js.map → chunk-XNLB57UD.js.map} +0 -0
@@ -1,3 +1,6 @@
1
+ import {
2
+ defaultPageStyle
3
+ } from "./chunk-VWCJ2WXC.js";
1
4
  import {
2
5
  THEME_SCHEMA_VERSION,
3
6
  assertTheme,
@@ -9,7 +12,7 @@ import {
9
12
  oklchSetChroma,
10
13
  pickContrastingText,
11
14
  relativeLuminance
12
- } from "./chunk-W4O2TX5I.js";
15
+ } from "./chunk-JHZWYRSW.js";
13
16
 
14
17
  // src/schemas/Doc.ts
15
18
  function calculateDuration(audio) {
@@ -150,6 +153,9 @@ function compileTheme(partial, opts = {}) {
150
153
  contrast: opts.contrast
151
154
  });
152
155
  }
156
+ if (!merged.pageStyle) {
157
+ merged.pageStyle = defaultPageStyle(merged);
158
+ }
153
159
  return assertTheme(merged, `compiled theme "${merged.id}"`);
154
160
  }
155
161
  function parseTheme(json) {
@@ -178,4 +184,4 @@ export {
178
184
  parseTheme,
179
185
  serializeTheme
180
186
  };
181
- //# sourceMappingURL=chunk-MMPBOUK7.js.map
187
+ //# sourceMappingURL=chunk-QUUPYOSP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schemas/Doc.ts","../src/schemas/themeCompile.ts"],"sourcesContent":["/**\n * Doc Schema\n *\n * Defines the JSON format for AI-scriptable visual docs that accompany\n * audio narration. A Doc describes a sequence of animated blocks\n * with text overlays, images, and transitions synchronized to audio.\n *\n * The format is designed to be:\n * 1. AI-generatable - Claude can create scripts from article content\n * 2. Browser-renderable - SVG + CSS animations (ES2015 compatible)\n * 3. Video-exportable - Frame-by-frame capture via Playwright\n *\n * Timing: Blocks are timed to match narration audio segments. Each article\n * has 3-6 MP3 files (intro + sections), and blocks are grouped by segment.\n */\n\nimport type { Transition } from './Transitions.js';\nexport type { Transition, TransitionType, TransitionDirection } from './Transitions.js';\n\n// ============================================\n// Core Types\n// ============================================\n\n/**\n * A directed connection from one block to another.\n *\n * Populated from a heading's Pandoc-style `{connectsTo=…}` attribute\n * (e.g. `## Step 1 {#step1 connectsTo=foo:flow,bar}`). Each item is\n * `target` or `target:type`. Used by diagram-style layouts that draw\n * edges between blocks.\n */\nexport interface BlockConnection {\n /** Target block id (matches another block's `id`). */\n target: string;\n /** Optional connection type/label (e.g., \"flow\", \"requires\"). */\n type?: string;\n}\n\n/**\n * Configuration for the Start/resting block shown before playback begins.\n */\nexport interface StartBlockConfig {\n /** Hero image path (relative to article media). When omitted, a theme-driven background is used. */\n heroSrc?: string;\n /** Alt text for the hero image */\n heroAlt?: string;\n /** Title to display over the hero */\n title: string;\n /** Optional subtitle */\n subtitle?: string;\n /** Ambient motion for the hero image */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n /** Photo credit / artist name for the hero image */\n heroCredit?: string;\n /** License identifier for the hero image */\n heroLicense?: string;\n}\n\n/**\n * A structural problem detected while converting or validating a document.\n *\n * Diagnostics ride on `Doc.diagnostics` so any consumer — the editor, the\n * CLI `validate` command, or an agent re-parsing its own output — gets the\n * same feedback without watching the console. Conversion never throws for\n * content problems; it degrades gracefully and records a diagnostic.\n */\nexport interface DocDiagnostic {\n /** `error` = the author's intent could not be honored (e.g. unparseable\n * data fence); `warning` = something looks wrong but rendering proceeds\n * with a fallback (e.g. unknown template name); `info` = nothing is\n * broken, but the author may want to know (e.g. a redundant annotation). */\n severity: 'error' | 'warning' | 'info';\n /** Stable machine-readable code (e.g. `unknown-template`, `duplicate-id`,\n * `unresolved-connection`, `data-fence-parse`, `missing-asset`). */\n code: string;\n /** Human-readable description, including a suggestion when one exists. */\n message: string;\n /** Id of the block the problem belongs to, when attributable. */\n blockId?: string;\n /** 1-based line number in the markdown source, when known. */\n line?: number;\n}\n\n/**\n * A complete visual doc for an article.\n */\nexport interface Doc {\n /** Article ID this doc belongs to */\n articleId: string;\n\n /** Total duration in seconds (sum of all audio segments) */\n duration: number;\n\n /** Ordered list of blocks */\n blocks: Block[];\n\n /** Audio track configuration */\n audio: AudioTrack;\n\n /** Caption track for closed captions (generated by postprocess-doc) */\n captions?: CaptionTrack;\n\n /**\n * Start/resting block shown before playback begins.\n * Displays hero image with title - acts as a \"poster\" for the doc.\n * The player shows this until the user starts playback.\n */\n startBlock?: StartBlockConfig;\n\n /**\n * Persistent layers rendered on every block (behind and/or on top of content).\n * Used for consistent branding overlays, background gradients, etc.\n */\n persistentLayers?: import('./BlockTemplates.js').PersistentLayerConfig;\n\n /**\n * Optional theme identifier. Resolved at render time via `resolveTheme()`.\n * When omitted, the renderer uses the default theme ('documentary').\n */\n themeId?: string;\n\n /** Optional metadata */\n meta?: {\n generatedAt?: string;\n generatedBy?: string;\n version?: number;\n };\n\n /**\n * YAML frontmatter from the source markdown.\n * Carries rendering hints like `document-render-as` and custom metadata.\n */\n frontmatter?: Record<string, unknown>;\n\n /**\n * User-defined block templates inlined into this doc.\n *\n * Populated from the markdown frontmatter key\n * `squisq-custom-templates`. The template-expansion pipeline\n * (`expandDocBlocks` in `doc/templates/index.ts`) merges these into\n * the registry before walking blocks, so a heading annotated\n * `{[myhero]}` resolves against a doc-defined template named `myhero`.\n *\n * Library templates (stored in localStorage on the editor side) are\n * NOT auto-loaded here — applying a library template to a block\n * copies its definition into this list so the doc remains\n * self-sufficient for SSR and export.\n */\n customTemplates?: import('./CustomTemplates.js').CustomTemplateDefinition[];\n\n /**\n * User-defined themes inlined into this doc.\n *\n * The theme analog of {@link Doc.customTemplates}. Populated from the\n * markdown frontmatter key `squisq-custom-themes`. Exactly one is active\n * at a time — selected by id via `squisq-theme` / {@link Doc.themeId},\n * the doc-level counterpart of a block's `{[name]}` template annotation —\n * but the payload is a list so a doc can carry a small catalog and stay\n * self-sufficient for SSR / export. `resolveThemeForDoc(doc, id)` resolves\n * against this list first (pure, doc-scoped) before built-ins, mirroring\n * how `buildRegistry` resolves custom templates.\n */\n customThemes?: import('./Theme.js').Theme[];\n\n /**\n * Structural problems found while building this doc (unknown templates,\n * unparseable data fences, duplicate ids, unresolved connections, …).\n * Populated by `markdownToDoc()`; extended by `validateMarkdownDoc()`.\n * Absent when the document is clean.\n */\n diagnostics?: DocDiagnostic[];\n\n /**\n * Document-spanning timed media (e.g. a full-length narration MP3/MP4),\n * authored as a media annotation in the preamble (before the first\n * heading) with `anchor=document`. Each clip is timed from the document\n * start and may play across every block. See `resolveMediaSchedule`.\n */\n documentMedia?: import('./Media.js').MediaClip[];\n}\n\n/**\n * A single block in the doc.\n *\n * Blocks can be flat (audio-synced timeline) or nested (markdown-driven hierarchy).\n * When derived from markdown, a block corresponds to a heading section:\n * - `sourceHeading` references the original MarkdownHeading node\n * - `contents` holds the body markdown between this heading and the next\n * - `children` holds sub-heading blocks (e.g., H2s under an H1)\n *\n * Four adjacent fields carry template information — do not confuse them:\n * - `template` — the *resolved* template id this block renders with.\n * - `templateOverrides` — raw `{[…]}` inline params (always strings).\n * - `templateData` — structured inputs from a data fence / GFM table\n * (parsed types, not strings).\n * - `sourceAnnotation.template` — the raw *requested* template name for a\n * standalone-annotation block (before alias resolution).\n * Merge order at render time: template defaults → `templateData` →\n * `templateOverrides`.\n */\nexport interface Block {\n /** Unique identifier for this block.\n * Defaults to a slug derived from the heading text. May be overridden by\n * a Pandoc-style `{#custom-id}` attribute on the heading. */\n id: string;\n\n /** When this block appears (seconds from start).\n * Overridden by a heading attribute `startTime=…` when present. */\n startTime: number;\n\n /** How long this block is visible (seconds).\n * Overridden by a heading attribute `duration=…` when present. */\n duration: number;\n\n /** Which audio segment this block belongs to (0-indexed) */\n audioSegment: number;\n\n /**\n * Transform provenance: the source block id this block was derived\n * from (see `BaseTemplateBlock.sourceBlockId`). Present on blocks a\n * transform produced; lets a persisted transformed Doc keep its typed\n * link back to the source content.\n */\n sourceBlockId?: string;\n /** All source block ids when this block summarizes several. */\n sourceBlockIds?: string[];\n /** Char offset of the extraction inside the source block's plain text. */\n sourceCharOffset?: number;\n\n /**\n * Pre-computed visual layers, rendered back-to-front.\n *\n * Optional — template-derived blocks typically omit this and compute\n * layers on demand via `materializeBlockLayers()` from `@bendyline/squisq/doc`.\n * Raw blocks (e.g., hand-crafted by AI) may provide layers directly.\n */\n layers?: Layer[];\n\n /** Entry transition from previous block */\n transition?: Transition;\n\n /** Resolved template id this block renders with (see the quartet note above). */\n template?: string;\n\n /**\n * True when `template` was chosen by content-aware auto-picking\n * (`markdownToDoc`'s `autoTemplates`) rather than authored. Ephemeral:\n * `docToMarkdown` does not materialize auto-picked templates as heading\n * annotations, keeping the markdown round-trip lossless.\n */\n autoTemplate?: boolean;\n\n /**\n * True when this block was produced from a *standalone* `{[templateName …]}`\n * annotation paragraph in another block's body (rather than from a heading).\n * Such blocks have no `sourceHeading`; `docToMarkdown` re-emits their\n * annotation as a synthesized paragraph before their `contents` so the\n * markdown round-trips. See `annotationBlocks.ts`.\n *\n * Presence-marker: only ever `true` (never `false`). Test with\n * `block.standaloneAnnotation` presence, not as a boolean toggle.\n */\n standaloneAnnotation?: true;\n\n /**\n * The annotation a standalone block was built from — the raw (un-resolved)\n * template name and its params, in author order. Round-tripped by\n * `docToMarkdown` (via `serializeAnnotation`) and read by validation as the\n * raw requested template name (symmetric with\n * `sourceHeading.templateAnnotation`). Present only when\n * `standaloneAnnotation` is true.\n */\n sourceAnnotation?: { template?: string; params?: Record<string, string> };\n\n /**\n * Display title for template rendering.\n * Extracted from the sourceHeading when the block is created by markdownToDoc().\n * Templates like sectionHeader and titleBlock read this for their title layer.\n */\n title?: string;\n\n // ── Markdown-driven hierarchy (optional) ──\n\n /**\n * Nested sub-blocks (heading hierarchy).\n * When a doc is derived from markdown, sub-headings within this\n * heading's section become child blocks. For example, H2 blocks\n * under an H1 block appear here.\n */\n children?: Block[];\n\n /**\n * Markdown body content for this block's section.\n * Contains the block-level markdown nodes (paragraphs, lists, code,\n * blockquotes, etc.) that appear between this heading and the next\n * heading or sub-heading. Empty for pure structural blocks.\n */\n contents?: import('../markdown/types.js').MarkdownBlockNode[];\n\n /**\n * Reference to the MarkdownHeading node that created this block.\n * Present when the block was derived from markdown via markdownToDoc().\n * Enables round-tripping back to markdown and provides heading depth.\n * Absent for the preamble block (content before the first heading).\n */\n sourceHeading?: import('../markdown/types.js').MarkdownHeading;\n\n /**\n * Template overrides extracted from a heading's `{[templateName key=value]}`\n * annotation. Only carries template-specific params (e.g. `colorScheme=blue`).\n * Block-level metadata lives in `x` / `y` / `connectsTo` / `metadata` and is\n * sourced from the Pandoc-style `{#id .class key=value}` attribute block instead.\n */\n templateOverrides?: Record<string, string>;\n\n /**\n * Structured template inputs sourced from the block's body content:\n * a ```json data / ```yaml data fence under the heading, or — for the\n * `dataTable` template — the first GFM table in the section. Unlike\n * `templateOverrides` (always strings), values here keep their parsed\n * types (arrays, numbers, nested objects). Merge order at render time:\n * template defaults → `templateData` → `templateOverrides`.\n */\n templateData?: Record<string, unknown>;\n\n // ── Block-level metadata from Pandoc-style `{#id .class key=value}` ──\n\n /**\n * X coordinate for diagram-style positioning (in author-defined units).\n * Sourced from a heading attribute `x=…`.\n */\n x?: number;\n\n /**\n * Y coordinate for diagram-style positioning (in author-defined units).\n * Sourced from a heading attribute `y=…`.\n */\n y?: number;\n\n /**\n * Outgoing connections to other blocks, by id. Sourced from a heading\n * attribute `connectsTo=target1,target2:type,target3`.\n */\n connectsTo?: BlockConnection[];\n\n /**\n * CSS-style class tokens from a heading's Pandoc attribute (e.g. `{.important .v2}`).\n * Parsed and stored; downstream consumers may use them for styling or filtering.\n */\n classes?: string[];\n\n /**\n * Free-form metadata for heading attribute keys outside the typed registry\n * (anything that isn't `x` / `y` / `connectsTo` / `startTime` / `duration`).\n * Values are raw strings exactly as authored.\n */\n metadata?: Record<string, string>;\n\n /**\n * Timed media clips attached to this block, authored as body-level\n * `{[audio …]}` / `{[video …]}` annotations. Each clip is timed relative\n * to this block's `startTime` (via `startAt`) and optionally spills past\n * the block's end. See `MediaClip` / `resolveMediaSchedule`.\n */\n media?: import('./Media.js').MediaClip[];\n}\n\n// ============================================\n// Layer Types\n// ============================================\n\n/**\n * A visual element within a block.\n * Layers are composited back-to-front (first layer is background).\n */\nexport type Layer =\n | ImageLayer\n | TextLayer\n | ShapeLayer\n | PathLayer\n | MapLayer\n | VideoLayer\n | TableLayer\n | TreeLayer\n | MermaidLayer;\n\ninterface BaseLayer {\n /** Unique identifier for this layer */\n id: string;\n\n /** Position and size */\n position: Position;\n\n /** Animation to apply */\n animation?: Animation;\n}\n\n/**\n * Photographic treatment applied to an image layer — a theme-level \"grade\"\n * so the same photo looks native in every theme. Rendered as CSS filter\n * functions, which behave identically in the browser player and headless\n * frame capture (video/still export).\n */\nexport interface ImageTreatment {\n /**\n * mono: desaturate toward archival black & white.\n * duotone: single-hue tint (hue taken from `color`).\n * warm / cool: gentle temperature grade.\n */\n type: 'none' | 'mono' | 'duotone' | 'warm' | 'cool';\n /** Blend strength 0..1. Default 0.6. */\n strength?: number;\n /** Duotone tint color (themes default this to their primary). */\n color?: string;\n}\n\n/**\n * Image layer - displays an image with optional Ken Burns effect.\n */\nexport interface ImageLayer extends BaseLayer {\n type: 'image';\n content: {\n /** Path to image file (relative to article media dir) */\n src: string;\n /** Alt text for accessibility */\n alt: string;\n /** How to fit image in bounds */\n fit?: 'cover' | 'contain' | 'fill';\n /** Photo credit / artist name */\n credit?: string;\n /** License identifier (e.g., 'CC BY-SA 4.0') */\n license?: string;\n /** Theme-derived photographic grade (see ImageTreatment). */\n treatment?: ImageTreatment;\n /** Gaussian blur radius in px (background/atmosphere imagery). */\n blur?: number;\n };\n}\n\n/**\n * Text layer - displays text with styling.\n */\nexport interface TextLayer extends BaseLayer {\n type: 'text';\n content: {\n /**\n * Plain text (supports \\n for line breaks). Source of truth for plain\n * consumers — PDF/markdown export, search, accessibility — and the SVG\n * `<text>` fallback. When `html` is set, this is its plain-text\n * projection and must be kept in sync.\n */\n text: string;\n /**\n * Optional sanitized **inline** HTML for rich formatting (bold/italic/\n * links, and — for layout textboxes — headings/lists). When present the\n * renderer draws it via `<foreignObject>` instead of SVG `<text>`. Treated\n * as untrusted and re-sanitized at render time. See `RichTextLayer` in\n * `@bendyline/squisq-react`.\n */\n html?: string;\n /** Text styling */\n style: TextStyle;\n };\n}\n\n/**\n * A two-stop linear gradient fill, shared by shape/path fills and text\n * backgrounds. When present it overrides the solid `fill` color.\n *\n * `angle` is in degrees: 0 = top→bottom, 90 = left→right, increasing\n * clockwise. Defaults to 0. Rendered as an SVG `<linearGradient>` in\n * objectBoundingBox units so it scales with the layer's box.\n */\nexport interface LinearGradient {\n from: string;\n to: string;\n angle?: number;\n}\n\n/** Border line style, mapped to an SVG stroke-dasharray by the renderer. */\nexport type BorderStyle = 'solid' | 'dashed' | 'dotted';\n\n/**\n * Shape layer - simple geometric shapes for visual accents.\n */\n/**\n * Repeating SVG pattern fill for a shape (dots, grid, diagonal lines).\n * Rendered as a native `<pattern>` def — fully vector and export-safe.\n */\nexport interface ShapePattern {\n kind: 'dots' | 'grid' | 'diagonal';\n /** Pattern ink color. */\n color: string;\n /** Tile size in px (default 24). */\n size?: number;\n /** Pattern opacity 0–1 (default 1; tint via a translucent color or this). */\n opacity?: number;\n}\n\n/**\n * Procedural filter applied to a shape. `noise` renders static film grain\n * via SVG feTurbulence — deliberately not animated so frame capture and\n * the live player agree.\n */\nexport interface ShapeFilter {\n type: 'noise';\n /** feTurbulence base frequency (default 0.8 — fine grain). */\n baseFrequency?: number;\n /** Grain opacity 0–1 (default 0.05). */\n opacity?: number;\n}\n\nexport interface ShapeLayer extends BaseLayer {\n type: 'shape';\n content: {\n /** Shape type */\n shape: 'rect' | 'circle' | 'line';\n /** Fill color (CSS color or 'none') */\n fill?: string;\n /** Fill opacity 0–1 (applies to solid and gradient fills). */\n fillOpacity?: number;\n /** Gradient fill; overrides `fill` when set. */\n gradient?: LinearGradient;\n /** Repeating pattern fill; overrides `fill`/`gradient` when set. */\n pattern?: ShapePattern;\n /** Procedural filter (film grain). */\n filter?: ShapeFilter;\n /** Stroke color */\n stroke?: string;\n /** Stroke width in pixels */\n strokeWidth?: number;\n /** Border line style (solid/dashed/dotted). Default solid. */\n borderStyle?: BorderStyle;\n /** Corner radius for rect */\n borderRadius?: number;\n };\n}\n\n/**\n * End-of-line marker style for a path/connector endpoint.\n * `arrow` is a filled triangle (the classic arrowhead); `open` is a stroked\n * V; `diamond`/`circle`/`square` are filled glyphs; `none` draws nothing.\n */\nexport type MarkerStyle = 'none' | 'arrow' | 'open' | 'diamond' | 'circle' | 'square';\n\n/**\n * Path layer - renders an SVG `<path>` for arbitrary curves, connectors,\n * arrows, or filled regions. Used by the diagram template for edges\n * between nodes, the drawing template for non-rect/circle/line shapes, and\n * available to any template that needs a custom geometry.\n *\n * The `position` field carries the layer's bounding box (so animations\n * and clipping work the same as for other layers), but the actual\n * geometry is encoded in the `d` attribute using absolute SVG path\n * coordinates relative to the block viewport.\n */\nexport interface PathLayer extends BaseLayer {\n type: 'path';\n content: {\n /** SVG path `d` attribute (e.g. \"M 10 10 L 90 90\"). Absolute viewBox coords. */\n d: string;\n /**\n * Named shape kind (e.g. `'diamond'`, `'star'`, `'arrow-right'`) for\n * path layers that represent one of Squisq's standard shapes. When\n * set, the renderer re-derives `d` from the layer's `position` box\n * (resolved against the viewport) instead of using the stored `d` —\n * so the shape moves, resizes, and adapts to any aspect ratio like\n * the native rect/circle/line layers do. Plain paths (connectors,\n * freehand) leave this unset and keep their absolute `d`.\n */\n shapeKind?: string;\n /** Stroke color (default: theme text color). */\n stroke?: string;\n /** Stroke width in pixels (default: 2). */\n strokeWidth?: number;\n /** Optional fill color (default: 'none' — pure connectors). */\n fill?: string;\n /** Fill opacity 0–1 (applies to solid and gradient fills). */\n fillOpacity?: number;\n /** Gradient fill; overrides `fill` when set. */\n gradient?: LinearGradient;\n /**\n * Border line style (solid/dashed/dotted). A convenience over\n * `dasharray` for named shapes; when set the renderer derives the\n * dash pattern from it (scaled by stroke width).\n */\n borderStyle?: BorderStyle;\n /** Optional stroke dash pattern (SVG `stroke-dasharray` syntax). */\n dasharray?: string;\n /** Marker at the path start. */\n startMarker?: MarkerStyle;\n /** Marker at the path end. */\n endMarker?: MarkerStyle;\n };\n}\n\n/**\n * Map layer - displays a geographic map with optional markers.\n *\n * Maps are rendered as composite tile images from free tile providers.\n * Supported styles use open-source/free tiles requiring attribution.\n */\nexport interface MapLayer extends BaseLayer {\n type: 'map';\n content: {\n /** Center coordinates for the map */\n center: {\n lat: number;\n lng: number;\n };\n /** Zoom level (0-18, typically 8-14 for doc blocks) */\n zoom: number;\n /** Map tile style */\n style: MapTileStyle;\n /** Optional markers to display on the map */\n markers?: MapMarker[];\n /** Pre-rendered static image path (for video export reliability) */\n staticSrc?: string;\n /** Show attribution text (default: true) */\n showAttribution?: boolean;\n };\n}\n\n/**\n * Video layer - displays a short video clip, always muted (narration provides audio).\n *\n * Rendered via an HTML5 <video> element inside <foreignObject>, similar to how\n * ImageLayer uses <img> for Ken Burns effects. clipStart/clipEnd define the window\n * within the source video to play. During Playwright frame capture (seekTo mode),\n * the video is seeked programmatically rather than playing in real time.\n */\nexport interface VideoLayer extends BaseLayer {\n type: 'video';\n content: {\n /** Path to video file (relative to article media dir) */\n src: string;\n /** Path to poster frame (shown before video loads / during seek) */\n posterSrc?: string;\n /** Alt text for accessibility */\n alt: string;\n /** How to fit video in bounds */\n fit?: 'cover' | 'contain' | 'fill';\n /** Start time within the source video (seconds) */\n clipStart: number;\n /** End time within the source video (seconds) */\n clipEnd: number;\n /** Total source video duration (for validation) */\n sourceDuration?: number;\n /**\n * Seconds into the owning block before this video begins playing\n * (the block-relative `startAt`). Default 0 — plays from block start.\n */\n startAt?: number;\n /**\n * When true, the video keeps playing past the block's end (the\n * playback scheduler re-homes it to the player level). Default false.\n */\n spillover?: boolean;\n /** Video credit / artist name */\n credit?: string;\n /** License identifier (e.g., 'CC BY-SA 4.0') */\n license?: string;\n };\n}\n\n/**\n * Table layer - renders a data table with themed styling.\n * Uses foreignObject inside SVG for HTML-based table layout.\n */\nexport interface TableLayer extends BaseLayer {\n type: 'table';\n content: {\n /** Header cell values */\n headers: string[];\n /** Data rows (array of cell value arrays) */\n rows: string[][];\n /** Per-column alignment */\n align?: (('left' | 'right' | 'center') | null)[];\n /** Visual styling */\n style: TableLayerStyle;\n };\n}\n\n/**\n * Styling options for a TableLayer.\n */\nexport interface TableLayerStyle {\n /** Header row background color */\n headerBackground: string;\n /** Header row text color */\n headerColor: string;\n /** Body cell background color */\n cellBackground: string;\n /** Body cell text color */\n cellColor: string;\n /** Border/divider color */\n borderColor: string;\n /** Font size in pixels */\n fontSize: number;\n /** Font family */\n fontFamily?: string;\n /** Header font family (falls back to fontFamily) */\n headerFontFamily?: string;\n /** Corner radius for the table container */\n borderRadius?: number;\n}\n\n/**\n * One node in a `TreeLayer` — a JSON-serializable hierarchy item (mirrors\n * the treeview codec's `TreeItem`). Rendered as an indented filesystem-style\n * row with a folder/file icon and connector rails.\n */\nexport interface TreeLayerItem {\n id: string;\n label: string;\n /** True renders a folder (container) icon; else a file (leaf) icon. */\n isDir?: boolean;\n /** Trailing comment shown muted after the label. */\n comment?: string;\n children: TreeLayerItem[];\n}\n\n/**\n * A hierarchical treeview rendered as interactive HTML inside a\n * `<foreignObject>` (like `TableLayer`): folder/file icons, connector\n * rails, and collapse chevrons. Interactive (collapse/expand) in the live\n * React player; captured fully-expanded and static in frame/PDF export.\n */\nexport interface TreeLayer extends BaseLayer {\n type: 'tree';\n content: {\n items: TreeLayerItem[];\n style: TreeLayerStyle;\n };\n}\n\n/** Styling options for a TreeLayer. */\nexport interface TreeLayerStyle {\n /** Leaf (file) row text color. */\n rowColor: string;\n /** Container (folder) row text color. */\n dirColor: string;\n /** Connector rail / branch color. */\n connectorColor: string;\n /** Icon color. */\n iconColor: string;\n /** Muted comment color. */\n commentColor: string;\n /** Font size in pixels. */\n fontSize: number;\n /** Row label font family. */\n fontFamily?: string;\n /** Monospace font for the connector rails. */\n monoFontFamily?: string;\n /** Indent step per depth level, in pixels. */\n indentPx: number;\n /** FontAwesome icon token for containers (default `folder`). */\n folderIcon?: string;\n /** FontAwesome icon token for leaves (default `file`). */\n fileIcon?: string;\n}\n\n/**\n * Mermaid diagram layer — renders an authored `mermaid` code fence through\n * the official Mermaid runtime while keeping the fence source authoritative.\n * Like video/table/tree layers, the browser renderer hosts the diagram in an\n * SVG `<foreignObject>` so it participates in slide layout and frame capture.\n */\nexport interface MermaidLayer extends BaseLayer {\n type: 'mermaid';\n content: {\n /** Complete Mermaid source, excluding the Markdown fence delimiters. */\n source: string;\n /** Theme-derived panel color behind the generated SVG. */\n background?: string;\n /** Theme-derived foreground used by loading/error states. */\n foreground?: string;\n /** Inner panel padding in pixels. */\n padding?: number;\n };\n}\n\n/**\n * Available map tile styles from free/open-source providers.\n */\nexport type MapTileStyle =\n | 'terrain' // OpenTopoMap - topographic/terrain (default)\n | 'satellite' // ESRI World Imagery\n | 'road' // OpenStreetMap standard\n | 'toner' // Stadia Toner (high contrast B&W)\n | 'watercolor'; // Stadia Watercolor (artistic)\n\n/**\n * A marker to display on the map.\n */\nexport interface MapMarker {\n /** Marker latitude */\n lat: number;\n /** Marker longitude */\n lng: number;\n /** Optional label text */\n label?: string;\n /** Marker color (CSS color, default: #ef4444) */\n color?: string;\n /** Marker icon type */\n icon?: 'pin' | 'circle' | 'star';\n}\n\n// ============================================\n// Position & Styling\n// ============================================\n\n/**\n * Position and dimensions for a layer.\n * Values can be pixels (number) or percentages (string like \"50%\").\n */\nexport interface Position {\n /** X position (pixels or percentage) */\n x: number | string;\n /** Y position (pixels or percentage) */\n y: number | string;\n /** Width (pixels or percentage) */\n width?: number | string;\n /** Height (pixels or percentage) */\n height?: number | string;\n /** Anchor point for positioning */\n anchor?: 'center' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n}\n\n/**\n * Text styling options.\n */\nexport interface TextStyle {\n /** Font size in pixels */\n fontSize: number;\n /** Font family (defaults to system sans-serif) */\n fontFamily?: string;\n /** Font weight */\n fontWeight?: 'normal' | 'bold';\n /** Font style. Also the inherited baseline for rich `content.html`. */\n fontStyle?: 'normal' | 'italic';\n /** Text color (CSS color) */\n color: string;\n /** Horizontal text alignment within the layer's position box. */\n textAlign?: 'left' | 'center' | 'right';\n /**\n * Vertical alignment of the text within the layer's position box.\n * Requires a `position.height` to have an effect. When omitted, the\n * vertical baseline is derived from `position.anchor` (legacy behavior).\n */\n verticalAlign?: 'top' | 'middle' | 'bottom';\n /** Line height multiplier */\n lineHeight?: number;\n /** Add drop shadow for readability over images */\n shadow?: boolean;\n /** Background color for text box */\n background?: string;\n /** Background opacity 0–1 (applies to solid and gradient backgrounds). */\n backgroundOpacity?: number;\n /** Gradient background; overrides `background` when set. */\n backgroundGradient?: LinearGradient;\n /** Border (stroke) color for the text box. */\n borderColor?: string;\n /** Border width in pixels. A border renders when > 0 and a color is set. */\n borderWidth?: number;\n /** Border line style (solid/dashed/dotted). Default solid. */\n borderStyle?: BorderStyle;\n /** Padding around text (pixels) */\n padding?: number;\n /** Maximum number of lines before truncation (adds \"...\" to last line) */\n maxLines?: number;\n}\n\n// ============================================\n// Animation & Transitions\n// ============================================\n\n/**\n * Animation to apply to a layer.\n */\nexport interface Animation {\n /** Animation type */\n type: AnimationType;\n /** Duration in seconds (defaults to layer's block duration) */\n duration?: number;\n /** Delay before animation starts (seconds) */\n delay?: number;\n /** CSS easing function */\n easing?: string;\n /** For Ken Burns: zoom direction */\n direction?: 'in' | 'out';\n /** For pan animations: pan direction */\n panDirection?: 'left' | 'right' | 'up' | 'down';\n}\n\n/**\n * Available animation types.\n */\nexport type AnimationType =\n | 'none'\n | 'fadeIn'\n | 'fadeOut'\n | 'slowZoom' // Slow zoom with optional pan\n | 'zoomIn'\n | 'zoomOut'\n | 'panLeft'\n | 'panRight'\n | 'typewriter'; // Text appears letter by letter\n\n// ============================================\n// Audio Configuration\n// ============================================\n\n/**\n * Audio track configuration.\n * Articles have multiple MP3 segments (intro + sections).\n */\nexport interface AudioTrack {\n /** Audio segments in playback order */\n segments: AudioSegment[];\n}\n\n// ============================================\n// Captions\n// ============================================\n\n/**\n * A single word with precise timing, used for word-level highlighting\n * in social-style captions. Populated from TTS timing data when available.\n */\nexport interface CaptionWord {\n /** The word text */\n text: string;\n /** Start time in seconds (relative to doc start) */\n startTime: number;\n /** End time in seconds */\n endTime: number;\n}\n\n/**\n * A single caption phrase to display during playback.\n */\nexport interface CaptionPhrase {\n /** The text to display */\n text: string;\n /** Start time in seconds (relative to doc start) */\n startTime: number;\n /** End time in seconds */\n endTime: number;\n /** Which audio segment this caption belongs to (0-indexed) */\n audioSegment: number;\n /**\n * Optional per-word timing from TTS timing data.\n * When present, enables precise word-level highlighting in social\n * caption style. When absent, word timing is interpolated evenly\n * across the phrase duration.\n */\n words?: CaptionWord[];\n}\n\n/**\n * Caption track for a doc.\n */\nexport interface CaptionTrack {\n /** Caption phrases in chronological order */\n phrases: CaptionPhrase[];\n /** When the captions were generated. Optional so that conversion stays\n * deterministic — `markdownToDoc()` only sets it when the caller\n * supplies a timestamp via `captionsGeneratedAt`. */\n generatedAt?: string;\n /** Algorithm version for regeneration detection */\n version: number;\n}\n\n/**\n * A single audio segment (one MP3 file).\n */\nexport interface AudioSegment {\n /** Path to MP3 file (relative to article media dir) */\n src: string;\n /** Segment name (e.g., \"intro\", \"history\") */\n name: string;\n /** Duration in seconds */\n duration: number;\n /** Start time in overall timeline (calculated) */\n startTime: number;\n}\n\n// ============================================\n// Audio Timing Data (from TTS)\n// ============================================\n\n/**\n * A single word-level timing bookmark from TTS synthesis.\n * Used for precise audio-to-content mapping and word-level caption sync.\n */\nexport interface AudioBookmark {\n /** Unique identifier (e.g., \"word-0\", \"word-1\") */\n id: string;\n /** Timestamp in seconds from audio start */\n time: number;\n /** Character offset in the source text */\n charOffset: number;\n /** The word text at this position */\n textFragment?: string;\n}\n\n/**\n * Timing data for an audio segment, typically from a `.timing.json` file\n * generated alongside TTS audio. Contains the source text and per-word\n * timing bookmarks for precise content matching and caption sync.\n */\nexport interface AudioTimingData {\n /** The normalized plain text that was synthesized */\n sourceText: string;\n /** Word-level timing bookmarks */\n bookmarks: AudioBookmark[];\n /** Total audio duration in seconds */\n duration: number;\n}\n\n// ============================================\n// Helper Functions\n// ============================================\n\n/**\n * Calculate total duration from audio segments.\n */\nexport function calculateDuration(audio: AudioTrack): number {\n return audio.segments.reduce((sum, seg) => sum + seg.duration, 0);\n}\n\n/**\n * Find which audio segment is playing at a given time.\n */\nexport function getSegmentAtTime(audio: AudioTrack, time: number): number {\n let elapsed = 0;\n for (let i = 0; i < audio.segments.length; i++) {\n elapsed += audio.segments[i].duration;\n if (time < elapsed) return i;\n }\n return audio.segments.length - 1;\n}\n\n/**\n * Find which block should be visible at a given time.\n */\nexport function getBlockAtTime(blocks: Block[], time: number): Block | null {\n for (let i = blocks.length - 1; i >= 0; i--) {\n const block = blocks[i];\n if (time >= block.startTime && time < block.startTime + block.duration) {\n return block;\n }\n }\n return blocks[0] || null;\n}\n\n/**\n * Find the caption phrase that should be displayed at a given time.\n */\nexport function getCaptionAtTime(\n captions: CaptionTrack | undefined,\n time: number,\n): CaptionPhrase | null {\n if (!captions || !captions.phrases.length) return null;\n\n for (const phrase of captions.phrases) {\n if (time >= phrase.startTime && time < phrase.endTime) {\n return phrase;\n }\n }\n return null;\n}\n","/**\n * Theme Compilation\n *\n * Turns a partial Theme (typically authored by the customizer panel from\n * a few seed colors and preset choices) into a complete, validated Theme\n * by:\n *\n * 1. Filling unspecified fields from a hardcoded `STARTER_THEME`.\n * 2. Deriving missing color slots from `seedColors` via OKLCh math.\n * 3. Validating the result.\n *\n * Built-in themes ship as fully-specified Theme JSON and skip this step.\n */\n\nimport type {\n Theme,\n DeepPartial,\n ThemeColorPalette,\n ThemeColorScheme,\n ThemeSeedColors,\n FontFamily,\n} from './Theme.js';\nimport { THEME_SCHEMA_VERSION, createTheme } from './Theme.js';\nimport { assertTheme } from './themeValidator.js';\nimport { defaultPageStyle } from './pageStyleDefaults.js';\nimport {\n oklchLighten,\n oklchDarken,\n oklchSetChroma,\n pickContrastingText,\n relativeLuminance,\n deriveScale,\n isHex,\n} from './colorUtils.js';\n\n/** Internal default theme used to fill in fields the customizer doesn't expose. */\nconst STARTER_BODY_FONT: FontFamily = { stackId: 'system-sans' };\nconst STARTER_TITLE_FONT: FontFamily = { stackId: 'system-serif' };\nconst STARTER_MONO_FONT: FontFamily = { stackId: 'system-mono' };\n\nconst STARTER_COLOR_SCHEMES: Record<string, ThemeColorScheme> = {\n blue: { bg: '#1a365d', text: '#63b3ed', accent: '#90cdf4' },\n green: { bg: '#22543d', text: '#9ae6b4', accent: '#68d391' },\n purple: { bg: '#44337a', text: '#d6bcfa', accent: '#b794f4' },\n red: { bg: '#742a2a', text: '#fc8181', accent: '#feb2b2' },\n orange: { bg: '#744210', text: '#fbd38d', accent: '#f6ad55' },\n teal: { bg: '#234e52', text: '#81e6d9', accent: '#4fd1c5' },\n};\n\nexport const STARTER_THEME: Theme = {\n schemaVersion: THEME_SCHEMA_VERSION,\n id: 'custom',\n name: 'Custom Theme',\n description: 'Customizer starter — gets overridden by user choices.',\n colors: {\n primary: '#3182ce',\n secondary: '#4a5568',\n background: '#1a202c',\n backgroundLight: '#2d3748',\n text: '#f7fafc',\n textMuted: '#a0aec0',\n highlight: '#4299e1',\n warning: '#fc8181',\n },\n typography: {\n bodyFont: STARTER_BODY_FONT,\n titleFont: STARTER_TITLE_FONT,\n monoFont: STARTER_MONO_FONT,\n titleWeight: 'bold',\n },\n style: {\n textShadow: true,\n overlayOpacity: 0.45,\n animationSpeed: 1.0,\n borderRadius: 6,\n },\n renderStyle: {\n name: 'standard',\n defaultTextAnimation: 'fadeIn',\n defaultImageAnimation: 'slowZoom',\n ambientMotion: true,\n defaultTransition: { type: 'fade', duration: 0.7 },\n },\n colorSchemes: STARTER_COLOR_SCHEMES,\n};\n\n/**\n * Derive a full `ThemeColorPalette` from `seedColors`, with any explicit\n * `partialColors` taking precedence over derived values. Background and\n * text are guessed from luminance when the user gave only a primary.\n */\nexport function deriveColorPalette(\n seeds: ThemeSeedColors,\n partialColors: Partial<ThemeColorPalette> = {},\n opts: { contrast?: 'subtle' | 'balanced' | 'high' } = {},\n): ThemeColorPalette {\n const spread = opts.contrast === 'high' ? 0.22 : opts.contrast === 'subtle' ? 0.08 : 0.15;\n\n const primary = seeds.primary;\n const secondary = seeds.secondary ?? oklchSetChroma(oklchLighten(primary, 0.05), 0.5);\n const accent = seeds.accent ?? oklchLighten(primary, spread);\n\n // Decide light vs dark surface from the explicit background, the seed background,\n // or default to dark.\n const bgSeed = partialColors.background ?? seeds.background;\n let background: string;\n if (bgSeed) {\n background = bgSeed;\n } else {\n // Pick a dark or light background that contrasts with primary\n background = relativeLuminance(primary) > 0.5 ? '#0a0a0a' : '#1a202c';\n }\n const isLightSurface = relativeLuminance(background) > 0.5;\n\n const backgroundLight =\n partialColors.backgroundLight ??\n (isLightSurface ? oklchDarken(background, 0.04) : oklchLighten(background, 0.04));\n\n const text =\n partialColors.text ?? seeds.text ?? pickContrastingText(background, '#f7fafc', '#1a202c');\n const textMuted =\n partialColors.textMuted ??\n (isLightSurface ? oklchLighten(text, 0.25) : oklchDarken(text, 0.25));\n\n const highlight = partialColors.highlight ?? accent;\n const warning = partialColors.warning ?? '#fc8181';\n\n return {\n primary: partialColors.primary ?? primary,\n secondary: partialColors.secondary ?? secondary,\n background,\n backgroundLight,\n text,\n textMuted,\n highlight,\n warning,\n };\n}\n\n/**\n * Expand one accent color into a full `{bg, text, accent}` color scheme via\n * the OKLCh scale — dark saturated bg, light readable text, the picked accent.\n * Falls back to a neutral scheme when the input isn't a valid hex. Shared by\n * the editor's accent list and file-import theme inference so both derive\n * identical schemes from the same accent.\n */\nexport function accentToColorScheme(accent: string): ThemeColorScheme {\n if (!isHex(accent)) return { bg: '#1a202c', text: '#e2e8f0', accent: '#63b3ed' };\n const scale = deriveScale(accent, 0.3);\n return { bg: scale.darker2, text: scale.lighter2, accent: scale.base };\n}\n\n/** Map a contrast preset to numeric spread used by `deriveColorPalette`. */\nexport type ContrastPreset = 'subtle' | 'balanced' | 'high';\n\nexport interface CompileOptions {\n /** Contrast level for OKLCh derivation (default 'balanced'). */\n contrast?: ContrastPreset;\n /**\n * Base theme to inherit from. When provided, the partial is deep-merged\n * over this theme instead of the neutral `STARTER_THEME`, so the compiled\n * theme inherits the base's render style, color schemes, typography, and\n * persistent layers — and only the fields the user changed are overridden.\n * The base's id is recorded on the result as `basedOn`.\n */\n base?: Theme;\n}\n\n/**\n * Compile a partial Theme into a complete one. Fills missing fields from\n * the base (`opts.base` when given, else `STARTER_THEME`), derives missing\n * color slots from `seedColors` (when present), and validates the result.\n */\nexport function compileTheme(partial: DeepPartial<Theme>, opts: CompileOptions = {}): Theme {\n // Step 1: deep-merge over the base (a chosen theme, or the neutral starter)\n const base = opts.base ?? STARTER_THEME;\n const merged = createTheme(base, partial);\n merged.schemaVersion = THEME_SCHEMA_VERSION;\n // Record which theme this was derived from so a customizer can re-inherit.\n if (opts.base && !merged.basedOn) merged.basedOn = opts.base.id;\n\n // Step 1b: typography fonts are discriminated unions ({stackId} | {custom}),\n // so deep-merge would leave stale keys from the starter when the partial\n // switches form. Replace each font wholesale when explicitly provided.\n const partialTypography = partial.typography;\n if (partialTypography) {\n if (partialTypography.titleFont !== undefined) {\n merged.typography.titleFont = partialTypography.titleFont as FontFamily;\n }\n if (partialTypography.bodyFont !== undefined) {\n merged.typography.bodyFont = partialTypography.bodyFont as FontFamily;\n }\n if (partialTypography.monoFont !== undefined) {\n merged.typography.monoFont = partialTypography.monoFont as FontFamily;\n }\n }\n\n // Step 1c: colorSchemes is a map the user edits wholesale (add / remove\n // accents). Deep-merge can't delete keys, so replace it outright when the\n // partial provides it — mirroring the font replacement above. This lets a\n // removed accent actually disappear rather than lingering from the base.\n if (partial.colorSchemes !== undefined) {\n merged.colorSchemes = partial.colorSchemes as Record<string, ThemeColorScheme>;\n }\n\n // Step 2: derive missing color slots from seeds, if present\n if (merged.seedColors) {\n const partialColors = (partial.colors ?? {}) as Partial<ThemeColorPalette>;\n merged.colors = deriveColorPalette(merged.seedColors, partialColors, {\n contrast: opts.contrast,\n });\n }\n\n // Step 2b: fill page art direction from existing fields when absent, so\n // every compiled theme carries an explicit, serializable pageStyle.\n if (!merged.pageStyle) {\n merged.pageStyle = defaultPageStyle(merged);\n }\n\n // Step 3: validate\n return assertTheme(merged, `compiled theme \"${merged.id}\"`);\n}\n\n/**\n * Parse a JSON string into a validated Theme. Throws on invalid input.\n */\nexport function parseTheme(json: string): Theme {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`Invalid theme JSON: ${msg}`);\n }\n return assertTheme(parsed, 'parsed theme');\n}\n\n/**\n * Serialize a Theme to a stable, pretty-printed JSON string. Round-trips\n * cleanly through `parseTheme`.\n */\nexport function serializeTheme(theme: Theme): string {\n return JSON.stringify(theme, null, 2);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAogCO,SAAS,kBAAkB,OAA2B;AAC3D,SAAO,MAAM,SAAS,OAAO,CAAC,KAAK,QAAQ,MAAM,IAAI,UAAU,CAAC;AAClE;AAKO,SAAS,iBAAiB,OAAmB,MAAsB;AACxE,MAAI,UAAU;AACd,WAAS,IAAI,GAAG,IAAI,MAAM,SAAS,QAAQ,KAAK;AAC9C,eAAW,MAAM,SAAS,CAAC,EAAE;AAC7B,QAAI,OAAO,QAAS,QAAO;AAAA,EAC7B;A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;AAC9C,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,IAAI;AAAA,EAC1B,SAAS,KAAc;AACrB,UAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC3D,UAAM,IAAI,MAAM,uBAAuB,GAAG,EAAE;AAAA,EAC9C;AACA,SAAO,YAAY,QAAQ,cAAc;AAC3C;AAMO,SAAS,eAAe,OAAsB;AACnD,SAAO,KAAK,UAAU,OAAO,MAAM,CAAC;AACtC;","names":[]}
@@ -0,0 +1,215 @@
1
+ // src/schemas/Media.ts
2
+ function flatten(blocks, out = []) {
3
+ for (const b of blocks) {
4
+ out.push(b);
5
+ if (b.children && b.children.length > 0) flatten(b.children, out);
6
+ }
7
+ return out;
8
+ }
9
+ function clipLength(clip) {
10
+ if (clip.clipEnd == null) return null;
11
+ return Math.max(0, clip.clipEnd - (clip.clipStart ?? 0));
12
+ }
13
+ function baseTimelineEnd(doc) {
14
+ const blockEnd = flatten(doc.blocks).reduce(
15
+ (max, b) => Math.max(max, b.startTime + b.duration),
16
+ 0
17
+ );
18
+ return Math.max(doc.duration ?? 0, blockEnd);
19
+ }
20
+ function resolveMediaSchedule(doc) {
21
+ const out = [];
22
+ const docEnd = baseTimelineEnd(doc);
23
+ for (const block of flatten(doc.blocks)) {
24
+ const blockEnd = block.startTime + block.duration;
25
+ for (const clip of block.media ?? []) {
26
+ const start = block.startTime + clip.startAt;
27
+ const len = clipLength(clip);
28
+ let end;
29
+ if (clip.spillover) {
30
+ end = len != null ? start + len : blockEnd;
31
+ } else {
32
+ end = len != null ? Math.min(start + len, blockEnd) : blockEnd;
33
+ }
34
+ out.push({
35
+ id: clip.id,
36
+ src: clip.src,
37
+ kind: clip.kind,
38
+ absoluteStart: start,
39
+ absoluteEnd: Math.max(start, end),
40
+ sourceIn: clip.clipStart ?? 0,
41
+ anchor: "block",
42
+ blockId: block.id,
43
+ ...clip.sourceLine != null ? { sourceLine: clip.sourceLine } : {}
44
+ });
45
+ }
46
+ }
47
+ for (const clip of doc.documentMedia ?? []) {
48
+ const start = clip.startAt;
49
+ const len = clipLength(clip);
50
+ const end = len != null ? start + len : docEnd;
51
+ out.push({
52
+ id: clip.id,
53
+ src: clip.src,
54
+ kind: clip.kind,
55
+ absoluteStart: start,
56
+ absoluteEnd: Math.max(start, end),
57
+ sourceIn: clip.clipStart ?? 0,
58
+ anchor: "document",
59
+ ...clip.sourceLine != null ? { sourceLine: clip.sourceLine } : {}
60
+ });
61
+ }
62
+ return out;
63
+ }
64
+ function getDocPlaybackDuration(doc) {
65
+ const base = baseTimelineEnd(doc);
66
+ const mediaEnd = resolveMediaSchedule(doc).reduce((max, c) => Math.max(max, c.absoluteEnd), 0);
67
+ return Math.max(base, mediaEnd);
68
+ }
69
+
70
+ // src/schemas/pageStyleDefaults.ts
71
+ var FAMILY_BY_RENDER_STYLE = {
72
+ standard: "clean",
73
+ minimalist: "clean",
74
+ documentary: "documentary",
75
+ magazine: "editorial",
76
+ bold: "brutalist",
77
+ "tech-dark": "terminal",
78
+ cinematic: "cinematic",
79
+ "warm-earth": "organic",
80
+ "morning-light": "soft",
81
+ gezellig: "soft"
82
+ };
83
+ var FAMILY_DEFAULTS = {
84
+ clean: {
85
+ sectionSpacing: "comfortable",
86
+ divider: "hairline",
87
+ backgroundRhythm: "alternate",
88
+ heroStyle: "stacked",
89
+ headingTreatment: { eyebrow: "kicker", scale: "regular", underline: "none" },
90
+ quoteMark: "accent-bar",
91
+ numeralStyle: "plain",
92
+ accentStrategy: "cycle"
93
+ },
94
+ editorial: {
95
+ sectionSpacing: "comfortable",
96
+ divider: "double-rule",
97
+ backgroundRhythm: "flat",
98
+ heroStyle: "split",
99
+ headingTreatment: { eyebrow: "kicker", scale: "display", underline: "none" },
100
+ quoteMark: "oversized-glyph",
101
+ numeralStyle: "oversized",
102
+ accentStrategy: "alternate-two"
103
+ },
104
+ brutalist: {
105
+ sectionSpacing: "compact",
106
+ divider: "thick-rule",
107
+ backgroundRhythm: "accent-bands",
108
+ heroStyle: "oversized-type",
109
+ headingTreatment: { eyebrow: "kicker", scale: "oversized", case: "uppercase" },
110
+ quoteMark: "none",
111
+ numeralStyle: "oversized",
112
+ accentStrategy: "cycle"
113
+ },
114
+ terminal: {
115
+ sectionSpacing: "compact",
116
+ divider: "hairline",
117
+ backgroundRhythm: "tinted-panels",
118
+ heroStyle: "stacked",
119
+ headingTreatment: { eyebrow: "mono-tag", scale: "regular", underline: "none" },
120
+ quoteMark: "none",
121
+ numeralStyle: "mono",
122
+ accentStrategy: "primary-only"
123
+ },
124
+ cinematic: {
125
+ sectionSpacing: "generous",
126
+ divider: "gap-only",
127
+ backgroundRhythm: "flat",
128
+ heroStyle: "full-bleed",
129
+ headingTreatment: { eyebrow: "kicker", scale: "display", case: "uppercase" },
130
+ quoteMark: "none",
131
+ numeralStyle: "oversized",
132
+ accentStrategy: "primary-only"
133
+ },
134
+ documentary: {
135
+ sectionSpacing: "generous",
136
+ divider: "thick-rule",
137
+ backgroundRhythm: "flat",
138
+ heroStyle: "letterbox",
139
+ headingTreatment: { eyebrow: "numbered", scale: "display", underline: "none" },
140
+ quoteMark: "accent-bar",
141
+ numeralStyle: "boxed",
142
+ accentStrategy: "primary-only"
143
+ },
144
+ organic: {
145
+ sectionSpacing: "comfortable",
146
+ divider: "thick-rule",
147
+ backgroundRhythm: "tinted-panels",
148
+ heroStyle: "stacked",
149
+ headingTreatment: { eyebrow: "kicker", scale: "regular", underline: "accent-bar" },
150
+ quoteMark: "oversized-glyph",
151
+ numeralStyle: "boxed",
152
+ accentStrategy: "alternate-two"
153
+ },
154
+ soft: {
155
+ sectionSpacing: "comfortable",
156
+ divider: "dotted",
157
+ backgroundRhythm: "tinted-panels",
158
+ heroStyle: "split",
159
+ headingTreatment: { eyebrow: "kicker", scale: "regular", underline: "none" },
160
+ quoteMark: "oversized-glyph",
161
+ numeralStyle: "plain",
162
+ accentStrategy: "alternate-two"
163
+ }
164
+ };
165
+ function derivePattern(theme) {
166
+ const layers = [
167
+ ...theme.persistentLayers?.bottomLayers ?? [],
168
+ ...theme.persistentLayers?.topLayers ?? []
169
+ ];
170
+ for (const layer of layers) {
171
+ if (typeof layer === "object" && layer !== null && "template" in layer && layer.template === "patternBackground") {
172
+ const config = layer.config;
173
+ const pattern = config?.pattern;
174
+ if (pattern === "dots" || pattern === "grid" || pattern === "diagonal" || pattern === "noise") {
175
+ return pattern;
176
+ }
177
+ }
178
+ }
179
+ return void 0;
180
+ }
181
+ function defaultPageStyle(theme) {
182
+ const family = FAMILY_BY_RENDER_STYLE[theme.renderStyle?.name ?? ""] ?? "clean";
183
+ const defaults = FAMILY_DEFAULTS[family];
184
+ const cornerRadius = theme.style?.borderRadius ?? 6;
185
+ const treatmentType = theme.style?.imageTreatment?.type;
186
+ const imageFraming = treatmentType === "mono" || treatmentType === "duotone" ? "letterboxed" : cornerRadius > 0 ? "rounded" : "flush";
187
+ const tokens = {
188
+ contentMaxWidth: 760,
189
+ wideMaxWidth: 1100,
190
+ sectionSpacing: defaults.sectionSpacing,
191
+ cornerRadius,
192
+ divider: defaults.divider,
193
+ backgroundRhythm: defaults.backgroundRhythm,
194
+ heroStyle: defaults.heroStyle,
195
+ headingTreatment: { ...defaults.headingTreatment },
196
+ imageFraming,
197
+ shadow: theme.style?.textShadow ? "soft" : "none",
198
+ quoteMark: defaults.quoteMark,
199
+ numeralStyle: defaults.numeralStyle
200
+ };
201
+ const pattern = derivePattern(theme);
202
+ if (pattern) tokens.pattern = pattern;
203
+ return {
204
+ family,
205
+ tokens,
206
+ accentRotation: { strategy: defaults.accentStrategy }
207
+ };
208
+ }
209
+
210
+ export {
211
+ resolveMediaSchedule,
212
+ getDocPlaybackDuration,
213
+ defaultPageStyle
214
+ };
215
+ //# sourceMappingURL=chunk-VWCJ2WXC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schemas/Media.ts","../src/schemas/pageStyleDefaults.ts"],"sourcesContent":["/**\n * Media-clip timing model.\n *\n * An additive layer on top of the simple sequential `Doc.audio.segments[]`\n * narration track, which remains first-class. A {@link MediaClip} is a piece\n * of audio or video whose\n * timing is expressed *relative to its parent block* (or the whole document),\n * with an optional `startAt` offset and an optional `spillover` past the\n * block's end. {@link resolveMediaSchedule} flattens these into absolute,\n * doc-timeline `ScheduledClip`s that playback and export consume.\n *\n * Authoring: a body-level `{[audio …]}` / `{[video …]}` annotation inside a\n * block becomes a `block.media` clip; the same annotation in the preamble\n * (before the first heading) with `anchor=document` becomes a\n * `doc.documentMedia` clip that spans the whole timeline.\n */\n\nimport type { Block, Doc } from './Doc.js';\n\n/**\n * A timed piece of media attached to a block (or the document).\n */\nexport interface MediaClip {\n /** Stable id (for React keys and timeline selection). */\n id: string;\n /** Source path (mp3/mp4/…), relative to the article media dir. */\n src: string;\n kind: 'audio' | 'video';\n /**\n * Seconds from the parent block's start when this clip begins. For an\n * `anchor='document'` clip, seconds from the document start. Default 0.\n */\n startAt: number;\n /** Source in-point within the file (seconds). Default 0. */\n clipStart?: number;\n /** Source out-point within the file (seconds). Default: file/block end. */\n clipEnd?: number;\n /**\n * When false (default) the clip stops at its block's end. When true it\n * keeps playing past the block boundary until the clip itself finishes.\n * Ignored for `anchor='document'` clips (they already span the timeline).\n */\n spillover?: boolean;\n /**\n * `'block'` (default) — timed relative to the parent block. `'document'` —\n * timed relative to the document start and able to span every block.\n */\n anchor: 'block' | 'document';\n /**\n * 1-based source line of the authoring annotation, when derived from\n * markdown. Enables round-tripping edits (e.g. the timeline editor rewriting\n * `startAt`) back to the exact line. Absent for programmatically built clips.\n */\n sourceLine?: number;\n /**\n * Round-trip home of the authoring annotation: the block whose contents\n * held the paragraph, its position in that block's ORIGINAL contents\n * array (before extraction), and the paragraph's exact source text.\n * `docToMarkdown` re-inserts the annotation from this — `raw` verbatim\n * when present, a re-serialized annotation otherwise. Absent for\n * programmatically built clips (those emit at the document top).\n */\n origin?: { blockId: string; index: number; raw?: string };\n}\n\n/**\n * A {@link MediaClip} resolved to absolute document-timeline coordinates.\n * Produced by {@link resolveMediaSchedule}; consumed by the playback\n * scheduler and the MP4 export.\n */\nexport interface ScheduledClip {\n id: string;\n src: string;\n kind: 'audio' | 'video';\n /** Absolute doc-timeline second the clip starts. */\n absoluteStart: number;\n /** Absolute doc-timeline second the clip ends (exclusive). */\n absoluteEnd: number;\n /** Source in-point to seek to at `absoluteStart`. */\n sourceIn: number;\n anchor: 'block' | 'document';\n /** Owning block id for block-anchored clips (for video re-homing/export). */\n blockId?: string;\n /** 1-based source line of the authoring annotation, when known. */\n sourceLine?: number;\n}\n\n/** Depth-first flatten of the block tree (local copy to avoid a doc-layer dep). */\nfunction flatten(blocks: Block[], out: Block[] = []): Block[] {\n for (const b of blocks) {\n out.push(b);\n if (b.children && b.children.length > 0) flatten(b.children, out);\n }\n return out;\n}\n\n/** Played length of a clip when known from its in/out points, else null. */\nfunction clipLength(clip: MediaClip): number | null {\n if (clip.clipEnd == null) return null;\n return Math.max(0, clip.clipEnd - (clip.clipStart ?? 0));\n}\n\n/**\n * Base playback span ignoring media — the larger of the audio-segment sum\n * and the last block's end. Document clips that don't pin a length run to\n * this point.\n */\nfunction baseTimelineEnd(doc: Doc): number {\n const blockEnd = flatten(doc.blocks).reduce(\n (max, b) => Math.max(max, b.startTime + b.duration),\n 0,\n );\n return Math.max(doc.duration ?? 0, blockEnd);\n}\n\n/**\n * Flatten every block clip and document clip into absolute-timed\n * `ScheduledClip`s. Pure — depends only on `doc`.\n */\nexport function resolveMediaSchedule(doc: Doc): ScheduledClip[] {\n const out: ScheduledClip[] = [];\n const docEnd = baseTimelineEnd(doc);\n\n for (const block of flatten(doc.blocks)) {\n const blockEnd = block.startTime + block.duration;\n for (const clip of block.media ?? []) {\n const start = block.startTime + clip.startAt;\n const len = clipLength(clip);\n let end: number;\n if (clip.spillover) {\n // Continue past the block; fall back to the block end when the\n // played length is unknown (no clipEnd authored).\n end = len != null ? start + len : blockEnd;\n } else {\n end = len != null ? Math.min(start + len, blockEnd) : blockEnd;\n }\n out.push({\n id: clip.id,\n src: clip.src,\n kind: clip.kind,\n absoluteStart: start,\n absoluteEnd: Math.max(start, end),\n sourceIn: clip.clipStart ?? 0,\n anchor: 'block',\n blockId: block.id,\n ...(clip.sourceLine != null ? { sourceLine: clip.sourceLine } : {}),\n });\n }\n }\n\n for (const clip of doc.documentMedia ?? []) {\n const start = clip.startAt;\n const len = clipLength(clip);\n const end = len != null ? start + len : docEnd;\n out.push({\n id: clip.id,\n src: clip.src,\n kind: clip.kind,\n absoluteStart: start,\n absoluteEnd: Math.max(start, end),\n sourceIn: clip.clipStart ?? 0,\n anchor: 'document',\n ...(clip.sourceLine != null ? { sourceLine: clip.sourceLine } : {}),\n });\n }\n\n return out;\n}\n\n/**\n * Total playback duration including any media that spills past the last\n * block (or audio segment). Export uses this for the frame count and the\n * player for its effective timeline length.\n */\nexport function getDocPlaybackDuration(doc: Doc): number {\n const base = baseTimelineEnd(doc);\n const mediaEnd = resolveMediaSchedule(doc).reduce((max, c) => Math.max(max, c.absoluteEnd), 0);\n return Math.max(base, mediaEnd);\n}\n","/**\n * Page Style Defaults\n *\n * Derives a complete `ThemePageStyle` from a theme's existing fields so\n * legacy themes, customizer themes, and file-inferred themes get a\n * coherent page art direction without declaring one. Built-in themes\n * ship explicit `pageStyle` blocks in their JSON; this derivation is the\n * fallback used by `compileTheme` and by `resolvePageStyle` at read time.\n *\n * Derivation signals:\n * - `renderStyle.name` → design family (documentary → documentary,\n * magazine → editorial, bold → brutalist, tech-dark → terminal, …)\n * - `style.borderRadius` → cornerRadius + rounded vs flush image framing\n * - `style.imageTreatment` (mono/duotone) → letterboxed framing\n * - `style.textShadow` → shadow language\n * - `persistentLayers` patternBackground → page pattern\n */\n\nimport type { Theme } from './Theme.js';\nimport type {\n PageDesignFamily,\n PageTokens,\n ThemePageStyle,\n PageHeadingTreatment,\n} from './PageStyle.js';\n\n/** renderStyle.name → design family. Unknown names fall back to 'clean'. */\nconst FAMILY_BY_RENDER_STYLE: Record<string, PageDesignFamily> = {\n standard: 'clean',\n minimalist: 'clean',\n documentary: 'documentary',\n magazine: 'editorial',\n bold: 'brutalist',\n 'tech-dark': 'terminal',\n cinematic: 'cinematic',\n 'warm-earth': 'organic',\n 'morning-light': 'soft',\n gezellig: 'soft',\n};\n\ninterface FamilyDefaults {\n sectionSpacing: PageTokens['sectionSpacing'];\n divider: PageTokens['divider'];\n backgroundRhythm: PageTokens['backgroundRhythm'];\n heroStyle: PageTokens['heroStyle'];\n headingTreatment: PageHeadingTreatment;\n quoteMark: PageTokens['quoteMark'];\n numeralStyle: PageTokens['numeralStyle'];\n accentStrategy: ThemePageStyle['accentRotation']['strategy'];\n}\n\nconst FAMILY_DEFAULTS: Record<PageDesignFamily, FamilyDefaults> = {\n clean: {\n sectionSpacing: 'comfortable',\n divider: 'hairline',\n backgroundRhythm: 'alternate',\n heroStyle: 'stacked',\n headingTreatment: { eyebrow: 'kicker', scale: 'regular', underline: 'none' },\n quoteMark: 'accent-bar',\n numeralStyle: 'plain',\n accentStrategy: 'cycle',\n },\n editorial: {\n sectionSpacing: 'comfortable',\n divider: 'double-rule',\n backgroundRhythm: 'flat',\n heroStyle: 'split',\n headingTreatment: { eyebrow: 'kicker', scale: 'display', underline: 'none' },\n quoteMark: 'oversized-glyph',\n numeralStyle: 'oversized',\n accentStrategy: 'alternate-two',\n },\n brutalist: {\n sectionSpacing: 'compact',\n divider: 'thick-rule',\n backgroundRhythm: 'accent-bands',\n heroStyle: 'oversized-type',\n headingTreatment: { eyebrow: 'kicker', scale: 'oversized', case: 'uppercase' },\n quoteMark: 'none',\n numeralStyle: 'oversized',\n accentStrategy: 'cycle',\n },\n terminal: {\n sectionSpacing: 'compact',\n divider: 'hairline',\n backgroundRhythm: 'tinted-panels',\n heroStyle: 'stacked',\n headingTreatment: { eyebrow: 'mono-tag', scale: 'regular', underline: 'none' },\n quoteMark: 'none',\n numeralStyle: 'mono',\n accentStrategy: 'primary-only',\n },\n cinematic: {\n sectionSpacing: 'generous',\n divider: 'gap-only',\n backgroundRhythm: 'flat',\n heroStyle: 'full-bleed',\n headingTreatment: { eyebrow: 'kicker', scale: 'display', case: 'uppercase' },\n quoteMark: 'none',\n numeralStyle: 'oversized',\n accentStrategy: 'primary-only',\n },\n documentary: {\n sectionSpacing: 'generous',\n divider: 'thick-rule',\n backgroundRhythm: 'flat',\n heroStyle: 'letterbox',\n headingTreatment: { eyebrow: 'numbered', scale: 'display', underline: 'none' },\n quoteMark: 'accent-bar',\n numeralStyle: 'boxed',\n accentStrategy: 'primary-only',\n },\n organic: {\n sectionSpacing: 'comfortable',\n divider: 'thick-rule',\n backgroundRhythm: 'tinted-panels',\n heroStyle: 'stacked',\n headingTreatment: { eyebrow: 'kicker', scale: 'regular', underline: 'accent-bar' },\n quoteMark: 'oversized-glyph',\n numeralStyle: 'boxed',\n accentStrategy: 'alternate-two',\n },\n soft: {\n sectionSpacing: 'comfortable',\n divider: 'dotted',\n backgroundRhythm: 'tinted-panels',\n heroStyle: 'split',\n headingTreatment: { eyebrow: 'kicker', scale: 'regular', underline: 'none' },\n quoteMark: 'oversized-glyph',\n numeralStyle: 'plain',\n accentStrategy: 'alternate-two',\n },\n};\n\n/** Read the first patternBackground pattern from a theme's persistent layers. */\nfunction derivePattern(theme: Theme): PageTokens['pattern'] {\n const layers = [\n ...(theme.persistentLayers?.bottomLayers ?? []),\n ...(theme.persistentLayers?.topLayers ?? []),\n ];\n for (const layer of layers) {\n if (\n typeof layer === 'object' &&\n layer !== null &&\n 'template' in layer &&\n (layer as { template?: unknown }).template === 'patternBackground'\n ) {\n const config = (layer as { config?: { pattern?: unknown } }).config;\n const pattern = config?.pattern;\n if (\n pattern === 'dots' ||\n pattern === 'grid' ||\n pattern === 'diagonal' ||\n pattern === 'noise'\n ) {\n return pattern;\n }\n }\n }\n return undefined;\n}\n\n/**\n * Derive a complete `ThemePageStyle` from a theme's existing fields.\n * Deterministic and read-only; explicit `theme.pageStyle` always wins\n * (callers check before deriving — see `resolvePageStyle`).\n */\nexport function defaultPageStyle(theme: Theme): ThemePageStyle {\n const family = FAMILY_BY_RENDER_STYLE[theme.renderStyle?.name ?? ''] ?? 'clean';\n const defaults = FAMILY_DEFAULTS[family];\n\n const cornerRadius = theme.style?.borderRadius ?? 6;\n const treatmentType = theme.style?.imageTreatment?.type;\n const imageFraming: PageTokens['imageFraming'] =\n treatmentType === 'mono' || treatmentType === 'duotone'\n ? 'letterboxed'\n : cornerRadius > 0\n ? 'rounded'\n : 'flush';\n\n const tokens: PageTokens = {\n contentMaxWidth: 760,\n wideMaxWidth: 1100,\n sectionSpacing: defaults.sectionSpacing,\n cornerRadius,\n divider: defaults.divider,\n backgroundRhythm: defaults.backgroundRhythm,\n heroStyle: defaults.heroStyle,\n headingTreatment: { ...defaults.headingTreatment },\n imageFraming,\n shadow: theme.style?.textShadow ? 'soft' : 'none',\n quoteMark: defaults.quoteMark,\n numeralStyle: defaults.numeralStyle,\n };\n\n const pattern = derivePattern(theme);\n if (pattern) tokens.pattern = pattern;\n\n return {\n family,\n tokens,\n accentRotation: { strategy: defaults.accentStrategy },\n };\n}\n"],"mappings":";AAwFA,SAAS,QAAQ,QAAiB,MAAe,CAAC,GAAY;AAC5D,aAAW,KAAK,QAAQ;AACtB,QAAI,KAAK,CAAC;AACV,QAAI,EAAE,YAAY,EAAE,SAAS,SAAS,EAAG,SAAQ,EAAE,UAAU,GAAG;AAAA,EAClE;AACA,SAAO;AACT;AAGA,SAAS,WAAW,MAAgC;AAClD,MAAI,KAAK,WAAW,KAAM,QAAO;AACjC,SAAO,KAAK,IAAI,GAAG,KAAK,WAAW,KAAK,aAAa,EAAE;AACzD;AAOA,SAAS,gBAAgB,KAAkB;AACzC,QAAM,WAAW,QAAQ,IAAI,MAAM,EAAE;AAAA,IACnC,CAAC,KAAK,MAAM,KAAK,IAAI,KAAK,EAAE,YAAY,EAAE,QAAQ;AAAA,IAClD;AAAA,EACF;AACA,SAAO,KAAK,IAAI,IAAI,YAAY,GAAG,QAAQ;AAC7C;A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MAA6C;AAC7D,YAAM,UAAU,QAAQ;AACxB,UACE,YAAY,UACZ,YAAY,UACZ,YAAY,cACZ,YAAY,SACZ;AACA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAOO,SAAS,iBAAiB,OAA8B;AAC7D,QAAM,SAAS,uBAAuB,MAAM,aAAa,QAAQ,EAAE,KAAK;AACxE,QAAM,WAAW,gBAAgB,MAAM;AAEvC,QAAM,eAAe,MAAM,OAAO,gBAAgB;AAClD,QAAM,gBAAgB,MAAM,OAAO,gBAAgB;AACnD,QAAM,eACJ,kBAAkB,UAAU,kBAAkB,YAC1C,gBACA,eAAe,IACb,YACA;AAER,QAAM,SAAqB;AAAA,IACzB,iBAAiB;AAAA,IACjB,cAAc;AAAA,IACd,gBAAgB,SAAS;AAAA,IACzB;AAAA,IACA,SAAS,SAAS;AAAA,IAClB,kBAAkB,SAAS;AAAA,IAC3B,WAAW,SAAS;AAAA,IACpB,kBAAkB,EAAE,GAAG,SAAS,iBAAiB;AAAA,IACjD;AAAA,IACA,QAAQ,MAAM,OAAO,aAAa,SAAS;AAAA,IAC3C,WAAW,SAAS;AAAA,IACpB,cAAc,SAAS;AAAA,EACzB;AAEA,QAAM,UAAU,cAAc,KAAK;AACnC,MAAI,QAAS,QAAO,UAAU;AAE9B,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,gBAAgB,EAAE,UAAU,SAAS,eAAe;AAAA,EACtD;AACF;","names":[]}
@@ -2,7 +2,7 @@ import {
2
2
  DEFAULT_THEME,
3
3
  applySurface,
4
4
  resolveFontFamily
5
- } from "./chunk-W4O2TX5I.js";
5
+ } from "./chunk-JHZWYRSW.js";
6
6
 
7
7
  // src/jsonForm/chooseControl.ts
8
8
  var ENUM_SEGMENTED_LIMIT = 4;
@@ -272,4 +272,4 @@ export {
272
272
  buildJsonFormTokens,
273
273
  resolveJsonFormTheme
274
274
  };
275
- //# sourceMappingURL=chunk-2PWOO4ZE.js.map
275
+ //# sourceMappingURL=chunk-VYFRI7R6.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  expectedSyllablesAt,
3
3
  wordPosAtExpectedSyllables
4
- } from "./chunk-X6DUONGT.js";
4
+ } from "./chunk-JI77MGAK.js";
5
5
 
6
6
  // src/narration/types.ts
7
7
  var DEFAULT_FEATURE_CONFIG = Object.freeze({
@@ -881,4 +881,4 @@ export {
881
881
  downsampleTrace,
882
882
  alignNarration
883
883
  };
884
- //# sourceMappingURL=chunk-CY2R2VPR.js.map
884
+ //# sourceMappingURL=chunk-XNLB57UD.js.map