@bendyline/squisq 1.1.1 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/{Doc-Cvt2lyzn.d.ts → Doc-Dwn5aHFC.d.ts} +60 -3
  2. package/dist/__tests__/dataTable.test.d.ts +2 -0
  3. package/dist/__tests__/dataTable.test.d.ts.map +1 -0
  4. package/dist/__tests__/dataTable.test.js +110 -0
  5. package/dist/__tests__/dataTable.test.js.map +1 -0
  6. package/dist/{chunk-CORGFIFU.js → chunk-KEFWM2VC.js} +1 -1
  7. package/dist/{chunk-CORGFIFU.js.map → chunk-KEFWM2VC.js.map} +1 -1
  8. package/dist/{chunk-OFU53HI7.js → chunk-QM5PKNPW.js} +1 -1
  9. package/dist/{chunk-OFU53HI7.js.map → chunk-QM5PKNPW.js.map} +1 -1
  10. package/dist/{chunk-3WBJAZZ5.js → chunk-T6WBC3ND.js} +67 -3
  11. package/dist/chunk-T6WBC3ND.js.map +1 -0
  12. package/dist/doc/templates/dataTable.d.ts +14 -0
  13. package/dist/doc/templates/dataTable.d.ts.map +1 -0
  14. package/dist/doc/templates/dataTable.js +73 -0
  15. package/dist/doc/templates/dataTable.js.map +1 -0
  16. package/dist/doc/templates/index.d.ts +1 -0
  17. package/dist/doc/templates/index.d.ts.map +1 -1
  18. package/dist/doc/templates/index.js +3 -0
  19. package/dist/doc/templates/index.js.map +1 -1
  20. package/dist/schemas/BlockTemplates.d.ts +18 -1
  21. package/dist/schemas/BlockTemplates.d.ts.map +1 -1
  22. package/dist/schemas/BlockTemplates.js.map +1 -1
  23. package/dist/schemas/Doc.d.ts +41 -1
  24. package/dist/schemas/Doc.d.ts.map +1 -1
  25. package/dist/schemas/Doc.js.map +1 -1
  26. package/dist/story/index.d.ts +17 -4
  27. package/dist/story/index.js +4 -2
  28. package/dist/{themeLibrary-VOHfPzRB.d.ts → themeLibrary-DLJtGh8-.d.ts} +1 -1
  29. package/package.json +13 -13
  30. package/src/__tests__/dataTable.test.ts +135 -0
  31. package/src/doc/templates/dataTable.ts +84 -0
  32. package/src/doc/templates/index.ts +3 -0
  33. package/src/schemas/BlockTemplates.ts +20 -1
  34. package/src/schemas/Doc.ts +43 -1
  35. package/dist/chunk-3WBJAZZ5.js.map +0 -1
@@ -718,10 +718,27 @@ interface VideoPullQuoteInput extends BaseTemplateBlock {
718
718
  license?: string;
719
719
  };
720
720
  }
721
+ /**
722
+ * Data table - renders a themed table with headers and rows.
723
+ * Ideal for structured data, comparisons, and reference information.
724
+ */
725
+ interface DataTableInput extends BaseTemplateBlock {
726
+ template: 'dataTable';
727
+ /** Optional title displayed above the table */
728
+ title?: string;
729
+ /** Header cell values */
730
+ headers: string[];
731
+ /** Data rows (array of cell value arrays) */
732
+ rows: string[][];
733
+ /** Per-column alignment */
734
+ align?: (('left' | 'right' | 'center') | null)[];
735
+ /** Color scheme for the table header */
736
+ colorScheme?: ColorScheme;
737
+ }
721
738
  /**
722
739
  * Union of all template block types.
723
740
  */
724
- type TemplateBlock = TitleBlockInput | SectionHeaderInput | StatHighlightInput | QuoteBlockInput | FactCardInput | TwoColumnInput | DateEventInput | ImageWithCaptionInput | MapBlockInput | FullBleedQuoteInput | ListBlockInput | PhotoGridInput | DefinitionCardInput | ComparisonBarInput | PullQuoteInput | VideoWithCaptionInput | VideoPullQuoteInput;
741
+ type TemplateBlock = TitleBlockInput | SectionHeaderInput | StatHighlightInput | QuoteBlockInput | FactCardInput | TwoColumnInput | DateEventInput | ImageWithCaptionInput | MapBlockInput | FullBleedQuoteInput | ListBlockInput | PhotoGridInput | DefinitionCardInput | ComparisonBarInput | PullQuoteInput | VideoWithCaptionInput | VideoPullQuoteInput | DataTableInput;
725
742
  /**
726
743
  * A block can be either a raw Block or a TemplateBlock.
727
744
  */
@@ -1043,7 +1060,7 @@ interface Block {
1043
1060
  * A visual element within a block.
1044
1061
  * Layers are composited back-to-front (first layer is background).
1045
1062
  */
1046
- type Layer = ImageLayer | TextLayer | ShapeLayer | MapLayer | VideoLayer;
1063
+ type Layer = ImageLayer | TextLayer | ShapeLayer | MapLayer | VideoLayer | TableLayer;
1047
1064
  interface BaseLayer {
1048
1065
  /** Unique identifier for this layer */
1049
1066
  id: string;
@@ -1157,6 +1174,46 @@ interface VideoLayer extends BaseLayer {
1157
1174
  license?: string;
1158
1175
  };
1159
1176
  }
1177
+ /**
1178
+ * Table layer - renders a data table with themed styling.
1179
+ * Uses foreignObject inside SVG for HTML-based table layout.
1180
+ */
1181
+ interface TableLayer extends BaseLayer {
1182
+ type: 'table';
1183
+ content: {
1184
+ /** Header cell values */
1185
+ headers: string[];
1186
+ /** Data rows (array of cell value arrays) */
1187
+ rows: string[][];
1188
+ /** Per-column alignment */
1189
+ align?: (('left' | 'right' | 'center') | null)[];
1190
+ /** Visual styling */
1191
+ style: TableLayerStyle;
1192
+ };
1193
+ }
1194
+ /**
1195
+ * Styling options for a TableLayer.
1196
+ */
1197
+ interface TableLayerStyle {
1198
+ /** Header row background color */
1199
+ headerBackground: string;
1200
+ /** Header row text color */
1201
+ headerColor: string;
1202
+ /** Body cell background color */
1203
+ cellBackground: string;
1204
+ /** Body cell text color */
1205
+ cellColor: string;
1206
+ /** Border/divider color */
1207
+ borderColor: string;
1208
+ /** Font size in pixels */
1209
+ fontSize: number;
1210
+ /** Font family */
1211
+ fontFamily?: string;
1212
+ /** Header font family (falls back to fontFamily) */
1213
+ headerFontFamily?: string;
1214
+ /** Corner radius for the table container */
1215
+ borderRadius?: number;
1216
+ }
1160
1217
  /**
1161
1218
  * Available map tile styles from free/open-source providers.
1162
1219
  */
@@ -1360,4 +1417,4 @@ declare function getCaptionAtTime(captions: CaptionTrack | undefined, time: numb
1360
1417
  */
1361
1418
  declare function validateDoc(script: Doc): string[];
1362
1419
 
1363
- export { type TemplateContext as $, type AccentImage as A, type Block as B, type CaptionPhrase as C, DEFAULT_DOC_FONT as D, type PersistentLayer as E, type FactCardInput as F, type GradientBackgroundConfig as G, type PersistentLayerConfig as H, type ImageBackgroundConfig as I, type PersistentLayerTemplate as J, type PersistentLayerTemplateConfig as K, type Layer as L, type MapBlockInput as M, type PersistentLayerTemplateType as N, type PhotoGridInput as O, type PatternBackgroundConfig as P, type Position as Q, type ProgressIndicatorConfig as R, type PullQuoteInput as S, type QuoteBlockInput as T, type RenderStyle as U, type SectionHeaderInput as V, type ShapeLayer as W, type SolidBackgroundConfig as X, type StartBlockConfig as Y, type StatHighlightInput as Z, type TemplateBlock as _, type AccentPosition as a, type TemplateFunction as a0, type TemplateRegistry as a1, type TextLayer as a2, type TextStyle as a3, type Theme as a4, type ThemeColorPalette as a5, type ThemeColorScheme as a6, type ThemeStyle as a7, type ThemeTypography as a8, type TitleBlockInput as a9, scaledFontSize$1 as aA, scaledFontSize as aB, validateDoc as aC, type TitleCaptionConfig as aa, type Transition as ab, type TransitionType as ac, type TwoColumnInput as ad, VIEWPORT_PRESETS as ae, type VideoLayer as af, type VideoPullQuoteInput as ag, type VideoWithCaptionInput as ah, type ViewportConfig as ai, type ViewportOrientation as aj, type ViewportPreset as ak, calculateDuration as al, calculateFontScale as am, createTemplateContext as an, createTheme as ao, getAspectRatioString as ap, getBlockAtTime as aq, getCaptionAtTime as ar, getLayoutHints as as, getSafeTextBounds as at, getSegmentAtTime as au, getTwoColumnPositions as av, getViewport as aw, getViewportOrientation as ax, isPersistentLayerTemplate as ay, isTemplateBlock as az, type Animation as b, type AnimationType as c, type AudioBookmark as d, type AudioSegment as e, type AudioTimingData as f, type AudioTrack as g, type CaptionTrack as h, type CaptionWord as i, type ColorScheme as j, type ComparisonBarInput as k, type CornerBrandingConfig as l, DEFAULT_TITLE_FONT as m, type DateEventInput as n, type DeepPartial as o, type DefinitionCardInput as p, type Doc as q, type DocBlock as r, type FullBleedQuoteInput as s, type ImageLayer as t, type ImageWithCaptionInput as u, type LayoutHints as v, type ListBlockInput as w, type MapLayer as x, type MapMarker as y, type MapTileStyle as z };
1420
+ export { type TableLayer as $, type AccentImage as A, type Block as B, type CaptionPhrase as C, DEFAULT_DOC_FONT as D, type MapTileStyle as E, type FactCardInput as F, type GradientBackgroundConfig as G, type PersistentLayer as H, type ImageBackgroundConfig as I, type PersistentLayerConfig as J, type PersistentLayerTemplate as K, type Layer as L, type MapBlockInput as M, type PersistentLayerTemplateConfig as N, type PersistentLayerTemplateType as O, type PatternBackgroundConfig as P, type PhotoGridInput as Q, type Position as R, type ProgressIndicatorConfig as S, type PullQuoteInput as T, type QuoteBlockInput as U, type RenderStyle as V, type SectionHeaderInput as W, type ShapeLayer as X, type SolidBackgroundConfig as Y, type StartBlockConfig as Z, type StatHighlightInput as _, type AccentPosition as a, type TableLayerStyle as a0, type TemplateBlock as a1, type TemplateContext as a2, type TemplateFunction as a3, type TemplateRegistry as a4, type TextLayer as a5, type TextStyle as a6, type Theme as a7, type ThemeColorPalette as a8, type ThemeColorScheme as a9, getViewportOrientation as aA, isPersistentLayerTemplate as aB, isTemplateBlock as aC, scaledFontSize$1 as aD, scaledFontSize as aE, validateDoc as aF, type ThemeStyle as aa, type ThemeTypography as ab, type TitleBlockInput as ac, type TitleCaptionConfig as ad, type Transition as ae, type TransitionType as af, type TwoColumnInput as ag, VIEWPORT_PRESETS as ah, type VideoLayer as ai, type VideoPullQuoteInput as aj, type VideoWithCaptionInput as ak, type ViewportConfig as al, type ViewportOrientation as am, type ViewportPreset as an, calculateDuration as ao, calculateFontScale as ap, createTemplateContext as aq, createTheme as ar, getAspectRatioString as as, getBlockAtTime as at, getCaptionAtTime as au, getLayoutHints as av, getSafeTextBounds as aw, getSegmentAtTime as ax, getTwoColumnPositions as ay, getViewport as az, type Animation as b, type AnimationType as c, type AudioBookmark as d, type AudioSegment as e, type AudioTimingData as f, type AudioTrack as g, type CaptionTrack as h, type CaptionWord as i, type ColorScheme as j, type ComparisonBarInput as k, type CornerBrandingConfig as l, DEFAULT_TITLE_FONT as m, type DataTableInput as n, type DateEventInput as o, type DeepPartial as p, type DefinitionCardInput as q, type Doc as r, type DocBlock as s, type FullBleedQuoteInput as t, type ImageLayer as u, type ImageWithCaptionInput as v, type LayoutHints as w, type ListBlockInput as x, type MapLayer as y, type MapMarker as z };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=dataTable.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dataTable.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/dataTable.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,110 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { getLayers } from '../doc/getLayers.js';
3
+ import { DEFAULT_THEME } from '../schemas/themeLibrary.js';
4
+ import { VIEWPORT_PRESETS } from '../schemas/Viewport.js';
5
+ // ---------------------------------------------------------------------------
6
+ // Helpers
7
+ // ---------------------------------------------------------------------------
8
+ function makeDataTableBlock(overrides = {}) {
9
+ return {
10
+ template: 'dataTable',
11
+ id: 'dt-1',
12
+ duration: 5,
13
+ audioSegment: 0,
14
+ headers: ['Name', 'Value'],
15
+ rows: [
16
+ ['Alpha', '100'],
17
+ ['Beta', '200'],
18
+ ],
19
+ ...overrides,
20
+ };
21
+ }
22
+ const defaultContext = {
23
+ theme: DEFAULT_THEME,
24
+ viewport: VIEWPORT_PRESETS.landscape,
25
+ blockIndex: 0,
26
+ totalBlocks: 5,
27
+ };
28
+ // ---------------------------------------------------------------------------
29
+ // Tests
30
+ // ---------------------------------------------------------------------------
31
+ describe('dataTable template', () => {
32
+ it('produces layers including a table layer', () => {
33
+ const layers = getLayers(makeDataTableBlock(), defaultContext);
34
+ expect(layers.length).toBeGreaterThan(0);
35
+ const tableLayer = layers.find((l) => l.type === 'table');
36
+ expect(tableLayer).toBeDefined();
37
+ });
38
+ it('table layer contains the correct headers', () => {
39
+ const layers = getLayers(makeDataTableBlock(), defaultContext);
40
+ const tableLayer = layers.find((l) => l.type === 'table');
41
+ expect(tableLayer.content.headers).toEqual(['Name', 'Value']);
42
+ });
43
+ it('table layer contains the correct rows', () => {
44
+ const layers = getLayers(makeDataTableBlock(), defaultContext);
45
+ const tableLayer = layers.find((l) => l.type === 'table');
46
+ expect(tableLayer.content.rows).toEqual([
47
+ ['Alpha', '100'],
48
+ ['Beta', '200'],
49
+ ]);
50
+ });
51
+ it('includes a title text layer when title is provided', () => {
52
+ const layers = getLayers(makeDataTableBlock({ title: 'My Table' }), defaultContext);
53
+ const textLayers = layers.filter((l) => l.type === 'text');
54
+ expect(textLayers.length).toBeGreaterThanOrEqual(1);
55
+ const titleLayer = textLayers.find((l) => l.type === 'text' && l.content.text === 'My Table');
56
+ expect(titleLayer).toBeDefined();
57
+ });
58
+ it('omits title layer when no title is given', () => {
59
+ const layers = getLayers(makeDataTableBlock({ title: undefined }), defaultContext);
60
+ const textLayers = layers.filter((l) => l.type === 'text');
61
+ // Should have no text layers (only bg + table)
62
+ expect(textLayers.length).toBe(0);
63
+ });
64
+ it('includes a background layer', () => {
65
+ const layers = getLayers(makeDataTableBlock(), defaultContext);
66
+ // Background is the first layer (shape with gradient fill)
67
+ expect(['shape', 'image']).toContain(layers[0].type);
68
+ });
69
+ it('passes column alignment to the table layer', () => {
70
+ const layers = getLayers(makeDataTableBlock({ align: ['left', 'right'] }), defaultContext);
71
+ const tableLayer = layers.find((l) => l.type === 'table');
72
+ expect(tableLayer.content.align).toEqual(['left', 'right']);
73
+ });
74
+ it('applies theme colors to table styling', () => {
75
+ const layers = getLayers(makeDataTableBlock(), defaultContext);
76
+ const tableLayer = layers.find((l) => l.type === 'table');
77
+ const style = tableLayer.content.style;
78
+ // Style fields should be populated strings/numbers
79
+ expect(style.headerBackground).toBeTruthy();
80
+ expect(style.headerColor).toBeTruthy();
81
+ expect(style.cellColor).toBeTruthy();
82
+ expect(style.borderColor).toBeTruthy();
83
+ expect(typeof style.fontSize).toBe('number');
84
+ expect(style.fontSize).toBeGreaterThan(0);
85
+ });
86
+ it('adjusts table position when title is present vs absent', () => {
87
+ const withTitle = getLayers(makeDataTableBlock({ title: 'Title' }), defaultContext);
88
+ const withoutTitle = getLayers(makeDataTableBlock({ title: undefined }), defaultContext);
89
+ const tableWithTitle = withTitle.find((l) => l.type === 'table');
90
+ const tableWithoutTitle = withoutTitle.find((l) => l.type === 'table');
91
+ // Table should be positioned lower when a title is present
92
+ expect(tableWithTitle.position.y).not.toBe(tableWithoutTitle.position.y);
93
+ });
94
+ it('works with portrait viewport', () => {
95
+ const portraitContext = {
96
+ ...defaultContext,
97
+ viewport: VIEWPORT_PRESETS.portrait,
98
+ };
99
+ const layers = getLayers(makeDataTableBlock(), portraitContext);
100
+ expect(layers.length).toBeGreaterThan(0);
101
+ const tableLayer = layers.find((l) => l.type === 'table');
102
+ expect(tableLayer).toBeDefined();
103
+ });
104
+ it('handles empty rows gracefully', () => {
105
+ const layers = getLayers(makeDataTableBlock({ headers: ['A', 'B'], rows: [] }), defaultContext);
106
+ const tableLayer = layers.find((l) => l.type === 'table');
107
+ expect(tableLayer.content.rows).toEqual([]);
108
+ });
109
+ });
110
+ //# sourceMappingURL=dataTable.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dataTable.test.js","sourceRoot":"","sources":["../../src/__tests__/dataTable.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAiB,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAI1D,8EAA8E;AAC9E,UAAU;AACV,8EAA8E;AAE9E,SAAS,kBAAkB,CAAC,YAAqC,EAAE;IACjE,OAAO;QACL,QAAQ,EAAE,WAAW;QACrB,EAAE,EAAE,MAAM;QACV,QAAQ,EAAE,CAAC;QACX,YAAY,EAAE,CAAC;QACf,OAAO,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC;QAC1B,IAAI,EAAE;YACJ,CAAC,OA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,CAAC,CAAC;QAChE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;QACzC,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC;QAC1D,MAAM,CAAC,UAAU,CAAC,CAAC,WAAW,EAAE,CAAC;IACnC,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,+BAA+B,EAAE,GAAG,EAAE;QACvC,MAAM,MAAM,GAAG,SAAS,CAAC,kBAAkB,CAAC,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,EAAE,cAAc,CAAC,CAAC;QAChG,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,OAAO,CAAe,CAAC;QACxE,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAC9C,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -89,4 +89,4 @@ export {
89
89
  validateDoc,
90
90
  createTheme
91
91
  };
92
- //# sourceMappingURL=chunk-CORGFIFU.js.map
92
+ //# sourceMappingURL=chunk-KEFWM2VC.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schemas/Doc.ts","../src/schemas/Theme.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\n// ============================================\n// Core Types\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) */\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 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/**\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 */\nexport interface Block {\n /** Unique identifier for this block */\n id: string;\n\n /** When this block appears (seconds from start) */\n startTime: number;\n\n /** How long this block is visible (seconds) */\n duration: number;\n\n /** Which audio segment this block belongs to (0-indexed) */\n audioSegment: 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 `getLayers()` 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 /** Template name that generated this block (for debugging) */\n template?: 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 markdown directives.\n * For example, `### Data Section {template=chart colorScheme=blue}`\n * would produce `{ template: 'chart', colorScheme: 'blue' }`.\n * Allows per-block customization of template selection and parameters.\n */\n templateOverrides?: Record<string, string>;\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 = ImageLayer | TextLayer | ShapeLayer | MapLayer | VideoLayer;\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 * 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 };\n}\n\n/**\n * Text layer - displays text with styling.\n */\nexport interface TextLayer extends BaseLayer {\n type: 'text';\n content: {\n /** Text to display (supports \\n for line breaks) */\n text: string;\n /** Text styling */\n style: TextStyle;\n };\n}\n\n/**\n * Shape layer - simple geometric shapes for visual accents.\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 /** Stroke color */\n stroke?: string;\n /** Stroke width in pixels */\n strokeWidth?: number;\n /** Corner radius for rect */\n borderRadius?: number;\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 /** 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 * 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 /** Text color (CSS color) */\n color: string;\n /** Text alignment */\n textAlign?: 'left' | 'center' | 'right';\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 /** 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 * Transition between blocks.\n */\nexport interface Transition {\n /** Transition type */\n type: TransitionType;\n /** Duration in seconds */\n duration: number;\n}\n\nexport type TransitionType =\n | 'cut' // Instant switch\n | 'fade' // Cross-fade\n | 'dissolve' // Soft dissolve\n | 'slideLeft' // New block enters from right\n | 'slideRight'; // New block enters from left\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 */\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/**\n * Validate a Doc for completeness.\n */\nexport function validateDoc(script: Doc): string[] {\n const errors: string[] = [];\n\n if (!script.articleId) {\n errors.push('Missing articleId');\n }\n\n if (!script.blocks || script.blocks.length === 0) {\n errors.push('No blocks defined');\n }\n\n if (!script.audio || !script.audio.segments || script.audio.segments.length === 0) {\n errors.push('No audio segments defined');\n }\n\n // Check for gaps in block coverage\n const totalDuration = script.duration;\n let covered = 0;\n for (const block of script.blocks) {\n if (block.startTime > covered + 0.1) {\n errors.push(`Gap in blocks: ${covered}s to ${block.startTime}s`);\n }\n covered = Math.max(covered, block.startTime + block.duration);\n }\n\n if (covered < totalDuration - 0.1) {\n errors.push(`Blocks end at ${covered}s but audio is ${totalDuration}s`);\n }\n\n return errors;\n}\n","/**\n * Theme System\n *\n * A Theme bundles color palette, typography, visual style, render-style\n * algorithm, and per-block color schemes into one JSON-serializable object.\n * Builders choose a theme from the built-in library or create a custom one\n * via `createTheme(base, overrides)`.\n *\n * Design principles:\n * - Fully JSON-serializable (no functions) — storable in config / APIs.\n * - Doc carries an optional `themeId` pointer; resolution happens at render time.\n * - `createTheme` deep-merges a base theme with partial overrides.\n */\n\nimport type { LayoutHints } from './LayoutStrategy.js';\nimport type { AnimationType, TransitionType } from './Doc.js';\nimport type { PersistentLayerConfig } from './BlockTemplates.js';\n\n// ============================================\n// Color Palette\n// ============================================\n\n/**\n * Core color palette for a theme. Every color is a CSS color string.\n */\nexport interface ThemeColorPalette {\n /** Primary accent color */\n primary: string;\n /** Secondary accent color */\n secondary: string;\n /** Background color (typically dark) */\n background: string;\n /** Lighter background for contrast panels */\n backgroundLight: string;\n /** Main text color */\n text: string;\n /** Muted/secondary text color */\n textMuted: string;\n /** Highlight/emphasis color */\n highlight: string;\n /** Warning/alert color */\n warning: string;\n}\n\n/**\n * A named color scheme used by templates for per-block color variation\n * (e.g., statHighlight or sectionHeader).\n */\nexport interface ThemeColorScheme {\n /** Background fill */\n bg: string;\n /** Primary text tint */\n text: string;\n /** Accent / secondary tint */\n accent: string;\n}\n\n// ============================================\n// Typography\n// ============================================\n\n/**\n * Typography settings for a theme.\n */\nexport interface ThemeTypography {\n /** Font family for body / description text */\n bodyFontFamily: string;\n /** Font family for titles and headings */\n titleFontFamily: string;\n /** Font family for code / monospaced text (optional) */\n monoFontFamily?: string;\n /** Multiplier applied to LayoutHints.titleScale (default 1.0) */\n titleScale?: number;\n /** Multiplier applied to LayoutHints.bodyScale (default 1.0) */\n bodyScale?: number;\n /** Default body line height (default 1.4) */\n lineHeight?: number;\n /** Default title line height */\n titleLineHeight?: number;\n /** Default title font weight */\n titleWeight?: 'normal' | 'bold';\n}\n\n// ============================================\n// Visual Style\n// ============================================\n\n/**\n * Global visual-style knobs that templates consult.\n */\nexport interface ThemeStyle {\n /** Default border radius for cards / shapes (px) */\n borderRadius?: number;\n /** Whether templates should default to text shadows */\n textShadow?: boolean;\n /** Darkness of overlay on image-backed blocks (0–1) */\n overlayOpacity?: number;\n /** Multiplier on all animation durations (1.0 = normal, <1 faster, >1 slower) */\n animationSpeed?: number;\n /** Default horizontal padding for text (percentage string, e.g. \"5%\") */\n blockPadding?: string;\n}\n\n// ============================================\n// Render Style\n// ============================================\n\n/**\n * Render-style algorithm preset. Controls layout tweaks, default animations,\n * transitions, and per-template behavioral hints.\n */\nexport interface RenderStyle {\n /** Identifier for this algorithmic approach (e.g. \"documentary\", \"magazine\") */\n name: string;\n /** Partial overrides merged onto the orientation-based LayoutHints */\n layoutOverrides?: Partial<LayoutHints>;\n /** Default entrance animation for text layers */\n defaultTextAnimation?: AnimationType;\n /** Default animation for background / image layers */\n defaultImageAnimation?: AnimationType;\n /** Whether to apply Ken Burns ambient motion to images by default */\n ambientMotion?: boolean;\n /** Default block-to-block transition */\n defaultTransition?: { type: TransitionType; duration?: number };\n /**\n * Per-template behavioral hints. Keys are template names, values are\n * string/number/boolean maps that templates can read to vary their output.\n *\n * @example\n * ```\n * { statHighlight: { entrance: 'dramatic' }, titleBlock: { showAccentLine: false } }\n * ```\n */\n templateHints?: Record<string, Record<string, string | number | boolean>>;\n}\n\n// ============================================\n// Theme\n// ============================================\n\n/**\n * A complete, JSON-serializable theme definition.\n */\nexport interface Theme {\n /** Unique identifier (e.g. \"documentary\") */\n id: string;\n /** Human-readable display name */\n name: string;\n /** Short description for theme pickers */\n description?: string;\n /** Color palette */\n colors: ThemeColorPalette;\n /** Typography settings */\n typography: ThemeTypography;\n /** Global visual-style knobs */\n style: ThemeStyle;\n /** Algorithmic render-style preset */\n renderStyle: RenderStyle;\n /**\n * Named color schemes for per-block color variation.\n * Templates reference these by name (e.g. \"blue\", \"warm\").\n */\n colorSchemes: Record<string, ThemeColorScheme>;\n /** Optional persistent layers baked into the theme */\n persistentLayers?: PersistentLayerConfig;\n}\n\n// ============================================\n// Deep-Partial helper type\n// ============================================\n\n/**\n * Recursively makes every property optional.\n */\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];\n};\n\n// ============================================\n// Helpers\n// ============================================\n\n/**\n * Deep-merge `source` into `target`, returning a new object.\n * Arrays are replaced wholesale (not concatenated).\n */\nfunction deepMerge<T extends Record<string, unknown>>(target: T, source: DeepPartial<T>): T {\n const result = { ...target } as Record<string, unknown>;\n for (const key of Object.keys(source)) {\n const srcVal = (source as Record<string, unknown>)[key];\n const tgtVal = (target as Record<string, unknown>)[key];\n if (\n srcVal !== null &&\n srcVal !== undefined &&\n typeof srcVal === 'object' &&\n !Array.isArray(srcVal) &&\n tgtVal !== null &&\n tgtVal !== undefined &&\n typeof tgtVal === 'object' &&\n !Array.isArray(tgtVal)\n ) {\n result[key] = deepMerge(\n tgtVal as Record<string, unknown>,\n srcVal as DeepPartial<Record<string, unknown>>,\n );\n } else if (srcVal !== undefined) {\n result[key] = srcVal;\n }\n }\n return result as T;\n}\n\n/**\n * Create a new theme by deep-merging overrides onto a base theme.\n * The returned theme gets its own `id` if one is provided in overrides,\n * otherwise keeps the base theme's `id` suffixed with \"-custom\".\n *\n * @example\n * ```ts\n * const myTheme = createTheme(THEMES.documentary, {\n * colors: { primary: '#ff0000' },\n * typography: { bodyFontFamily: '\"Inter\", sans-serif' },\n * });\n * ```\n */\nexport function createTheme(base: Theme, overrides: DeepPartial<Theme>): Theme {\n const merged = deepMerge(\n base as unknown as Record<string, unknown>,\n overrides as DeepPartial<Record<string, unknown>>,\n ) as unknown as Theme;\n if (!overrides.id && merged.id === base.id) {\n merged.id = `${base.id}-custom`;\n }\n return merged;\n}\n"],"mappings":";AAiiBO,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;AACA,SAAO,MAAM,SAAS,SAAS;AACjC;AAKO,SAAS,eAAe,QAAiB,MAA4B;AAC1E,WAAS,IAAI,OAAO,SAAS,GAAG,KAAK,GAAG,KAAK;AAC3C,UAAM,QAAQ,OAAO,CAAC;AACtB,QAAI,QAAQ,MAAM,aAAa,OAAO,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ClB,CAAC,MAAM,QAAQ,MAAM,KACrB,WAAW,QACX,WAAW,UACX,OAAO,WAAW,YAClB,CAAC,MAAM,QAAQ,MAAM,GACrB;AACA,aAAO,GAAG,IAAI;AAAA,QACZ;AAAA,QACA;AAAA,MACF;AAAA,IACF,WAAW,WAAW,QAAW;AAC/B,aAAO,GAAG,IAAI;AAAA,IAChB;AAAA,EACF;AACA,SAAO;AACT;AAeO,SAAS,YAAY,MAAa,WAAsC;AAC7E,QAAM,SAAS;AAAA,IACb;AAAA,IACA;AAAA,EACF;AACA,MAAI,CAAC,UAAU,MAAM,OAAO,OAAO,KAAK,IAAI;AAC1C,WAAO,KAAK,GAAG,KAAK,EAAE;AAAA,EACxB;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/schemas/Doc.ts","../src/schemas/Theme.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\n// ============================================\n// Core Types\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) */\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 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/**\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 */\nexport interface Block {\n /** Unique identifier for this block */\n id: string;\n\n /** When this block appears (seconds from start) */\n startTime: number;\n\n /** How long this block is visible (seconds) */\n duration: number;\n\n /** Which audio segment this block belongs to (0-indexed) */\n audioSegment: 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 `getLayers()` 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 /** Template name that generated this block (for debugging) */\n template?: 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 markdown directives.\n * For example, `### Data Section {template=chart colorScheme=blue}`\n * would produce `{ template: 'chart', colorScheme: 'blue' }`.\n * Allows per-block customization of template selection and parameters.\n */\n templateOverrides?: Record<string, string>;\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 = ImageLayer | TextLayer | ShapeLayer | MapLayer | VideoLayer | TableLayer;\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 * 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 };\n}\n\n/**\n * Text layer - displays text with styling.\n */\nexport interface TextLayer extends BaseLayer {\n type: 'text';\n content: {\n /** Text to display (supports \\n for line breaks) */\n text: string;\n /** Text styling */\n style: TextStyle;\n };\n}\n\n/**\n * Shape layer - simple geometric shapes for visual accents.\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 /** Stroke color */\n stroke?: string;\n /** Stroke width in pixels */\n strokeWidth?: number;\n /** Corner radius for rect */\n borderRadius?: number;\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 /** 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 * 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 /** Text color (CSS color) */\n color: string;\n /** Text alignment */\n textAlign?: 'left' | 'center' | 'right';\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 /** 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 * Transition between blocks.\n */\nexport interface Transition {\n /** Transition type */\n type: TransitionType;\n /** Duration in seconds */\n duration: number;\n}\n\nexport type TransitionType =\n | 'cut' // Instant switch\n | 'fade' // Cross-fade\n | 'dissolve' // Soft dissolve\n | 'slideLeft' // New block enters from right\n | 'slideRight'; // New block enters from left\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 */\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/**\n * Validate a Doc for completeness.\n */\nexport function validateDoc(script: Doc): string[] {\n const errors: string[] = [];\n\n if (!script.articleId) {\n errors.push('Missing articleId');\n }\n\n if (!script.blocks || script.blocks.length === 0) {\n errors.push('No blocks defined');\n }\n\n if (!script.audio || !script.audio.segments || script.audio.segments.length === 0) {\n errors.push('No audio segments defined');\n }\n\n // Check for gaps in block coverage\n const totalDuration = script.duration;\n let covered = 0;\n for (const block of script.blocks) {\n if (block.startTime > covered + 0.1) {\n errors.push(`Gap in blocks: ${covered}s to ${block.startTime}s`);\n }\n covered = Math.max(covered, block.startTime + block.duration);\n }\n\n if (covered < totalDuration - 0.1) {\n errors.push(`Blocks end at ${covered}s but audio is ${totalDuration}s`);\n }\n\n return errors;\n}\n","/**\n * Theme System\n *\n * A Theme bundles color palette, typography, visual style, render-style\n * algorithm, and per-block color schemes into one JSON-serializable object.\n * Builders choose a theme from the built-in library or create a custom one\n * via `createTheme(base, overrides)`.\n *\n * Design principles:\n * - Fully JSON-serializable (no functions) — storable in config / APIs.\n * - Doc carries an optional `themeId` pointer; resolution happens at render time.\n * - `createTheme` deep-merges a base theme with partial overrides.\n */\n\nimport type { LayoutHints } from './LayoutStrategy.js';\nimport type { AnimationType, TransitionType } from './Doc.js';\nimport type { PersistentLayerConfig } from './BlockTemplates.js';\n\n// ============================================\n// Color Palette\n// ============================================\n\n/**\n * Core color palette for a theme. Every color is a CSS color string.\n */\nexport interface ThemeColorPalette {\n /** Primary accent color */\n primary: string;\n /** Secondary accent color */\n secondary: string;\n /** Background color (typically dark) */\n background: string;\n /** Lighter background for contrast panels */\n backgroundLight: string;\n /** Main text color */\n text: string;\n /** Muted/secondary text color */\n textMuted: string;\n /** Highlight/emphasis color */\n highlight: string;\n /** Warning/alert color */\n warning: string;\n}\n\n/**\n * A named color scheme used by templates for per-block color variation\n * (e.g., statHighlight or sectionHeader).\n */\nexport interface ThemeColorScheme {\n /** Background fill */\n bg: string;\n /** Primary text tint */\n text: string;\n /** Accent / secondary tint */\n accent: string;\n}\n\n// ============================================\n// Typography\n// ============================================\n\n/**\n * Typography settings for a theme.\n */\nexport interface ThemeTypography {\n /** Font family for body / description text */\n bodyFontFamily: string;\n /** Font family for titles and headings */\n titleFontFamily: string;\n /** Font family for code / monospaced text (optional) */\n monoFontFamily?: string;\n /** Multiplier applied to LayoutHints.titleScale (default 1.0) */\n titleScale?: number;\n /** Multiplier applied to LayoutHints.bodyScale (default 1.0) */\n bodyScale?: number;\n /** Default body line height (default 1.4) */\n lineHeight?: number;\n /** Default title line height */\n titleLineHeight?: number;\n /** Default title font weight */\n titleWeight?: 'normal' | 'bold';\n}\n\n// ============================================\n// Visual Style\n// ============================================\n\n/**\n * Global visual-style knobs that templates consult.\n */\nexport interface ThemeStyle {\n /** Default border radius for cards / shapes (px) */\n borderRadius?: number;\n /** Whether templates should default to text shadows */\n textShadow?: boolean;\n /** Darkness of overlay on image-backed blocks (0–1) */\n overlayOpacity?: number;\n /** Multiplier on all animation durations (1.0 = normal, <1 faster, >1 slower) */\n animationSpeed?: number;\n /** Default horizontal padding for text (percentage string, e.g. \"5%\") */\n blockPadding?: string;\n}\n\n// ============================================\n// Render Style\n// ============================================\n\n/**\n * Render-style algorithm preset. Controls layout tweaks, default animations,\n * transitions, and per-template behavioral hints.\n */\nexport interface RenderStyle {\n /** Identifier for this algorithmic approach (e.g. \"documentary\", \"magazine\") */\n name: string;\n /** Partial overrides merged onto the orientation-based LayoutHints */\n layoutOverrides?: Partial<LayoutHints>;\n /** Default entrance animation for text layers */\n defaultTextAnimation?: AnimationType;\n /** Default animation for background / image layers */\n defaultImageAnimation?: AnimationType;\n /** Whether to apply Ken Burns ambient motion to images by default */\n ambientMotion?: boolean;\n /** Default block-to-block transition */\n defaultTransition?: { type: TransitionType; duration?: number };\n /**\n * Per-template behavioral hints. Keys are template names, values are\n * string/number/boolean maps that templates can read to vary their output.\n *\n * @example\n * ```\n * { statHighlight: { entrance: 'dramatic' }, titleBlock: { showAccentLine: false } }\n * ```\n */\n templateHints?: Record<string, Record<string, string | number | boolean>>;\n}\n\n// ============================================\n// Theme\n// ============================================\n\n/**\n * A complete, JSON-serializable theme definition.\n */\nexport interface Theme {\n /** Unique identifier (e.g. \"documentary\") */\n id: string;\n /** Human-readable display name */\n name: string;\n /** Short description for theme pickers */\n description?: string;\n /** Color palette */\n colors: ThemeColorPalette;\n /** Typography settings */\n typography: ThemeTypography;\n /** Global visual-style knobs */\n style: ThemeStyle;\n /** Algorithmic render-style preset */\n renderStyle: RenderStyle;\n /**\n * Named color schemes for per-block color variation.\n * Templates reference these by name (e.g. \"blue\", \"warm\").\n */\n colorSchemes: Record<string, ThemeColorScheme>;\n /** Optional persistent layers baked into the theme */\n persistentLayers?: PersistentLayerConfig;\n}\n\n// ============================================\n// Deep-Partial helper type\n// ============================================\n\n/**\n * Recursively makes every property optional.\n */\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];\n};\n\n// ============================================\n// Helpers\n// ============================================\n\n/**\n * Deep-merge `source` into `target`, returning a new object.\n * Arrays are replaced wholesale (not concatenated).\n */\nfunction deepMerge<T extends Record<string, unknown>>(target: T, source: DeepPartial<T>): T {\n const result = { ...target } as Record<string, unknown>;\n for (const key of Object.keys(source)) {\n const srcVal = (source as Record<string, unknown>)[key];\n const tgtVal = (target as Record<string, unknown>)[key];\n if (\n srcVal !== null &&\n srcVal !== undefined &&\n typeof srcVal === 'object' &&\n !Array.isArray(srcVal) &&\n tgtVal !== null &&\n tgtVal !== undefined &&\n typeof tgtVal === 'object' &&\n !Array.isArray(tgtVal)\n ) {\n result[key] = deepMerge(\n tgtVal as Record<string, unknown>,\n srcVal as DeepPartial<Record<string, unknown>>,\n );\n } else if (srcVal !== undefined) {\n result[key] = srcVal;\n }\n }\n return result as T;\n}\n\n/**\n * Create a new theme by deep-merging overrides onto a base theme.\n * The returned theme gets its own `id` if one is provided in overrides,\n * otherwise keeps the base theme's `id` suffixed with \"-custom\".\n *\n * @example\n * ```ts\n * const myTheme = createTheme(THEMES.documentary, {\n * colors: { primary: '#ff0000' },\n * typography: { bodyFontFamily: '\"Inter\", sans-serif' },\n * });\n * ```\n */\nexport function createTheme(base: Theme, overrides: DeepPartial<Theme>): Theme {\n const merged = deepMerge(\n base as unknown as Record<string, unknown>,\n overrides as DeepPartial<Record<string, unknown>>,\n ) as unknown as Theme;\n if (!overrides.id && merged.id === base.id) {\n merged.id = `${base.id}-custom`;\n }\n return merged;\n}\n"],"mappings":";AA2kBO,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;AACA,SAAO,MAAM,SAAS,SAAS;AACjC;AAKO,SAAS,eAAe,QAAiB,MAA4B;AAC1E,WAAS,IAAI,OAAO,SA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AAU,OAAmC,GAAG;AACtD,UAAM,SAAU,OAAmC,GAAG;AACtD,QACE,WAAW,QACX,WAAW,UACX,OAAO,WAAW,YAClB,CAAC,MAAM,QAAQ,MAAM,KACrB,WAAW,QACX,WAAW,UACX,OAAO,WAAW,YAClB,CAAC,MAAM,QAAQ,MAAM,GACrB;AACA,aAAO,GAAG,IAAI;AAAA,QACZ;AAAA,QACA;AAAA,MACF;AAAA,IACF,WAAW,WAAW,QAAW;AAC/B,aAAO,GAAG,IAAI;AAAA,IAChB;AAAA,EACF;AACA,SAAO;AACT;AAeO,SAAS,YAAY,MAAa,WAAsC;AAC7E,QAAM,SAAS;AAAA,IACb;AAAA,IACA;AAAA,EACF;AACA,MAAI,CAAC,UAAU,MAAM,OAAO,OAAO,KAAK,IAAI;AAC1C,WAAO,KAAK,GAAG,KAAK,EAAE;AAAA,EACxB;AACA,SAAO;AACT;","names":[]}
@@ -162,4 +162,4 @@ export {
162
162
  scaledFontSize2,
163
163
  isPersistentLayerTemplate
164
164
  };
165
- //# sourceMappingURL=chunk-OFU53HI7.js.map
165
+ //# sourceMappingURL=chunk-QM5PKNPW.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schemas/Viewport.ts","../src/schemas/LayoutStrategy.ts","../src/schemas/BlockTemplates.ts"],"sourcesContent":["/**\n * Viewport Configuration\n *\n * Defines viewport dimensions for doc rendering across different aspect ratios.\n * Templates use this configuration to adapt their layouts appropriately.\n *\n * Supported aspect ratios:\n * - landscape (16:9) - Default, standard video/presentation format\n * - portrait (9:16) - Vertical video, mobile stories\n * - square (1:1) - Social media posts\n * - standard (4:3) - Legacy presentation format\n */\n\n/**\n * Viewport configuration for doc rendering.\n */\nexport interface ViewportConfig {\n /** Canonical width in virtual pixels */\n width: number;\n /** Canonical height in virtual pixels */\n height: number;\n /** Human-readable name for debugging/display */\n name: string;\n}\n\n/**\n * Standard viewport presets for common aspect ratios.\n */\nexport const VIEWPORT_PRESETS = {\n /** 16:9 landscape (default, 1080p) */\n landscape: { width: 1920, height: 1080, name: '16:9 Landscape' },\n /** 9:16 portrait (vertical video, stories) */\n portrait: { width: 1080, height: 1920, name: '9:16 Portrait' },\n /** 1:1 square (social media) */\n square: { width: 1080, height: 1080, name: '1:1 Square' },\n /** 4:3 standard (legacy) */\n standard: { width: 1440, height: 1080, name: '4:3 Standard' },\n} as const;\n\n/**\n * Viewport preset name.\n */\nexport type ViewportPreset = keyof typeof VIEWPORT_PRESETS;\n\n/**\n * Viewport orientation derived from aspect ratio.\n */\nexport type ViewportOrientation = 'landscape' | 'portrait' | 'square';\n\n/**\n * Get a viewport configuration from a preset name or return the config if already a ViewportConfig.\n */\nexport function getViewport(viewport: ViewportPreset | ViewportConfig): ViewportConfig {\n if (typeof viewport === 'string') {\n return VIEWPORT_PRESETS[viewport];\n }\n return viewport;\n}\n\n/**\n * Calculate font scale factor for a viewport.\n * Based on diagonal pixels relative to 1080p landscape reference.\n * This ensures text remains readable across different viewport sizes.\n */\nconst REFERENCE_DIAGONAL = Math.sqrt(1920 * 1920 + 1080 * 1080); // ~2203\n\nexport function calculateFontScale(viewport: ViewportConfig): number {\n const currentDiagonal = Math.sqrt(\n viewport.width * viewport.width + viewport.height * viewport.height,\n );\n return currentDiagonal / REFERENCE_DIAGONAL;\n}\n\n/**\n * Determine if viewport is landscape, portrait, or square.\n */\nexport function getViewportOrientation(viewport: ViewportConfig): ViewportOrientation {\n const ratio = viewport.width / viewport.height;\n // Allow small tolerance for \"square\" classification\n if (Math.abs(ratio - 1) < 0.05) return 'square';\n return ratio > 1 ? 'landscape' : 'portrait';\n}\n\n/**\n * Get aspect ratio as a string (e.g., \"16:9\", \"9:16\", \"1:1\").\n */\nexport function getAspectRatioString(viewport: ViewportConfig): string {\n const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\n const divisor = gcd(viewport.width, viewport.height);\n return `${viewport.width / divisor}:${viewport.height / divisor}`;\n}\n","/**\n * Layout Strategy\n *\n * Provides orientation-specific layout hints for slide templates.\n * Templates use these hints to position content appropriately for\n * different aspect ratios (landscape, portrait, square).\n *\n * Key adaptations by orientation:\n * - Portrait: Larger relative text, stacked layouts instead of side-by-side\n * - Square: Balanced layout with moderate adjustments\n * - Landscape: Default/reference layout\n */\n\nimport type { ViewportOrientation, ViewportConfig } from './Viewport.js';\nimport { calculateFontScale } from './Viewport.js';\n\n/**\n * Layout hints for template positioning based on orientation.\n */\nexport interface LayoutHints {\n /** Primary content Y position (percentage string, e.g., \"35%\") */\n primaryY: string;\n /** Secondary content Y position (percentage string) */\n secondaryY: string;\n /** Tertiary/detail Y position (percentage string) */\n tertiaryY: string;\n /** Title font size multiplier (relative to base) */\n titleScale: number;\n /** Body text font size multiplier (relative to base) */\n bodyScale: number;\n /** Two-column: left X position (percentage string) */\n columnLeftX: string;\n /** Two-column: right X position (percentage string) */\n columnRightX: string;\n /** Two-column in portrait: top Y position for stacked layout */\n columnTopY: string;\n /** Two-column in portrait: bottom Y position for stacked layout */\n columnBottomY: string;\n /** Whether two-column should stack vertically */\n stackColumns: boolean;\n /** Max text width (percentage string) for wrapping */\n maxTextWidth: string;\n /** Horizontal padding from edges (percentage string) */\n horizontalPadding: string;\n /** Caption position Y for imageWithCaption (percentage string) */\n captionY: string;\n /** Caption font size multiplier */\n captionScale: number;\n}\n\n/**\n * Layout configurations by orientation.\n */\nconst LAYOUT_CONFIGS: Record<ViewportOrientation, LayoutHints> = {\n landscape: {\n primaryY: '35%',\n secondaryY: '55%',\n tertiaryY: '75%',\n titleScale: 1.0,\n bodyScale: 1.0,\n columnLeftX: '25%',\n columnRightX: '75%',\n columnTopY: '35%',\n columnBottomY: '65%',\n stackColumns: false,\n maxTextWidth: '80%',\n horizontalPadding: '10%',\n captionY: '85%',\n captionScale: 1.0,\n },\n portrait: {\n // Content positioned higher for thumb-reach zone on mobile\n primaryY: '25%',\n secondaryY: '42%',\n tertiaryY: '58%',\n // Titles scale down for narrower width; body text scales up to fill vertical space\n titleScale: 0.7,\n bodyScale: 1.5,\n // Stacked columns instead of side-by-side\n columnLeftX: '50%',\n columnRightX: '50%',\n columnTopY: '30%',\n columnBottomY: '55%',\n stackColumns: true,\n // Wider relative to viewport to use available space\n maxTextWidth: '90%',\n horizontalPadding: '5%',\n captionY: '75%',\n captionScale: 0.85,\n },\n square: {\n primaryY: '30%',\n secondaryY: '50%',\n tertiaryY: '70%',\n titleScale: 0.85,\n bodyScale: 0.9,\n columnLeftX: '25%',\n columnRightX: '75%',\n columnTopY: '35%',\n columnBottomY: '65%',\n stackColumns: false,\n maxTextWidth: '85%',\n horizontalPadding: '7.5%',\n captionY: '82%',\n captionScale: 0.9,\n },\n};\n\n/**\n * Get layout hints for a given orientation.\n */\nexport function getLayoutHints(orientation: ViewportOrientation): LayoutHints {\n return LAYOUT_CONFIGS[orientation];\n}\n\n/**\n * Calculate a scaled font size based on viewport and layout hints.\n *\n * @param basePx - Base font size in pixels (designed for 1920x1080)\n * @param viewport - Target viewport configuration\n * @param orientation - Viewport orientation\n * @param isTitle - Whether this is title text (uses titleScale) or body (uses bodyScale)\n */\nexport function scaledFontSize(\n basePx: number,\n viewport: ViewportConfig,\n orientation: ViewportOrientation,\n isTitle: boolean = false,\n): number {\n const fontScale = calculateFontScale(viewport);\n const layout = getLayoutHints(orientation);\n const typeScale = isTitle ? layout.titleScale : layout.bodyScale;\n return Math.round(basePx * fontScale * typeScale);\n}\n\n/**\n * Get position for two-column layout based on orientation.\n * Returns { left: {x, y}, right: {x, y} } positions.\n */\nexport function getTwoColumnPositions(orientation: ViewportOrientation): {\n left: { x: string; y: string };\n right: { x: string; y: string };\n} {\n const layout = getLayoutHints(orientation);\n\n if (layout.stackColumns) {\n // Portrait: stack vertically\n return {\n left: { x: '50%', y: layout.columnTopY },\n right: { x: '50%', y: layout.columnBottomY },\n };\n }\n\n // Landscape/square: side by side\n return {\n left: { x: layout.columnLeftX, y: '50%' },\n right: { x: layout.columnRightX, y: '50%' },\n };\n}\n\n/**\n * Get safe text bounds for a given orientation.\n * Returns margins to keep text away from edges.\n */\nexport function getSafeTextBounds(orientation: ViewportOrientation): {\n left: string;\n right: string;\n top: string;\n bottom: string;\n} {\n const layout = getLayoutHints(orientation);\n return {\n left: layout.horizontalPadding,\n right: layout.horizontalPadding,\n top: '10%',\n bottom: '10%',\n };\n}\n","/**\n * Block Templates Schema\n *\n * Defines a template system for AI-generated doc blocks. Instead of\n * specifying low-level layers, positions, and animations, AI can use\n * high-level templates like \"titleBlock\" or \"statHighlight\" with simple\n * content parameters.\n *\n * Templates are expanded into full Block structures at render time,\n * ensuring consistent styling and reducing AI generation errors.\n *\n * Template Types:\n * - titleBlock: Doc intro with title + subtitle\n * - sectionHeader: Colored section divider\n * - statHighlight: Big number/stat with description\n * - quoteBlock: Large centered quote\n * - factCard: Key fact with explanation\n * - twoColumn: Side-by-side comparison\n * - dateEvent: Timeline-style date + description\n * - imageWithCaption: Image with text overlay\n */\n\nimport type { Layer, Block, Transition, MapTileStyle, MapMarker } from './Doc.js';\nimport type { ViewportConfig, ViewportOrientation } from './Viewport.js';\nimport type { LayoutHints } from './LayoutStrategy.js';\nimport type { Theme } from './Theme.js';\nimport { VIEWPORT_PRESETS, getViewportOrientation, calculateFontScale } from './Viewport.js';\nimport { getLayoutHints, scaledFontSize as scaleFontSize } from './LayoutStrategy.js';\n\n/**\n * Name of a color scheme defined in the active theme's `colorSchemes` map.\n * Templates reference schemes by name (e.g. 'blue', 'green') and the theme\n * resolves them to actual colors at render time via `resolveColorScheme()`.\n */\nexport type ColorScheme = string;\n\n/**\n * Default font family for doc text.\n * PT Serif provides a classic, readable appearance for documentary-style content.\n * Used as a fallback in TextLayer when no font is specified.\n */\nexport const DEFAULT_DOC_FONT = 'system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif';\n\n/**\n * Default font family for titles.\n */\nexport const DEFAULT_TITLE_FONT = 'Georgia, \"Times New Roman\", serif';\n\n// ============================================\n// Accent Image System\n// ============================================\n\n/**\n * Position options for accent images on text-based blocks.\n * Accents are tasteful image additions that complement rather than overwhelm text.\n */\nexport type AccentPosition =\n | 'left-strip' // Vertical strip on left (25-30% width), text shifts right\n | 'right-strip' // Vertical strip on right (25-30% width), text shifts left\n | 'bottom-strip' // Horizontal strip at bottom (25-30% height), text shifts up\n | 'corner-inset'; // Small inset image in corner with vignette edge\n\n/**\n * Accent image configuration for text-based blocks.\n * When present, the template adjusts layout to accommodate the image tastefully.\n */\nexport interface AccentImage {\n /** Path to image file (relative to article media dir) */\n src: string;\n /** Alt text for accessibility */\n alt: string;\n /** Where to position the accent image */\n position: AccentPosition;\n /** Ambient motion effect (subtle Ken Burns) */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n /** Photo credit / artist name */\n credit?: string;\n /** License identifier (e.g., 'CC BY-SA 4.0') */\n license?: string;\n}\n\n// ============================================\n// Template Input Types\n// ============================================\n\n/**\n * Base properties shared by all template blocks.\n */\ninterface BaseTemplateBlock {\n /** Unique block ID */\n id: string;\n /** Block duration in seconds */\n duration: number;\n /** Which audio segment this block belongs to */\n audioSegment: number;\n /** Entry transition */\n transition?: Transition;\n /** Show doc's bottom layers (default: true) */\n useBottomLayer?: boolean;\n /** Show doc's top layers (default: true) */\n useTopLayer?: boolean;\n /**\n * Start time within the audio segment when this content is spoken.\n * Used to sync the block appearance with the narration.\n * If not provided, blocks are distributed evenly across the segment.\n */\n sourceStartTime?: number;\n /**\n * Duration of the spoken content this block represents.\n * Used with sourceStartTime to precisely position the block.\n */\n sourceDuration?: number;\n}\n\n/**\n * Title block - doc intro with large title and subtitle.\n */\nexport interface TitleBlockInput extends BaseTemplateBlock {\n template: 'titleBlock';\n /** Main title text */\n title: string;\n /** Subtitle or tagline (supports \\n for line breaks) */\n subtitle?: string;\n /** Background color (defaults to theme primary) */\n backgroundColor?: string;\n}\n\n/**\n * Section header - section title card with optional background image.\n * Displays the section title prominently, optionally over an image.\n */\nexport interface SectionHeaderInput extends BaseTemplateBlock {\n template: 'sectionHeader';\n /** Section title */\n title: string;\n /** Color scheme for the section (used for fallback background) */\n colorScheme?: ColorScheme;\n /** Optional background image path */\n imageSrc?: string;\n /** Alt text for background image */\n imageAlt?: string;\n /** Ambient motion for background image */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n}\n\n/**\n * Stat highlight - big number with description and optional detail.\n */\nexport interface StatHighlightInput extends BaseTemplateBlock {\n template: 'statHighlight';\n /** The statistic (e.g., \"89%\", \"2x\", \"7 miles\") */\n stat: string;\n /** Description of what the stat means */\n description: string;\n /** Additional detail or context */\n detail?: string;\n /** Color scheme for the stat */\n colorScheme?: ColorScheme;\n /** Optional accent image to complement the text */\n accentImage?: AccentImage;\n}\n\n/**\n * Quote block - large centered quote text.\n */\nexport interface QuoteBlockInput extends BaseTemplateBlock {\n template: 'quoteBlock';\n /** The quote text (supports \\n for line breaks) */\n quote: string;\n /** Attribution (author, source) */\n attribution?: string;\n /** Optional accent image to complement the text */\n accentImage?: AccentImage;\n}\n\n/**\n * Fact card - key fact with explanation.\n */\nexport interface FactCardInput extends BaseTemplateBlock {\n template: 'factCard';\n /** The main fact or statement */\n fact: string;\n /** Explanation or context */\n explanation: string;\n /** Optional source citation */\n source?: string;\n /** Optional accent image to complement the text */\n accentImage?: AccentImage;\n}\n\n/**\n * Two column - side-by-side comparison.\n */\nexport interface TwoColumnInput extends BaseTemplateBlock {\n template: 'twoColumn';\n /** Left column content */\n left: {\n label: string;\n sublabel?: string;\n };\n /** Right column content */\n right: {\n label: string;\n sublabel?: string;\n };\n /** Optional header above columns */\n header?: string;\n /** Color schemes for left and right */\n leftColor?: ColorScheme;\n rightColor?: ColorScheme;\n}\n\n/**\n * Date event - timeline-style date with description.\n */\nexport interface DateEventInput extends BaseTemplateBlock {\n template: 'dateEvent';\n /** The date (e.g., \"July 14, 1974\") */\n date: string;\n /** Description of what happened (supports \\n) */\n description: string;\n /** Optional footer text */\n footer?: string;\n /** Mood: 'neutral', 'somber', 'celebratory' */\n mood?: 'neutral' | 'somber' | 'celebratory';\n /** Optional accent image to complement the text */\n accentImage?: AccentImage;\n}\n\n/**\n * Image with caption - background image with text overlay.\n */\nexport interface ImageWithCaptionInput extends BaseTemplateBlock {\n template: 'imageWithCaption';\n /** Path to image file */\n imageSrc: string;\n /** Alt text for accessibility */\n imageAlt: string;\n /** Caption text */\n caption?: string;\n /** Caption position */\n captionPosition?: 'bottom' | 'top' | 'center';\n /** Ambient motion effect: slow zoom or pan for visual interest */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n /** When true, style caption as a title (larger, centered, prominent) */\n isTitle?: boolean;\n /** Optional subtitle shown below the title (only when isTitle is true) */\n subtitle?: string;\n /** Photo credit / artist name */\n imageCredit?: string;\n /** License identifier (e.g., 'CC BY-SA 4.0') */\n imageLicense?: string;\n}\n\n/**\n * Map block - geographic map showing article location.\n *\n * Displays a map centered on given coordinates with optional title,\n * caption, and markers. Great for establishing geographic context.\n * See docs/MAP_TILES.md for available tile styles and attribution.\n */\nexport interface MapBlockInput extends BaseTemplateBlock {\n template: 'mapBlock';\n /** Map center coordinates */\n center: {\n lat: number;\n lng: number;\n };\n /** Zoom level (4-16, typically 8-12 for regional context) */\n zoom: number;\n /** Map tile style (default: 'terrain') */\n mapStyle?: MapTileStyle;\n /** Optional title overlay at top */\n title?: string;\n /** Optional caption at bottom */\n caption?: string;\n /** Optional markers to show on map */\n markers?: MapMarker[];\n /** Ambient motion effect: slow zoom or pan for visual interest */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n /** Pre-rendered static image path (set by prerender-maps command) */\n staticSrc?: string;\n}\n\n/**\n * Full-bleed quote - dramatic short text filling the viewport.\n * Like a movie title card. For short, punchy sentences < 60 chars.\n */\nexport interface FullBleedQuoteInput extends BaseTemplateBlock {\n template: 'fullBleedQuote';\n /** Short dramatic text (< 60 chars recommended) */\n text: string;\n /** Color scheme for text tint */\n colorScheme?: ColorScheme;\n}\n\n/**\n * List block - 3-5 items stacked vertically with subtle numbering.\n * Good for enumerations like \"things to see\" or \"key features\".\n */\nexport interface ListBlockInput extends BaseTemplateBlock {\n template: 'listBlock';\n /** List items (3-5 recommended) */\n items: string[];\n /** Optional header above the list */\n title?: string;\n /** Color scheme for numbering accents */\n colorScheme?: ColorScheme;\n /** Optional accent image */\n accentImage?: AccentImage;\n}\n\n/**\n * Photo grid - 2-4 images in a tiled layout.\n * Used when multiple images are available for visual variety.\n */\nexport interface PhotoGridInput extends BaseTemplateBlock {\n template: 'photoGrid';\n /** Images to display (2-4) */\n images: { src: string; alt: string; credit?: string; license?: string }[];\n /** Optional caption below the grid */\n caption?: string;\n /** Ambient motion effect for the largest image */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n}\n\n/**\n * Definition card - dictionary-style term with definition.\n * Large term at top, definition below, optional origin note.\n */\nexport interface DefinitionCardInput extends BaseTemplateBlock {\n template: 'definitionCard';\n /** The term being defined */\n term: string;\n /** The definition text */\n definition: string;\n /** Optional etymology or origin note */\n origin?: string;\n /** Color scheme for term accent */\n colorScheme?: ColorScheme;\n /** Optional accent image */\n accentImage?: AccentImage;\n}\n\n/**\n * Comparison bar - two horizontal bars showing relative numeric values.\n * Good for side-by-side numeric comparisons with visual weight.\n */\nexport interface ComparisonBarInput extends BaseTemplateBlock {\n template: 'comparisonBar';\n /** Left bar label */\n leftLabel: string;\n /** Left bar numeric value */\n leftValue: number;\n /** Right bar label */\n rightLabel: string;\n /** Right bar numeric value */\n rightValue: number;\n /** Unit label (e.g., \"km\", \"people\") */\n unit?: string;\n /** Color scheme */\n colorScheme?: ColorScheme;\n}\n\n/**\n * Pull quote - quote text over a full-bleed background image with dark overlay.\n * Cinematic alternative to quoteBlock when a high-quality image is available.\n */\nexport interface PullQuoteInput extends BaseTemplateBlock {\n template: 'pullQuote';\n /** Quote text */\n text: string;\n /** Optional attribution */\n attribution?: string;\n /** Background image (fills entire viewport) */\n backgroundImage: { src: string; alt: string; credit?: string; license?: string };\n /** Ambient motion for background image */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n}\n\n/**\n * Video with caption - background video clip with text overlay.\n * Plays a short clip from a source video, always muted (narration is the audio track).\n * Mirrors ImageWithCaptionInput but with video-specific fields.\n */\nexport interface VideoWithCaptionInput extends BaseTemplateBlock {\n template: 'videoWithCaption';\n /** Path to video file */\n videoSrc: string;\n /** Path to poster frame (shown before video loads) */\n posterSrc?: string;\n /** Alt text for accessibility */\n videoAlt: string;\n /** Start time within source video (seconds) */\n clipStart: number;\n /** End time within source video (seconds) */\n clipEnd: number;\n /** Source video total duration (for validation) */\n sourceDuration?: number;\n /** Caption text overlay */\n caption?: string;\n /** Caption position */\n captionPosition?: 'bottom' | 'top' | 'center';\n /** Video credit / artist name */\n videoCredit?: string;\n /** License identifier */\n videoLicense?: string;\n}\n\n/**\n * Video pull quote - quote text over a video clip background with dark overlay.\n * Cinematic alternative to pullQuote when a video clip is available.\n */\nexport interface VideoPullQuoteInput extends BaseTemplateBlock {\n template: 'videoPullQuote';\n /** Quote text */\n text: string;\n /** Optional attribution */\n attribution?: string;\n /** Background video clip */\n backgroundVideo: {\n src: string;\n posterSrc?: string;\n alt: string;\n clipStart: number;\n clipEnd: number;\n credit?: string;\n license?: string;\n };\n}\n\n/**\n * Union of all template block types.\n */\nexport type TemplateBlock =\n | TitleBlockInput\n | SectionHeaderInput\n | StatHighlightInput\n | QuoteBlockInput\n | FactCardInput\n | TwoColumnInput\n | DateEventInput\n | ImageWithCaptionInput\n | MapBlockInput\n | FullBleedQuoteInput\n | ListBlockInput\n | PhotoGridInput\n | DefinitionCardInput\n | ComparisonBarInput\n | PullQuoteInput\n | VideoWithCaptionInput\n | VideoPullQuoteInput;\n\n/**\n * A block can be either a raw Block or a TemplateBlock.\n */\nexport type DocBlock = Block | TemplateBlock;\n\n/**\n * Check if a block is a template block.\n */\nexport function isTemplateBlock(block: DocBlock): block is TemplateBlock {\n return 'template' in block && typeof block.template === 'string';\n}\n\n// ============================================\n// Template Function Type\n// ============================================\n\n/**\n * Template context passed to template functions.\n * Includes viewport information for multi-aspect ratio support.\n */\nexport interface TemplateContext {\n /** Full theme (colors, typography, style, renderStyle, colorSchemes) */\n theme: Theme;\n /** Block index in the doc */\n blockIndex: number;\n /** Total number of blocks */\n totalBlocks: number;\n /** Target viewport configuration */\n viewport: ViewportConfig;\n /** Computed font scale factor for this viewport */\n fontScale: number;\n /** Viewport orientation (landscape, portrait, square) */\n orientation: ViewportOrientation;\n /** Layout hints for this orientation */\n layout: LayoutHints;\n}\n\n/**\n * Create a template context with viewport-derived values.\n */\nexport function createTemplateContext(\n theme: Theme,\n blockIndex: number,\n totalBlocks: number,\n viewport: ViewportConfig = VIEWPORT_PRESETS.landscape,\n): TemplateContext {\n const orientation = getViewportOrientation(viewport);\n return {\n theme,\n blockIndex,\n totalBlocks,\n viewport,\n fontScale: calculateFontScale(viewport),\n orientation,\n layout: getLayoutHints(orientation),\n };\n}\n\n/**\n * Calculate a scaled font size for the given context.\n * Use this in templates to ensure text scales appropriately.\n *\n * @param basePx - Base font size in pixels (designed for 1920x1080)\n * @param context - Template context with viewport info\n * @param isTitle - Whether this is title text (larger scale) or body text\n */\nexport function scaledFontSize(\n basePx: number,\n context: TemplateContext,\n isTitle: boolean = false,\n): number {\n return scaleFontSize(basePx, context.viewport, context.orientation, isTitle);\n}\n\n/**\n * Template function signature.\n * Takes template input and returns layers array.\n */\nexport type TemplateFunction<T extends TemplateBlock> = (\n input: T,\n context: TemplateContext,\n) => Layer[];\n\n/**\n * Registry of all template functions.\n */\nexport type TemplateRegistry = {\n [K in TemplateBlock['template']]: TemplateFunction<Extract<TemplateBlock, { template: K }>>;\n};\n\n// ============================================\n// Persistent Layer System\n// ============================================\n\n/**\n * Configuration for persistent doc-wide layers.\n * Bottom layers render behind all block content, top layers on top.\n */\nexport interface PersistentLayerConfig {\n /** Layers rendered behind all block content */\n bottomLayers?: PersistentLayer[];\n /** Layers rendered on top of all block content */\n topLayers?: PersistentLayer[];\n}\n\n/**\n * A persistent layer - either a template or raw Layer.\n */\nexport type PersistentLayer = PersistentLayerTemplate | Layer;\n\n/**\n * Check if a persistent layer is a template.\n */\nexport function isPersistentLayerTemplate(\n layer: PersistentLayer,\n): layer is PersistentLayerTemplate {\n return 'template' in layer && typeof layer.template === 'string';\n}\n\n/**\n * Template-based persistent layer for easy configuration.\n */\nexport interface PersistentLayerTemplate {\n template: PersistentLayerTemplateType;\n config: PersistentLayerTemplateConfig;\n}\n\n/**\n * Available persistent layer template types.\n */\nexport type PersistentLayerTemplateType =\n | 'solidBackground' // Solid color fill\n | 'gradientBackground' // CSS gradient or preset\n | 'imageBackground' // Blurred/faded hero image\n | 'patternBackground' // Subtle pattern (dots, grid)\n | 'titleCaption' // Article title in corner\n | 'cornerBranding' // Logo or text badge\n | 'progressIndicator'; // Bar/dots showing position\n\n/**\n * Union of all persistent layer template configs.\n */\nexport type PersistentLayerTemplateConfig =\n | SolidBackgroundConfig\n | GradientBackgroundConfig\n | ImageBackgroundConfig\n | PatternBackgroundConfig\n | TitleCaptionConfig\n | CornerBrandingConfig\n | ProgressIndicatorConfig;\n\n// ============================================\n// Background Layer Configs\n// ============================================\n\n/**\n * Solid color background.\n */\nexport interface SolidBackgroundConfig {\n type: 'solidBackground';\n /** CSS color value */\n color: string;\n}\n\n/**\n * Gradient background (CSS gradient or preset).\n */\nexport interface GradientBackgroundConfig {\n type: 'gradientBackground';\n /** Custom CSS gradient string */\n gradient?: string;\n /** Preset gradient name */\n preset?: 'dark-vignette' | 'radial-dark' | 'warm-sunset' | 'cool-blue' | 'earth-tones';\n}\n\n/**\n * Image background (blurred/faded hero image).\n */\nexport interface ImageBackgroundConfig {\n type: 'imageBackground';\n /** Path to image file */\n src: string;\n /** Blur radius in pixels (0-20) */\n blur?: number;\n /** Opacity (0-1) */\n opacity?: number;\n /** Ambient motion effect */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n}\n\n/**\n * Pattern background (subtle repeating pattern).\n */\nexport interface PatternBackgroundConfig {\n type: 'patternBackground';\n /** Pattern type */\n pattern: 'dots' | 'grid' | 'diagonal' | 'noise';\n /** Pattern color */\n color?: string;\n /** Pattern opacity (0-1) */\n opacity?: number;\n /** Pattern scale multiplier */\n scale?: number;\n}\n\n// ============================================\n// Overlay Layer Configs\n// ============================================\n\n/**\n * Title caption overlay (article title in corner).\n */\nexport interface TitleCaptionConfig {\n type: 'titleCaption';\n /** Title text */\n title: string;\n /** Subtitle text (e.g., short URL like \"qual..la/slug\") */\n subtitle?: string;\n /** Position on screen */\n position: 'bottom-left' | 'bottom-right' | 'top-left' | 'top-right';\n /** Font size in pixels (default: 18) */\n fontSize?: number;\n /** Show thumbnail alongside title */\n showThumbnail?: boolean;\n /** Thumbnail image path */\n thumbnailSrc?: string;\n}\n\n/**\n * Corner branding overlay (logo or text badge).\n */\nexport interface CornerBrandingConfig {\n type: 'cornerBranding';\n /** Text content or image path */\n content: string;\n /** Position on screen */\n position: 'bottom-left' | 'bottom-right' | 'top-left' | 'top-right';\n /** Whether content is an image path (vs text) */\n isImage?: boolean;\n}\n\n/**\n * Progress indicator overlay (bar or dots showing position).\n */\nexport interface ProgressIndicatorConfig {\n type: 'progressIndicator';\n /** Indicator style */\n style: 'bar' | 'dots' | 'fraction';\n /** Position on screen */\n position: 'bottom' | 'top';\n /** Indicator color */\n color?: string;\n}\n"],"mappings":";AA4BO,IAAM,mBAAmB;AAAA;AAAA,EAE9B,WAAW,EAAE,OAAO,MAAM,QAAQ,MAAM,MAAM,iBAAiB;AAAA;AAAA,EAE/D,UAAU,EAAE,OAAO,MAAM,QAAQ,MAAM,MAAM,gBAAgB;AAAA;AAAA,EAE7D,QAAQ,EAAE,OAAO,MAAM,QAAQ,MAAM,MAAM,aAAa;AAAA;AAAA,EAExD,UAAU,EAAE,OAAO,MAAM,QAAQ,MAAM,MAAM,eAAe;AAC9D;AAeO,SAAS,YAAY,UAA2D;AACr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SAAS,sBACd,OACA,YACA,aACA,WAA2B,iBAAiB,WAC3B;AACjB,QAAM,cAAc,uBAAuB,QAAQ;AACnD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW,mBAAmB,QAAQ;AAAA,IACtC;AAAA,IACA,QAAQ,eAAe,WAAW;AAAA,EACpC;AACF;AAUO,SAASA,gBACd,QACA,SACA,UAAmB,OACX;AACR,SAAO,eAAc,QAAQ,QAAQ,UAAU,QAAQ,aAAa,OAAO;AAC7E;AAyCO,SAAS,0BACd,OACkC;AAClC,SAAO,cAAc,SAAS,OAAO,MAAM,aAAa;AAC1D;","names":["scaledFontSize"]}
1
+ {"version":3,"sources":["../src/schemas/Viewport.ts","../src/schemas/LayoutStrategy.ts","../src/schemas/BlockTemplates.ts"],"sourcesContent":["/**\n * Viewport Configuration\n *\n * Defines viewport dimensions for doc rendering across different aspect ratios.\n * Templates use this configuration to adapt their layouts appropriately.\n *\n * Supported aspect ratios:\n * - landscape (16:9) - Default, standard video/presentation format\n * - portrait (9:16) - Vertical video, mobile stories\n * - square (1:1) - Social media posts\n * - standard (4:3) - Legacy presentation format\n */\n\n/**\n * Viewport configuration for doc rendering.\n */\nexport interface ViewportConfig {\n /** Canonical width in virtual pixels */\n width: number;\n /** Canonical height in virtual pixels */\n height: number;\n /** Human-readable name for debugging/display */\n name: string;\n}\n\n/**\n * Standard viewport presets for common aspect ratios.\n */\nexport const VIEWPORT_PRESETS = {\n /** 16:9 landscape (default, 1080p) */\n landscape: { width: 1920, height: 1080, name: '16:9 Landscape' },\n /** 9:16 portrait (vertical video, stories) */\n portrait: { width: 1080, height: 1920, name: '9:16 Portrait' },\n /** 1:1 square (social media) */\n square: { width: 1080, height: 1080, name: '1:1 Square' },\n /** 4:3 standard (legacy) */\n standard: { width: 1440, height: 1080, name: '4:3 Standard' },\n} as const;\n\n/**\n * Viewport preset name.\n */\nexport type ViewportPreset = keyof typeof VIEWPORT_PRESETS;\n\n/**\n * Viewport orientation derived from aspect ratio.\n */\nexport type ViewportOrientation = 'landscape' | 'portrait' | 'square';\n\n/**\n * Get a viewport configuration from a preset name or return the config if already a ViewportConfig.\n */\nexport function getViewport(viewport: ViewportPreset | ViewportConfig): ViewportConfig {\n if (typeof viewport === 'string') {\n return VIEWPORT_PRESETS[viewport];\n }\n return viewport;\n}\n\n/**\n * Calculate font scale factor for a viewport.\n * Based on diagonal pixels relative to 1080p landscape reference.\n * This ensures text remains readable across different viewport sizes.\n */\nconst REFERENCE_DIAGONAL = Math.sqrt(1920 * 1920 + 1080 * 1080); // ~2203\n\nexport function calculateFontScale(viewport: ViewportConfig): number {\n const currentDiagonal = Math.sqrt(\n viewport.width * viewport.width + viewport.height * viewport.height,\n );\n return currentDiagonal / REFERENCE_DIAGONAL;\n}\n\n/**\n * Determine if viewport is landscape, portrait, or square.\n */\nexport function getViewportOrientation(viewport: ViewportConfig): ViewportOrientation {\n const ratio = viewport.width / viewport.height;\n // Allow small tolerance for \"square\" classification\n if (Math.abs(ratio - 1) < 0.05) return 'square';\n return ratio > 1 ? 'landscape' : 'portrait';\n}\n\n/**\n * Get aspect ratio as a string (e.g., \"16:9\", \"9:16\", \"1:1\").\n */\nexport function getAspectRatioString(viewport: ViewportConfig): string {\n const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\n const divisor = gcd(viewport.width, viewport.height);\n return `${viewport.width / divisor}:${viewport.height / divisor}`;\n}\n","/**\n * Layout Strategy\n *\n * Provides orientation-specific layout hints for slide templates.\n * Templates use these hints to position content appropriately for\n * different aspect ratios (landscape, portrait, square).\n *\n * Key adaptations by orientation:\n * - Portrait: Larger relative text, stacked layouts instead of side-by-side\n * - Square: Balanced layout with moderate adjustments\n * - Landscape: Default/reference layout\n */\n\nimport type { ViewportOrientation, ViewportConfig } from './Viewport.js';\nimport { calculateFontScale } from './Viewport.js';\n\n/**\n * Layout hints for template positioning based on orientation.\n */\nexport interface LayoutHints {\n /** Primary content Y position (percentage string, e.g., \"35%\") */\n primaryY: string;\n /** Secondary content Y position (percentage string) */\n secondaryY: string;\n /** Tertiary/detail Y position (percentage string) */\n tertiaryY: string;\n /** Title font size multiplier (relative to base) */\n titleScale: number;\n /** Body text font size multiplier (relative to base) */\n bodyScale: number;\n /** Two-column: left X position (percentage string) */\n columnLeftX: string;\n /** Two-column: right X position (percentage string) */\n columnRightX: string;\n /** Two-column in portrait: top Y position for stacked layout */\n columnTopY: string;\n /** Two-column in portrait: bottom Y position for stacked layout */\n columnBottomY: string;\n /** Whether two-column should stack vertically */\n stackColumns: boolean;\n /** Max text width (percentage string) for wrapping */\n maxTextWidth: string;\n /** Horizontal padding from edges (percentage string) */\n horizontalPadding: string;\n /** Caption position Y for imageWithCaption (percentage string) */\n captionY: string;\n /** Caption font size multiplier */\n captionScale: number;\n}\n\n/**\n * Layout configurations by orientation.\n */\nconst LAYOUT_CONFIGS: Record<ViewportOrientation, LayoutHints> = {\n landscape: {\n primaryY: '35%',\n secondaryY: '55%',\n tertiaryY: '75%',\n titleScale: 1.0,\n bodyScale: 1.0,\n columnLeftX: '25%',\n columnRightX: '75%',\n columnTopY: '35%',\n columnBottomY: '65%',\n stackColumns: false,\n maxTextWidth: '80%',\n horizontalPadding: '10%',\n captionY: '85%',\n captionScale: 1.0,\n },\n portrait: {\n // Content positioned higher for thumb-reach zone on mobile\n primaryY: '25%',\n secondaryY: '42%',\n tertiaryY: '58%',\n // Titles scale down for narrower width; body text scales up to fill vertical space\n titleScale: 0.7,\n bodyScale: 1.5,\n // Stacked columns instead of side-by-side\n columnLeftX: '50%',\n columnRightX: '50%',\n columnTopY: '30%',\n columnBottomY: '55%',\n stackColumns: true,\n // Wider relative to viewport to use available space\n maxTextWidth: '90%',\n horizontalPadding: '5%',\n captionY: '75%',\n captionScale: 0.85,\n },\n square: {\n primaryY: '30%',\n secondaryY: '50%',\n tertiaryY: '70%',\n titleScale: 0.85,\n bodyScale: 0.9,\n columnLeftX: '25%',\n columnRightX: '75%',\n columnTopY: '35%',\n columnBottomY: '65%',\n stackColumns: false,\n maxTextWidth: '85%',\n horizontalPadding: '7.5%',\n captionY: '82%',\n captionScale: 0.9,\n },\n};\n\n/**\n * Get layout hints for a given orientation.\n */\nexport function getLayoutHints(orientation: ViewportOrientation): LayoutHints {\n return LAYOUT_CONFIGS[orientation];\n}\n\n/**\n * Calculate a scaled font size based on viewport and layout hints.\n *\n * @param basePx - Base font size in pixels (designed for 1920x1080)\n * @param viewport - Target viewport configuration\n * @param orientation - Viewport orientation\n * @param isTitle - Whether this is title text (uses titleScale) or body (uses bodyScale)\n */\nexport function scaledFontSize(\n basePx: number,\n viewport: ViewportConfig,\n orientation: ViewportOrientation,\n isTitle: boolean = false,\n): number {\n const fontScale = calculateFontScale(viewport);\n const layout = getLayoutHints(orientation);\n const typeScale = isTitle ? layout.titleScale : layout.bodyScale;\n return Math.round(basePx * fontScale * typeScale);\n}\n\n/**\n * Get position for two-column layout based on orientation.\n * Returns { left: {x, y}, right: {x, y} } positions.\n */\nexport function getTwoColumnPositions(orientation: ViewportOrientation): {\n left: { x: string; y: string };\n right: { x: string; y: string };\n} {\n const layout = getLayoutHints(orientation);\n\n if (layout.stackColumns) {\n // Portrait: stack vertically\n return {\n left: { x: '50%', y: layout.columnTopY },\n right: { x: '50%', y: layout.columnBottomY },\n };\n }\n\n // Landscape/square: side by side\n return {\n left: { x: layout.columnLeftX, y: '50%' },\n right: { x: layout.columnRightX, y: '50%' },\n };\n}\n\n/**\n * Get safe text bounds for a given orientation.\n * Returns margins to keep text away from edges.\n */\nexport function getSafeTextBounds(orientation: ViewportOrientation): {\n left: string;\n right: string;\n top: string;\n bottom: string;\n} {\n const layout = getLayoutHints(orientation);\n return {\n left: layout.horizontalPadding,\n right: layout.horizontalPadding,\n top: '10%',\n bottom: '10%',\n };\n}\n","/**\n * Block Templates Schema\n *\n * Defines a template system for AI-generated doc blocks. Instead of\n * specifying low-level layers, positions, and animations, AI can use\n * high-level templates like \"titleBlock\" or \"statHighlight\" with simple\n * content parameters.\n *\n * Templates are expanded into full Block structures at render time,\n * ensuring consistent styling and reducing AI generation errors.\n *\n * Template Types:\n * - titleBlock: Doc intro with title + subtitle\n * - sectionHeader: Colored section divider\n * - statHighlight: Big number/stat with description\n * - quoteBlock: Large centered quote\n * - factCard: Key fact with explanation\n * - twoColumn: Side-by-side comparison\n * - dateEvent: Timeline-style date + description\n * - imageWithCaption: Image with text overlay\n */\n\nimport type { Layer, Block, Transition, MapTileStyle, MapMarker } from './Doc.js';\nimport type { ViewportConfig, ViewportOrientation } from './Viewport.js';\nimport type { LayoutHints } from './LayoutStrategy.js';\nimport type { Theme } from './Theme.js';\nimport { VIEWPORT_PRESETS, getViewportOrientation, calculateFontScale } from './Viewport.js';\nimport { getLayoutHints, scaledFontSize as scaleFontSize } from './LayoutStrategy.js';\n\n/**\n * Name of a color scheme defined in the active theme's `colorSchemes` map.\n * Templates reference schemes by name (e.g. 'blue', 'green') and the theme\n * resolves them to actual colors at render time via `resolveColorScheme()`.\n */\nexport type ColorScheme = string;\n\n/**\n * Default font family for doc text.\n * PT Serif provides a classic, readable appearance for documentary-style content.\n * Used as a fallback in TextLayer when no font is specified.\n */\nexport const DEFAULT_DOC_FONT = 'system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif';\n\n/**\n * Default font family for titles.\n */\nexport const DEFAULT_TITLE_FONT = 'Georgia, \"Times New Roman\", serif';\n\n// ============================================\n// Accent Image System\n// ============================================\n\n/**\n * Position options for accent images on text-based blocks.\n * Accents are tasteful image additions that complement rather than overwhelm text.\n */\nexport type AccentPosition =\n | 'left-strip' // Vertical strip on left (25-30% width), text shifts right\n | 'right-strip' // Vertical strip on right (25-30% width), text shifts left\n | 'bottom-strip' // Horizontal strip at bottom (25-30% height), text shifts up\n | 'corner-inset'; // Small inset image in corner with vignette edge\n\n/**\n * Accent image configuration for text-based blocks.\n * When present, the template adjusts layout to accommodate the image tastefully.\n */\nexport interface AccentImage {\n /** Path to image file (relative to article media dir) */\n src: string;\n /** Alt text for accessibility */\n alt: string;\n /** Where to position the accent image */\n position: AccentPosition;\n /** Ambient motion effect (subtle Ken Burns) */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n /** Photo credit / artist name */\n credit?: string;\n /** License identifier (e.g., 'CC BY-SA 4.0') */\n license?: string;\n}\n\n// ============================================\n// Template Input Types\n// ============================================\n\n/**\n * Base properties shared by all template blocks.\n */\ninterface BaseTemplateBlock {\n /** Unique block ID */\n id: string;\n /** Block duration in seconds */\n duration: number;\n /** Which audio segment this block belongs to */\n audioSegment: number;\n /** Entry transition */\n transition?: Transition;\n /** Show doc's bottom layers (default: true) */\n useBottomLayer?: boolean;\n /** Show doc's top layers (default: true) */\n useTopLayer?: boolean;\n /**\n * Start time within the audio segment when this content is spoken.\n * Used to sync the block appearance with the narration.\n * If not provided, blocks are distributed evenly across the segment.\n */\n sourceStartTime?: number;\n /**\n * Duration of the spoken content this block represents.\n * Used with sourceStartTime to precisely position the block.\n */\n sourceDuration?: number;\n}\n\n/**\n * Title block - doc intro with large title and subtitle.\n */\nexport interface TitleBlockInput extends BaseTemplateBlock {\n template: 'titleBlock';\n /** Main title text */\n title: string;\n /** Subtitle or tagline (supports \\n for line breaks) */\n subtitle?: string;\n /** Background color (defaults to theme primary) */\n backgroundColor?: string;\n}\n\n/**\n * Section header - section title card with optional background image.\n * Displays the section title prominently, optionally over an image.\n */\nexport interface SectionHeaderInput extends BaseTemplateBlock {\n template: 'sectionHeader';\n /** Section title */\n title: string;\n /** Color scheme for the section (used for fallback background) */\n colorScheme?: ColorScheme;\n /** Optional background image path */\n imageSrc?: string;\n /** Alt text for background image */\n imageAlt?: string;\n /** Ambient motion for background image */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n}\n\n/**\n * Stat highlight - big number with description and optional detail.\n */\nexport interface StatHighlightInput extends BaseTemplateBlock {\n template: 'statHighlight';\n /** The statistic (e.g., \"89%\", \"2x\", \"7 miles\") */\n stat: string;\n /** Description of what the stat means */\n description: string;\n /** Additional detail or context */\n detail?: string;\n /** Color scheme for the stat */\n colorScheme?: ColorScheme;\n /** Optional accent image to complement the text */\n accentImage?: AccentImage;\n}\n\n/**\n * Quote block - large centered quote text.\n */\nexport interface QuoteBlockInput extends BaseTemplateBlock {\n template: 'quoteBlock';\n /** The quote text (supports \\n for line breaks) */\n quote: string;\n /** Attribution (author, source) */\n attribution?: string;\n /** Optional accent image to complement the text */\n accentImage?: AccentImage;\n}\n\n/**\n * Fact card - key fact with explanation.\n */\nexport interface FactCardInput extends BaseTemplateBlock {\n template: 'factCard';\n /** The main fact or statement */\n fact: string;\n /** Explanation or context */\n explanation: string;\n /** Optional source citation */\n source?: string;\n /** Optional accent image to complement the text */\n accentImage?: AccentImage;\n}\n\n/**\n * Two column - side-by-side comparison.\n */\nexport interface TwoColumnInput extends BaseTemplateBlock {\n template: 'twoColumn';\n /** Left column content */\n left: {\n label: string;\n sublabel?: string;\n };\n /** Right column content */\n right: {\n label: string;\n sublabel?: string;\n };\n /** Optional header above columns */\n header?: string;\n /** Color schemes for left and right */\n leftColor?: ColorScheme;\n rightColor?: ColorScheme;\n}\n\n/**\n * Date event - timeline-style date with description.\n */\nexport interface DateEventInput extends BaseTemplateBlock {\n template: 'dateEvent';\n /** The date (e.g., \"July 14, 1974\") */\n date: string;\n /** Description of what happened (supports \\n) */\n description: string;\n /** Optional footer text */\n footer?: string;\n /** Mood: 'neutral', 'somber', 'celebratory' */\n mood?: 'neutral' | 'somber' | 'celebratory';\n /** Optional accent image to complement the text */\n accentImage?: AccentImage;\n}\n\n/**\n * Image with caption - background image with text overlay.\n */\nexport interface ImageWithCaptionInput extends BaseTemplateBlock {\n template: 'imageWithCaption';\n /** Path to image file */\n imageSrc: string;\n /** Alt text for accessibility */\n imageAlt: string;\n /** Caption text */\n caption?: string;\n /** Caption position */\n captionPosition?: 'bottom' | 'top' | 'center';\n /** Ambient motion effect: slow zoom or pan for visual interest */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n /** When true, style caption as a title (larger, centered, prominent) */\n isTitle?: boolean;\n /** Optional subtitle shown below the title (only when isTitle is true) */\n subtitle?: string;\n /** Photo credit / artist name */\n imageCredit?: string;\n /** License identifier (e.g., 'CC BY-SA 4.0') */\n imageLicense?: string;\n}\n\n/**\n * Map block - geographic map showing article location.\n *\n * Displays a map centered on given coordinates with optional title,\n * caption, and markers. Great for establishing geographic context.\n * See docs/MAP_TILES.md for available tile styles and attribution.\n */\nexport interface MapBlockInput extends BaseTemplateBlock {\n template: 'mapBlock';\n /** Map center coordinates */\n center: {\n lat: number;\n lng: number;\n };\n /** Zoom level (4-16, typically 8-12 for regional context) */\n zoom: number;\n /** Map tile style (default: 'terrain') */\n mapStyle?: MapTileStyle;\n /** Optional title overlay at top */\n title?: string;\n /** Optional caption at bottom */\n caption?: string;\n /** Optional markers to show on map */\n markers?: MapMarker[];\n /** Ambient motion effect: slow zoom or pan for visual interest */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n /** Pre-rendered static image path (set by prerender-maps command) */\n staticSrc?: string;\n}\n\n/**\n * Full-bleed quote - dramatic short text filling the viewport.\n * Like a movie title card. For short, punchy sentences < 60 chars.\n */\nexport interface FullBleedQuoteInput extends BaseTemplateBlock {\n template: 'fullBleedQuote';\n /** Short dramatic text (< 60 chars recommended) */\n text: string;\n /** Color scheme for text tint */\n colorScheme?: ColorScheme;\n}\n\n/**\n * List block - 3-5 items stacked vertically with subtle numbering.\n * Good for enumerations like \"things to see\" or \"key features\".\n */\nexport interface ListBlockInput extends BaseTemplateBlock {\n template: 'listBlock';\n /** List items (3-5 recommended) */\n items: string[];\n /** Optional header above the list */\n title?: string;\n /** Color scheme for numbering accents */\n colorScheme?: ColorScheme;\n /** Optional accent image */\n accentImage?: AccentImage;\n}\n\n/**\n * Photo grid - 2-4 images in a tiled layout.\n * Used when multiple images are available for visual variety.\n */\nexport interface PhotoGridInput extends BaseTemplateBlock {\n template: 'photoGrid';\n /** Images to display (2-4) */\n images: { src: string; alt: string; credit?: string; license?: string }[];\n /** Optional caption below the grid */\n caption?: string;\n /** Ambient motion effect for the largest image */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n}\n\n/**\n * Definition card - dictionary-style term with definition.\n * Large term at top, definition below, optional origin note.\n */\nexport interface DefinitionCardInput extends BaseTemplateBlock {\n template: 'definitionCard';\n /** The term being defined */\n term: string;\n /** The definition text */\n definition: string;\n /** Optional etymology or origin note */\n origin?: string;\n /** Color scheme for term accent */\n colorScheme?: ColorScheme;\n /** Optional accent image */\n accentImage?: AccentImage;\n}\n\n/**\n * Comparison bar - two horizontal bars showing relative numeric values.\n * Good for side-by-side numeric comparisons with visual weight.\n */\nexport interface ComparisonBarInput extends BaseTemplateBlock {\n template: 'comparisonBar';\n /** Left bar label */\n leftLabel: string;\n /** Left bar numeric value */\n leftValue: number;\n /** Right bar label */\n rightLabel: string;\n /** Right bar numeric value */\n rightValue: number;\n /** Unit label (e.g., \"km\", \"people\") */\n unit?: string;\n /** Color scheme */\n colorScheme?: ColorScheme;\n}\n\n/**\n * Pull quote - quote text over a full-bleed background image with dark overlay.\n * Cinematic alternative to quoteBlock when a high-quality image is available.\n */\nexport interface PullQuoteInput extends BaseTemplateBlock {\n template: 'pullQuote';\n /** Quote text */\n text: string;\n /** Optional attribution */\n attribution?: string;\n /** Background image (fills entire viewport) */\n backgroundImage: { src: string; alt: string; credit?: string; license?: string };\n /** Ambient motion for background image */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n}\n\n/**\n * Video with caption - background video clip with text overlay.\n * Plays a short clip from a source video, always muted (narration is the audio track).\n * Mirrors ImageWithCaptionInput but with video-specific fields.\n */\nexport interface VideoWithCaptionInput extends BaseTemplateBlock {\n template: 'videoWithCaption';\n /** Path to video file */\n videoSrc: string;\n /** Path to poster frame (shown before video loads) */\n posterSrc?: string;\n /** Alt text for accessibility */\n videoAlt: string;\n /** Start time within source video (seconds) */\n clipStart: number;\n /** End time within source video (seconds) */\n clipEnd: number;\n /** Source video total duration (for validation) */\n sourceDuration?: number;\n /** Caption text overlay */\n caption?: string;\n /** Caption position */\n captionPosition?: 'bottom' | 'top' | 'center';\n /** Video credit / artist name */\n videoCredit?: string;\n /** License identifier */\n videoLicense?: string;\n}\n\n/**\n * Video pull quote - quote text over a video clip background with dark overlay.\n * Cinematic alternative to pullQuote when a video clip is available.\n */\nexport interface VideoPullQuoteInput extends BaseTemplateBlock {\n template: 'videoPullQuote';\n /** Quote text */\n text: string;\n /** Optional attribution */\n attribution?: string;\n /** Background video clip */\n backgroundVideo: {\n src: string;\n posterSrc?: string;\n alt: string;\n clipStart: number;\n clipEnd: number;\n credit?: string;\n license?: string;\n };\n}\n\n/**\n * Data table - renders a themed table with headers and rows.\n * Ideal for structured data, comparisons, and reference information.\n */\nexport interface DataTableInput extends BaseTemplateBlock {\n template: 'dataTable';\n /** Optional title displayed above the table */\n title?: string;\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 /** Color scheme for the table header */\n colorScheme?: ColorScheme;\n}\n\n/**\n * Union of all template block types.\n */\nexport type TemplateBlock =\n | TitleBlockInput\n | SectionHeaderInput\n | StatHighlightInput\n | QuoteBlockInput\n | FactCardInput\n | TwoColumnInput\n | DateEventInput\n | ImageWithCaptionInput\n | MapBlockInput\n | FullBleedQuoteInput\n | ListBlockInput\n | PhotoGridInput\n | DefinitionCardInput\n | ComparisonBarInput\n | PullQuoteInput\n | VideoWithCaptionInput\n | VideoPullQuoteInput\n | DataTableInput;\n\n/**\n * A block can be either a raw Block or a TemplateBlock.\n */\nexport type DocBlock = Block | TemplateBlock;\n\n/**\n * Check if a block is a template block.\n */\nexport function isTemplateBlock(block: DocBlock): block is TemplateBlock {\n return 'template' in block && typeof block.template === 'string';\n}\n\n// ============================================\n// Template Function Type\n// ============================================\n\n/**\n * Template context passed to template functions.\n * Includes viewport information for multi-aspect ratio support.\n */\nexport interface TemplateContext {\n /** Full theme (colors, typography, style, renderStyle, colorSchemes) */\n theme: Theme;\n /** Block index in the doc */\n blockIndex: number;\n /** Total number of blocks */\n totalBlocks: number;\n /** Target viewport configuration */\n viewport: ViewportConfig;\n /** Computed font scale factor for this viewport */\n fontScale: number;\n /** Viewport orientation (landscape, portrait, square) */\n orientation: ViewportOrientation;\n /** Layout hints for this orientation */\n layout: LayoutHints;\n}\n\n/**\n * Create a template context with viewport-derived values.\n */\nexport function createTemplateContext(\n theme: Theme,\n blockIndex: number,\n totalBlocks: number,\n viewport: ViewportConfig = VIEWPORT_PRESETS.landscape,\n): TemplateContext {\n const orientation = getViewportOrientation(viewport);\n return {\n theme,\n blockIndex,\n totalBlocks,\n viewport,\n fontScale: calculateFontScale(viewport),\n orientation,\n layout: getLayoutHints(orientation),\n };\n}\n\n/**\n * Calculate a scaled font size for the given context.\n * Use this in templates to ensure text scales appropriately.\n *\n * @param basePx - Base font size in pixels (designed for 1920x1080)\n * @param context - Template context with viewport info\n * @param isTitle - Whether this is title text (larger scale) or body text\n */\nexport function scaledFontSize(\n basePx: number,\n context: TemplateContext,\n isTitle: boolean = false,\n): number {\n return scaleFontSize(basePx, context.viewport, context.orientation, isTitle);\n}\n\n/**\n * Template function signature.\n * Takes template input and returns layers array.\n */\nexport type TemplateFunction<T extends TemplateBlock> = (\n input: T,\n context: TemplateContext,\n) => Layer[];\n\n/**\n * Registry of all template functions.\n */\nexport type TemplateRegistry = {\n [K in TemplateBlock['template']]: TemplateFunction<Extract<TemplateBlock, { template: K }>>;\n};\n\n// ============================================\n// Persistent Layer System\n// ============================================\n\n/**\n * Configuration for persistent doc-wide layers.\n * Bottom layers render behind all block content, top layers on top.\n */\nexport interface PersistentLayerConfig {\n /** Layers rendered behind all block content */\n bottomLayers?: PersistentLayer[];\n /** Layers rendered on top of all block content */\n topLayers?: PersistentLayer[];\n}\n\n/**\n * A persistent layer - either a template or raw Layer.\n */\nexport type PersistentLayer = PersistentLayerTemplate | Layer;\n\n/**\n * Check if a persistent layer is a template.\n */\nexport function isPersistentLayerTemplate(\n layer: PersistentLayer,\n): layer is PersistentLayerTemplate {\n return 'template' in layer && typeof layer.template === 'string';\n}\n\n/**\n * Template-based persistent layer for easy configuration.\n */\nexport interface PersistentLayerTemplate {\n template: PersistentLayerTemplateType;\n config: PersistentLayerTemplateConfig;\n}\n\n/**\n * Available persistent layer template types.\n */\nexport type PersistentLayerTemplateType =\n | 'solidBackground' // Solid color fill\n | 'gradientBackground' // CSS gradient or preset\n | 'imageBackground' // Blurred/faded hero image\n | 'patternBackground' // Subtle pattern (dots, grid)\n | 'titleCaption' // Article title in corner\n | 'cornerBranding' // Logo or text badge\n | 'progressIndicator'; // Bar/dots showing position\n\n/**\n * Union of all persistent layer template configs.\n */\nexport type PersistentLayerTemplateConfig =\n | SolidBackgroundConfig\n | GradientBackgroundConfig\n | ImageBackgroundConfig\n | PatternBackgroundConfig\n | TitleCaptionConfig\n | CornerBrandingConfig\n | ProgressIndicatorConfig;\n\n// ============================================\n// Background Layer Configs\n// ============================================\n\n/**\n * Solid color background.\n */\nexport interface SolidBackgroundConfig {\n type: 'solidBackground';\n /** CSS color value */\n color: string;\n}\n\n/**\n * Gradient background (CSS gradient or preset).\n */\nexport interface GradientBackgroundConfig {\n type: 'gradientBackground';\n /** Custom CSS gradient string */\n gradient?: string;\n /** Preset gradient name */\n preset?: 'dark-vignette' | 'radial-dark' | 'warm-sunset' | 'cool-blue' | 'earth-tones';\n}\n\n/**\n * Image background (blurred/faded hero image).\n */\nexport interface ImageBackgroundConfig {\n type: 'imageBackground';\n /** Path to image file */\n src: string;\n /** Blur radius in pixels (0-20) */\n blur?: number;\n /** Opacity (0-1) */\n opacity?: number;\n /** Ambient motion effect */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n}\n\n/**\n * Pattern background (subtle repeating pattern).\n */\nexport interface PatternBackgroundConfig {\n type: 'patternBackground';\n /** Pattern type */\n pattern: 'dots' | 'grid' | 'diagonal' | 'noise';\n /** Pattern color */\n color?: string;\n /** Pattern opacity (0-1) */\n opacity?: number;\n /** Pattern scale multiplier */\n scale?: number;\n}\n\n// ============================================\n// Overlay Layer Configs\n// ============================================\n\n/**\n * Title caption overlay (article title in corner).\n */\nexport interface TitleCaptionConfig {\n type: 'titleCaption';\n /** Title text */\n title: string;\n /** Subtitle text (e.g., short URL like \"qual..la/slug\") */\n subtitle?: string;\n /** Position on screen */\n position: 'bottom-left' | 'bottom-right' | 'top-left' | 'top-right';\n /** Font size in pixels (default: 18) */\n fontSize?: number;\n /** Show thumbnail alongside title */\n showThumbnail?: boolean;\n /** Thumbnail image path */\n thumbnailSrc?: string;\n}\n\n/**\n * Corner branding overlay (logo or text badge).\n */\nexport interface CornerBrandingConfig {\n type: 'cornerBranding';\n /** Text content or image path */\n content: string;\n /** Position on screen */\n position: 'bottom-left' | 'bottom-right' | 'top-left' | 'top-right';\n /** Whether content is an image path (vs text) */\n isImage?: boolean;\n}\n\n/**\n * Progress indicator overlay (bar or dots showing position).\n */\nexport interface ProgressIndicatorConfig {\n type: 'progressIndicator';\n /** Indicator style */\n style: 'bar' | 'dots' | 'fraction';\n /** Position on screen */\n position: 'bottom' | 'top';\n /** Indicator color */\n color?: string;\n}\n"],"mappings":";AA4BO,IAAM,mBAAmB;AAAA;AAAA,EAE9B,WAAW,EAAE,OAAO,MAAM,QAAQ,MAAM,MAAM,iBAAiB;AAAA;AAAA,EAE/D,UAAU,EAAE,OAAO,MAAM,QAAQ,MAAM,MAAM,gBAAgB;AAAA;AAAA,EAE7D,QAAQ,EAAE,OAAO,MAAM,QAAQ,MAAM,MAAM,aAAa;AAAA;AAAA,EAExD,UAAU,EAAE,OAAO,MAAM,QAAQ,MAAM,MAAM,eAAe;AAC9D;AAeO,SAAS,YAAY,UAA2D;AACrF,MAAI,OAAO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