@bendyline/squisq 1.4.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (216) hide show
  1. package/dist/{Doc-BeSeH2iX.d.ts → Doc-BsMkmzH8.d.ts} +838 -268
  2. package/dist/{ImageEditDoc-BTIvw0oq.d.ts → ImageEditDoc-DvoeHMP9.d.ts} +11 -4
  3. package/dist/{chunk-ZTX4PFFT.js → chunk-2OIBZYKP.js} +75 -2
  4. package/dist/chunk-2OIBZYKP.js.map +1 -0
  5. package/dist/chunk-2UQOHYE2.js +45 -0
  6. package/dist/chunk-2UQOHYE2.js.map +1 -0
  7. package/dist/{chunk-B4EEON3N.js → chunk-4AKUQPEE.js} +536 -103
  8. package/dist/chunk-4AKUQPEE.js.map +1 -0
  9. package/dist/chunk-4ZFRZBU2.js +6582 -0
  10. package/dist/chunk-4ZFRZBU2.js.map +1 -0
  11. package/dist/{chunk-57CVQCFX.js → chunk-7MQGNR76.js} +79 -3
  12. package/dist/chunk-7MQGNR76.js.map +1 -0
  13. package/dist/{chunk-5WFRKURX.js → chunk-DLXZMS5K.js} +4 -2
  14. package/dist/chunk-DLXZMS5K.js.map +1 -0
  15. package/dist/{chunk-MYIH7FWD.js → chunk-FBKP5CAO.js} +1 -1
  16. package/dist/chunk-FBKP5CAO.js.map +1 -0
  17. package/dist/chunk-KZNXZ5SM.js +333 -0
  18. package/dist/chunk-KZNXZ5SM.js.map +1 -0
  19. package/dist/{chunk-WMOI7FN3.js → chunk-LRCV7N7F.js} +12 -2
  20. package/dist/{chunk-WMOI7FN3.js.map → chunk-LRCV7N7F.js.map} +1 -1
  21. package/dist/{chunk-3K5OG6KI.js → chunk-OH43RPTP.js} +403 -187
  22. package/dist/chunk-OH43RPTP.js.map +1 -0
  23. package/dist/{chunk-H3AXU4MJ.js → chunk-OKJOQXK4.js} +149 -2
  24. package/dist/chunk-OKJOQXK4.js.map +1 -0
  25. package/dist/chunk-PGGGKYWG.js +1 -0
  26. package/dist/chunk-PGGGKYWG.js.map +1 -0
  27. package/dist/{chunk-7UDSRZKG.js → chunk-Q3ROPT5H.js} +35 -14
  28. package/dist/chunk-Q3ROPT5H.js.map +1 -0
  29. package/dist/chunk-QE7TWGVT.js +178 -0
  30. package/dist/chunk-QE7TWGVT.js.map +1 -0
  31. package/dist/chunk-RUDYOTA6.js +345 -0
  32. package/dist/chunk-RUDYOTA6.js.map +1 -0
  33. package/dist/chunk-TVSGLUID.js +596 -0
  34. package/dist/chunk-TVSGLUID.js.map +1 -0
  35. package/dist/chunk-ZLQKNOZQ.js +1 -0
  36. package/dist/chunk-ZLQKNOZQ.js.map +1 -0
  37. package/dist/doc/index.d.ts +4 -4
  38. package/dist/doc/index.js +124 -6
  39. package/dist/generate/index.d.ts +9 -2
  40. package/dist/generate/index.js +1 -1
  41. package/dist/icons/index.d.ts +3 -26
  42. package/dist/icons/index.js +13 -0
  43. package/dist/icons/inlineIconMarker.d.ts +1 -0
  44. package/dist/icons/inlineIconMarker.js +15 -0
  45. package/dist/icons/inlineIconMarker.js.map +1 -0
  46. package/dist/imageEdit/index.d.ts +11 -5
  47. package/dist/imageEdit/index.js +4 -1
  48. package/dist/index.d.ts +11 -8
  49. package/dist/index.js +243 -24
  50. package/dist/inlineIconMarker-CiE8Hlvz.d.ts +59 -0
  51. package/dist/markdown/index.d.ts +212 -3
  52. package/dist/markdown/index.js +40 -7
  53. package/dist/recommend/index.d.ts +1 -1
  54. package/dist/recommend/index.js +3 -2
  55. package/dist/schemas/index.d.ts +28 -8
  56. package/dist/schemas/index.js +35 -5
  57. package/dist/spatial/index.d.ts +9 -4
  58. package/dist/spatial/index.js +1 -1
  59. package/dist/story/index.d.ts +906 -40
  60. package/dist/story/index.js +124 -6
  61. package/dist/{themeLibrary-BHjJ0Qx6.d.ts → themeLibrary-DQQKuRMx.d.ts} +1 -1
  62. package/dist/transform/index.d.ts +48 -10
  63. package/dist/transform/index.js +17 -481
  64. package/dist/transform/index.js.map +1 -1
  65. package/dist/{types-BdZkdJ3z.d.ts → types-DlAZ7MW4.d.ts} +115 -1
  66. package/package.json +6 -1
  67. package/src/__tests__/animationUtils.test.ts +40 -0
  68. package/src/__tests__/annotationCoercion.test.ts +243 -0
  69. package/src/__tests__/applyRenderStyle.test.ts +146 -0
  70. package/src/__tests__/atmosphereLayers.test.ts +108 -0
  71. package/src/__tests__/attrTokens.test.ts +162 -0
  72. package/src/__tests__/customTemplateSample.test.ts +83 -0
  73. package/src/__tests__/customTemplatesFrontmatter.test.ts +205 -0
  74. package/src/__tests__/customThemesFrontmatter.test.ts +118 -0
  75. package/src/__tests__/diagramBlock.test.ts +122 -0
  76. package/src/__tests__/diagramLayout.test.ts +134 -0
  77. package/src/__tests__/drawing.test.ts +109 -0
  78. package/src/__tests__/drawingBlock.test.ts +124 -0
  79. package/src/__tests__/drawingLayout.test.ts +171 -0
  80. package/src/__tests__/geohash.test.ts +6 -5
  81. package/src/__tests__/getLayers.test.ts +6 -2
  82. package/src/__tests__/getLayersFallback.test.ts +103 -0
  83. package/src/__tests__/imageEditExportSvg.test.ts +70 -0
  84. package/src/__tests__/imageEditVersions.test.ts +72 -0
  85. package/src/__tests__/inlineIconMarker.test.ts +36 -0
  86. package/src/__tests__/layoutBlock.test.ts +83 -0
  87. package/src/__tests__/layoutLayout.test.ts +169 -0
  88. package/src/__tests__/markdown.test.ts +23 -0
  89. package/src/__tests__/markdownSanitize.test.ts +64 -0
  90. package/src/__tests__/markdownToDoc.test.ts +223 -2
  91. package/src/__tests__/mediaAnnotations.test.ts +64 -0
  92. package/src/__tests__/mediaSchedule.test.ts +118 -0
  93. package/src/__tests__/pandocAttrParse.test.ts +187 -0
  94. package/src/__tests__/resolveDocTheme.test.ts +55 -0
  95. package/src/__tests__/rootExports.test.ts +43 -0
  96. package/src/__tests__/shapeGeometry.test.ts +89 -0
  97. package/src/__tests__/shapeVocabulary.test.ts +133 -0
  98. package/src/__tests__/structuredData.test.ts +179 -0
  99. package/src/__tests__/templateAnnotationParse.test.ts +108 -0
  100. package/src/__tests__/templateMetadata.test.ts +21 -0
  101. package/src/__tests__/templates.test.ts +145 -4
  102. package/src/__tests__/themeCompile.test.ts +42 -0
  103. package/src/__tests__/themeValidator.test.ts +6 -0
  104. package/src/__tests__/transformV2.test.ts +137 -0
  105. package/src/__tests__/transitionNormalize.test.ts +61 -0
  106. package/src/__tests__/validateDoc.test.ts +100 -0
  107. package/src/doc/customTemplatesFrontmatter.ts +308 -0
  108. package/src/doc/customThemesFrontmatter.ts +90 -0
  109. package/src/doc/docToMarkdown.ts +73 -4
  110. package/src/doc/getLayers.ts +40 -17
  111. package/src/doc/index.ts +35 -1
  112. package/src/doc/markdownToDoc.ts +333 -12
  113. package/src/doc/mediaAnnotations.ts +118 -0
  114. package/src/doc/resolveDocTheme.ts +55 -0
  115. package/src/doc/structuredData.ts +230 -0
  116. package/src/doc/templateInputs.ts +240 -0
  117. package/src/doc/templates/__tests__/customTemplate.test.ts +151 -0
  118. package/src/doc/templates/__tests__/customTemplateRegistry.test.ts +110 -0
  119. package/src/doc/templates/accentImage.ts +30 -6
  120. package/src/doc/templates/captionUtils.ts +23 -0
  121. package/src/doc/templates/comparisonBar.ts +26 -18
  122. package/src/doc/templates/coverBlock.ts +7 -4
  123. package/src/doc/templates/customTemplate.ts +45 -0
  124. package/src/doc/templates/dataTable.ts +37 -19
  125. package/src/doc/templates/dateEvent.ts +41 -20
  126. package/src/doc/templates/definitionCard.ts +26 -18
  127. package/src/doc/templates/diagramBlock.ts +204 -0
  128. package/src/doc/templates/diagramLayout.ts +159 -0
  129. package/src/doc/templates/drawingBlock.ts +325 -0
  130. package/src/doc/templates/drawingLayout.ts +539 -0
  131. package/src/doc/templates/factCard.ts +51 -25
  132. package/src/doc/templates/fallbackBlock.ts +123 -0
  133. package/src/doc/templates/featureBlock.ts +20 -13
  134. package/src/doc/templates/fullBleedQuote.ts +18 -8
  135. package/src/doc/templates/imageWithCaption.ts +22 -9
  136. package/src/doc/templates/index.ts +215 -46
  137. package/src/doc/templates/layoutBlock.ts +43 -0
  138. package/src/doc/templates/layoutLayout.ts +243 -0
  139. package/src/doc/templates/listBlock.ts +56 -30
  140. package/src/doc/templates/mapBlock.ts +15 -12
  141. package/src/doc/templates/metadata.ts +120 -0
  142. package/src/doc/templates/persistentLayers.ts +129 -11
  143. package/src/doc/templates/photoGrid.ts +23 -12
  144. package/src/doc/templates/pullQuote.ts +30 -12
  145. package/src/doc/templates/quoteBlock.ts +54 -29
  146. package/src/doc/templates/sectionHeader.ts +25 -11
  147. package/src/doc/templates/statHighlight.ts +39 -22
  148. package/src/doc/templates/titleBlock.ts +59 -21
  149. package/src/doc/templates/tokens/__tests__/resolveTokens.test.ts +221 -0
  150. package/src/doc/templates/tokens/resolveTokens.ts +0 -0
  151. package/src/doc/templates/twoColumn.ts +48 -30
  152. package/src/doc/templates/videoPullQuote.ts +22 -12
  153. package/src/doc/templates/videoWithCaption.ts +13 -8
  154. package/src/doc/utils/animationUtils.ts +267 -3
  155. package/src/doc/utils/applyRenderStyle.ts +113 -0
  156. package/src/doc/utils/imageTreatment.ts +70 -0
  157. package/src/doc/utils/shapeGeometry.ts +464 -0
  158. package/src/doc/utils/themeUtils.ts +75 -1
  159. package/src/doc/validate.ts +476 -0
  160. package/src/generate/slideshowGenerator.ts +7 -0
  161. package/src/icons/index.ts +8 -0
  162. package/src/icons/inlineIconMarker.ts +73 -0
  163. package/src/imageEdit/export.ts +85 -2
  164. package/src/imageEdit/index.ts +1 -0
  165. package/src/imageEdit/persistence.ts +51 -0
  166. package/src/index.ts +2 -0
  167. package/src/markdown/annotationCoercion.ts +295 -0
  168. package/src/markdown/attrTokens.ts +222 -0
  169. package/src/markdown/convert.ts +229 -26
  170. package/src/markdown/index.ts +36 -0
  171. package/src/markdown/sanitize.ts +298 -0
  172. package/src/markdown/stringify.ts +84 -3
  173. package/src/markdown/types.ts +66 -0
  174. package/src/markdown/utils.ts +49 -1
  175. package/src/recommend/templates.ts +24 -0
  176. package/src/schemas/BlockTemplates.ts +133 -4
  177. package/src/schemas/CustomTemplates.ts +74 -0
  178. package/src/schemas/Doc.ts +353 -29
  179. package/src/schemas/ImageEditDoc.ts +11 -4
  180. package/src/schemas/Media.ts +169 -0
  181. package/src/schemas/Theme.ts +23 -1
  182. package/src/schemas/Transitions.ts +224 -0
  183. package/src/schemas/colorUtils.ts +33 -0
  184. package/src/schemas/fontStacks.ts +5 -2
  185. package/src/schemas/index.ts +3 -0
  186. package/src/schemas/themeCompile.ts +23 -4
  187. package/src/schemas/themeValidator.ts +49 -11
  188. package/src/schemas/themes/cinematic.json +69 -12
  189. package/src/schemas/themes/documentary.json +58 -11
  190. package/src/schemas/themes/gezellig.json +60 -11
  191. package/src/schemas/themes/magazine.json +54 -9
  192. package/src/schemas/themes/morning-light.json +52 -9
  193. package/src/schemas/themes/standard-dark.json +48 -13
  194. package/src/schemas/themes/standard.json +44 -12
  195. package/src/schemas/themes/tech-dark.json +65 -12
  196. package/src/spatial/Geohash.ts +52 -21
  197. package/src/transform/applyTransform.ts +43 -4
  198. package/src/transform/index.ts +1 -0
  199. package/src/transform/registry.ts +44 -13
  200. package/src/transform/styles/dataDriven.ts +2 -1
  201. package/src/transform/styles/documentary.ts +2 -1
  202. package/src/transform/styles/magazine.ts +3 -1
  203. package/src/transform/styles/minimal.ts +2 -1
  204. package/src/transform/styles/narrative.ts +3 -1
  205. package/src/transform/templateSelector.ts +87 -11
  206. package/src/transform/types.ts +35 -2
  207. package/dist/chunk-3K5OG6KI.js.map +0 -1
  208. package/dist/chunk-57CVQCFX.js.map +0 -1
  209. package/dist/chunk-5WFRKURX.js.map +0 -1
  210. package/dist/chunk-7UDSRZKG.js.map +0 -1
  211. package/dist/chunk-B4EEON3N.js.map +0 -1
  212. package/dist/chunk-H3AXU4MJ.js.map +0 -1
  213. package/dist/chunk-KSWJR66U.js +0 -3706
  214. package/dist/chunk-KSWJR66U.js.map +0 -1
  215. package/dist/chunk-MYIH7FWD.js.map +0 -1
  216. package/dist/chunk-ZTX4PFFT.js.map +0 -1
@@ -0,0 +1,308 @@
1
+ /**
2
+ * Frontmatter serialization for user-defined custom templates (layouts).
3
+ *
4
+ * Custom template definitions live in the document's YAML frontmatter
5
+ * under the key `squisq-custom-templates`. They're stored as a single
6
+ * **compact JSON** object keyed by template name:
7
+ *
8
+ * ```yaml
9
+ * squisq-custom-templates: {"hero":{"lb":"Hero Section","ly":[{"ty":"text",…}]}}
10
+ * ```
11
+ *
12
+ * Squisq's frontmatter parser is line-based; a JSON object literal
13
+ * round-trips through it verbatim (no leading quote to strip, single
14
+ * line), so the value is written **unquoted** and stays human-readable
15
+ * and diffable — important for a codebase edited by people and agents.
16
+ *
17
+ * The JSON is kept small by:
18
+ * - keying definitions by `name` (drops the `name` field + array wrapper),
19
+ * - omitting the viewport when it's the 1920×1080 default,
20
+ * - renaming well-known property names to two-letter codes via
21
+ * {@link LONG_TO_SHORT} (e.g. `fontSize` → `fz`).
22
+ *
23
+ * The rename is a generic, recursive, bijective pass: **any property not
24
+ * in the map passes through unchanged**, so the format is lossless even
25
+ * as the Layer schema grows — new fields are simply stored under their
26
+ * full name until (optionally) added to the map.
27
+ *
28
+ * Back-compat: the reader still accepts the historical base64-of-JSON
29
+ * payload and a structured array, so older documents load unchanged.
30
+ * The first save migrates them to the compact form.
31
+ *
32
+ * The `encodeLayersForFrontmatter` / `decodeLayersFromFrontmatter` pair
33
+ * handles a single Layer array for the editor's `dataLayers="…"` Pandoc
34
+ * param path; that path stays base64 (it's a different, per-block
35
+ * mechanism) and is re-exported here for locality.
36
+ */
37
+
38
+ import type { Layer } from '../schemas/Doc.js';
39
+ import type { CustomTemplateDefinition } from '../schemas/CustomTemplates.js';
40
+ import { FRONTMATTER_CUSTOM_TEMPLATES_KEY } from '../schemas/CustomTemplates.js';
41
+
42
+ const DEFAULT_VIEWPORT = { width: 1920, height: 1080 };
43
+
44
+ /** Re-export for callers that need the canonical key spelling. */
45
+ export { FRONTMATTER_CUSTOM_TEMPLATES_KEY };
46
+
47
+ // ─── Compact key codec ──────────────────────────────────────────────
48
+
49
+ /**
50
+ * Long → short property-name map. Values must be unique and must not
51
+ * collide with any real key that passes through unmapped (those are
52
+ * 1-char — `x`/`y`/`d`/`id`/`to` — or full words; the codes here are
53
+ * 2-letter combos, so they never clash). A field literally named like a
54
+ * code (e.g. a real `fz` key) would be the one corruption case — none
55
+ * exist in the schema, and the round-trip test guards against it.
56
+ */
57
+ const LONG_TO_SHORT: Readonly<Record<string, string>> = {
58
+ // definition
59
+ label: 'lb',
60
+ description: 'ds',
61
+ viewport: 'vp',
62
+ layers: 'ly',
63
+ name: 'nm',
64
+ // layer
65
+ type: 'ty',
66
+ position: 'po',
67
+ content: 'ct',
68
+ animation: 'am',
69
+ // position
70
+ width: 'wd',
71
+ height: 'hg',
72
+ anchor: 'an',
73
+ // text
74
+ text: 'tx',
75
+ style: 'sy',
76
+ fontSize: 'fz',
77
+ fontFamily: 'ff',
78
+ fontWeight: 'fw',
79
+ color: 'cl',
80
+ textAlign: 'al',
81
+ verticalAlign: 'vl',
82
+ lineHeight: 'lh',
83
+ shadow: 'sd',
84
+ background: 'bg',
85
+ backgroundOpacity: 'bo',
86
+ backgroundGradient: 'bj',
87
+ borderColor: 'bc',
88
+ borderWidth: 'bw',
89
+ borderStyle: 'bs',
90
+ padding: 'pd',
91
+ maxLines: 'mx',
92
+ // shape / path
93
+ shape: 'sp',
94
+ fill: 'fl',
95
+ fillOpacity: 'fo',
96
+ gradient: 'gr',
97
+ stroke: 'sk',
98
+ strokeWidth: 'sw',
99
+ borderRadius: 'br',
100
+ shapeKind: 'kd',
101
+ dasharray: 'da',
102
+ arrow: 'ar',
103
+ startMarker: 'st',
104
+ endMarker: 'em',
105
+ // image
106
+ src: 'sc',
107
+ alt: 'at',
108
+ fit: 'ft',
109
+ credit: 'cr',
110
+ license: 'lc',
111
+ // gradient
112
+ from: 'fr',
113
+ angle: 'ag',
114
+ };
115
+
116
+ const SHORT_TO_LONG: Readonly<Record<string, string>> = Object.fromEntries(
117
+ Object.entries(LONG_TO_SHORT).map(([long, short]) => [short, long]),
118
+ );
119
+
120
+ /** Recursively rename an object's keys via `map`, leaving unmapped keys. */
121
+ function renameKeys(value: unknown, map: Readonly<Record<string, string>>): unknown {
122
+ if (Array.isArray(value)) return value.map((v) => renameKeys(v, map));
123
+ if (value && typeof value === 'object') {
124
+ const out: Record<string, unknown> = {};
125
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
126
+ out[map[k] ?? k] = renameKeys(v, map);
127
+ }
128
+ return out;
129
+ }
130
+ return value;
131
+ }
132
+
133
+ function isDefaultViewport(v: { width: number; height: number } | undefined): boolean {
134
+ return !v || (v.width === DEFAULT_VIEWPORT.width && v.height === DEFAULT_VIEWPORT.height);
135
+ }
136
+
137
+ // ─── Single-Layer base64 codec (legacy `dataLayers` path) ───────────
138
+
139
+ /**
140
+ * Base64-encode a Layer array as JSON, UTF-8 safe. Used by the editor's
141
+ * per-block `dataLayers="…"` Pandoc param (not the doc-level template
142
+ * list, which uses the compact JSON above).
143
+ *
144
+ * `btoa` only accepts Latin1 strings — any character outside that range
145
+ * (e.g. an em-dash in a description) throws — so we round through
146
+ * `TextEncoder`. Works in Node ≥18 and browsers.
147
+ */
148
+ export function encodeLayersForFrontmatter(layers: readonly Layer[]): string {
149
+ return utf8ToBase64(JSON.stringify(layers));
150
+ }
151
+
152
+ /** Inverse of {@link encodeLayersForFrontmatter}. Returns [] on parse failure. */
153
+ export function decodeLayersFromFrontmatter(encoded: string): Layer[] {
154
+ try {
155
+ const json = base64ToUtf8(encoded);
156
+ const parsed = JSON.parse(json);
157
+ return Array.isArray(parsed) ? (parsed as Layer[]) : [];
158
+ } catch {
159
+ return [];
160
+ }
161
+ }
162
+
163
+ /** UTF-8 safe `btoa` — uses TextEncoder so arbitrary Unicode round-trips. */
164
+ function utf8ToBase64(str: string): string {
165
+ const bytes = new TextEncoder().encode(str);
166
+ if (typeof globalThis.btoa === 'function') {
167
+ let binary = '';
168
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
169
+ return globalThis.btoa(binary);
170
+ }
171
+ return Buffer.from(bytes).toString('base64');
172
+ }
173
+
174
+ /** UTF-8 safe `atob`. */
175
+ function base64ToUtf8(b64: string): string {
176
+ if (typeof globalThis.atob === 'function') {
177
+ const binary = globalThis.atob(b64);
178
+ const bytes = new Uint8Array(binary.length);
179
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
180
+ return new TextDecoder().decode(bytes);
181
+ }
182
+ return Buffer.from(b64, 'base64').toString('utf-8');
183
+ }
184
+
185
+ // ─── Definition list read / write ───────────────────────────────────
186
+
187
+ /**
188
+ * Read the `squisq-custom-templates` frontmatter key and decode it into
189
+ * an array of CustomTemplateDefinitions. Returns undefined when the key
190
+ * is absent or unparseable so callers can omit the field from the Doc.
191
+ *
192
+ * Accepts, in order: the compact JSON object (current), a base64-JSON
193
+ * string (legacy), and an already-structured array/object (in case a
194
+ * richer YAML parser delivers it). Malformed payloads return undefined
195
+ * rather than failing the whole doc load.
196
+ */
197
+ export function readCustomTemplatesFromFrontmatter(
198
+ frontmatter: Record<string, unknown> | undefined,
199
+ ): CustomTemplateDefinition[] | undefined {
200
+ if (!frontmatter) return undefined;
201
+ const candidates = normalizeCandidates(frontmatter[FRONTMATTER_CUSTOM_TEMPLATES_KEY]);
202
+ if (!candidates) return undefined;
203
+ const out: CustomTemplateDefinition[] = [];
204
+ for (const entry of candidates) {
205
+ if (!entry || typeof entry !== 'object') continue;
206
+ const e = entry as Record<string, unknown>;
207
+ if (typeof e.name !== 'string' || typeof e.label !== 'string') continue;
208
+ if (!Array.isArray(e.layers)) continue;
209
+ const def: CustomTemplateDefinition = {
210
+ name: e.name,
211
+ label: e.label,
212
+ viewport: readViewport(e.viewport),
213
+ layers: e.layers as Layer[],
214
+ };
215
+ if (typeof e.description === 'string') def.description = e.description;
216
+ out.push(def);
217
+ }
218
+ return out.length > 0 ? out : undefined;
219
+ }
220
+
221
+ /**
222
+ * Encode a list of custom template definitions into the compact JSON
223
+ * object described in the module header. Returns undefined when the
224
+ * input list is empty so callers can leave the key off the output.
225
+ */
226
+ export function writeCustomTemplatesToFrontmatter(
227
+ templates: readonly CustomTemplateDefinition[] | undefined,
228
+ ): string | undefined {
229
+ if (!templates || templates.length === 0) return undefined;
230
+ const map: Record<string, Record<string, unknown>> = {};
231
+ for (const def of templates) {
232
+ const entry: Record<string, unknown> = { lb: def.label };
233
+ if (def.description) entry.ds = def.description;
234
+ if (!isDefaultViewport(def.viewport)) entry.vp = def.viewport;
235
+ entry.ly = renameKeys(def.layers, LONG_TO_SHORT);
236
+ map[def.name] = entry;
237
+ }
238
+ return JSON.stringify(map);
239
+ }
240
+
241
+ function readViewport(raw: unknown): { width: number; height: number } {
242
+ if (raw && typeof raw === 'object') {
243
+ const v = raw as Record<string, unknown>;
244
+ const w = typeof v.width === 'number' ? v.width : DEFAULT_VIEWPORT.width;
245
+ const h = typeof v.height === 'number' ? v.height : DEFAULT_VIEWPORT.height;
246
+ return { width: w, height: h };
247
+ }
248
+ return DEFAULT_VIEWPORT;
249
+ }
250
+
251
+ /**
252
+ * Expand the compact, name-keyed map into full-keyed definition objects
253
+ * that {@link readCustomTemplatesFromFrontmatter}'s validation loop
254
+ * understands. The `name` comes from the map key.
255
+ */
256
+ function expandCompactMap(map: Record<string, unknown>): unknown[] {
257
+ return Object.entries(map).map(([name, raw]) => {
258
+ const e = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>;
259
+ const def: Record<string, unknown> = {
260
+ name,
261
+ label: e.lb,
262
+ viewport: e.vp ?? { ...DEFAULT_VIEWPORT },
263
+ layers: renameKeys(e.ly ?? [], SHORT_TO_LONG),
264
+ };
265
+ if (typeof e.ds === 'string') def.description = e.ds;
266
+ return def;
267
+ });
268
+ }
269
+
270
+ /** Turn a parsed value into a list of full-keyed definition objects. */
271
+ function fromParsed(parsed: unknown): unknown[] | null {
272
+ if (Array.isArray(parsed)) return parsed; // legacy structured array
273
+ if (parsed && typeof parsed === 'object')
274
+ return expandCompactMap(parsed as Record<string, unknown>);
275
+ return null;
276
+ }
277
+
278
+ function tryJson(s: string): unknown | undefined {
279
+ try {
280
+ return JSON.parse(s);
281
+ } catch {
282
+ return undefined;
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Normalize any supported payload shape into a list of full-keyed
288
+ * definition objects. Returns null when the value is none of them.
289
+ */
290
+ function normalizeCandidates(raw: unknown): unknown[] | null {
291
+ if (raw == null) return null;
292
+ if (Array.isArray(raw)) return raw;
293
+ if (typeof raw === 'object') return expandCompactMap(raw as Record<string, unknown>);
294
+ if (typeof raw !== 'string') return null;
295
+
296
+ // Current format: a JSON object/array literal stored verbatim.
297
+ const direct = tryJson(raw.trim());
298
+ if (direct !== undefined) return fromParsed(direct);
299
+
300
+ // Legacy format: base64-encoded JSON.
301
+ try {
302
+ const decoded = tryJson(base64ToUtf8(raw));
303
+ if (decoded !== undefined) return fromParsed(decoded);
304
+ } catch {
305
+ // not valid base64 either
306
+ }
307
+ return null;
308
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Frontmatter serialization for user-defined custom themes.
3
+ *
4
+ * The theme analog of {@link ./customTemplatesFrontmatter.ts}. Custom Theme
5
+ * definitions live in the document's YAML frontmatter under the key
6
+ * `squisq-custom-themes`, stored as a single **compact JSON** object keyed
7
+ * by theme id:
8
+ *
9
+ * ```yaml
10
+ * squisq-custom-themes: {"my-brand":{"schemaVersion":"1","id":"my-brand",…}}
11
+ * ```
12
+ *
13
+ * Squisq's frontmatter parser is line-based; a JSON object literal
14
+ * round-trips through it verbatim (single line, no leading quote to strip),
15
+ * so the value is written **unquoted** and stays human-readable and diffable
16
+ * — the same mechanism the custom-templates codec relies on.
17
+ *
18
+ * Only one theme is *active* per doc (selected by id via the `squisq-theme`
19
+ * frontmatter key / `Doc.themeId`), but the payload is a keyed map — parallel
20
+ * to custom templates — so a doc can carry a small catalog and switch between
21
+ * them, and `resolveThemeForDoc` can resolve any of them doc-scoped.
22
+ *
23
+ * Malformed entries are dropped (via `validateTheme`) rather than failing the
24
+ * whole doc load, matching the tolerant behavior of the templates reader.
25
+ */
26
+
27
+ import type { Theme } from '../schemas/Theme.js';
28
+ import { FRONTMATTER_CUSTOM_THEMES_KEY } from '../schemas/Theme.js';
29
+ import { validateTheme } from '../schemas/themeValidator.js';
30
+
31
+ /** Re-export for callers that need the canonical key spelling. */
32
+ export { FRONTMATTER_CUSTOM_THEMES_KEY };
33
+
34
+ /**
35
+ * Normalize the raw frontmatter value into an array of candidate objects.
36
+ * Accepts, in order: a JSON string (current, from the line-based parser),
37
+ * an already-parsed object map (keyed by id), and an array (in case a richer
38
+ * YAML parser delivers one). Returns undefined when absent/unparseable.
39
+ */
40
+ function normalizeCandidates(raw: unknown): unknown[] | undefined {
41
+ if (raw === undefined || raw === null) return undefined;
42
+ let value: unknown = raw;
43
+ if (typeof value === 'string') {
44
+ const trimmed = value.trim();
45
+ if (!trimmed) return undefined;
46
+ try {
47
+ value = JSON.parse(trimmed);
48
+ } catch {
49
+ return undefined;
50
+ }
51
+ }
52
+ if (Array.isArray(value)) return value;
53
+ if (value && typeof value === 'object') {
54
+ return Object.values(value as Record<string, unknown>);
55
+ }
56
+ return undefined;
57
+ }
58
+
59
+ /**
60
+ * Read the custom themes inlined into a document's frontmatter. Returns
61
+ * undefined when the key is absent or holds no valid theme, so callers can
62
+ * omit the field from the Doc.
63
+ */
64
+ export function readCustomThemesFromFrontmatter(
65
+ frontmatter: Record<string, unknown> | undefined,
66
+ ): Theme[] | undefined {
67
+ if (!frontmatter) return undefined;
68
+ const candidates = normalizeCandidates(frontmatter[FRONTMATTER_CUSTOM_THEMES_KEY]);
69
+ if (!candidates) return undefined;
70
+ const out: Theme[] = [];
71
+ for (const entry of candidates) {
72
+ const result = validateTheme(entry);
73
+ if (result.valid && result.theme) out.push(result.theme);
74
+ }
75
+ return out.length > 0 ? out : undefined;
76
+ }
77
+
78
+ /**
79
+ * Encode a list of custom themes into the compact JSON object described in
80
+ * the module header (keyed by theme id). Returns undefined when the input is
81
+ * empty so callers can leave the key off the output.
82
+ */
83
+ export function writeCustomThemesToFrontmatter(
84
+ themes: readonly Theme[] | undefined,
85
+ ): string | undefined {
86
+ if (!themes || themes.length === 0) return undefined;
87
+ const map: Record<string, Theme> = {};
88
+ for (const theme of themes) map[theme.id] = theme;
89
+ return JSON.stringify(map);
90
+ }
@@ -24,6 +24,14 @@
24
24
 
25
25
  import type { Doc, Block } from '../schemas/Doc.js';
26
26
  import type { MarkdownDocument, MarkdownBlockNode, MarkdownHeading } from '../markdown/types.js';
27
+ import {
28
+ FRONTMATTER_CUSTOM_TEMPLATES_KEY,
29
+ writeCustomTemplatesToFrontmatter,
30
+ } from './customTemplatesFrontmatter.js';
31
+ import {
32
+ FRONTMATTER_CUSTOM_THEMES_KEY,
33
+ writeCustomThemesToFrontmatter,
34
+ } from './customThemesFrontmatter.js';
27
35
 
28
36
  /**
29
37
  * Convert a Doc with heading-driven blocks back to a MarkdownDocument.
@@ -66,9 +74,36 @@ export function docToMarkdown(doc: Doc): MarkdownDocument {
66
74
  emitBlock(block);
67
75
  }
68
76
 
77
+ // Merge `Doc.customTemplates` into the outgoing frontmatter so the
78
+ // markdown remains the source-of-truth: edits made via the editor's
79
+ // TemplateDesigner round-trip through `docToMarkdown` →
80
+ // `stringifyMarkdown` and are visible to anyone reading the file.
81
+ const customPayload = writeCustomTemplatesToFrontmatter(doc.customTemplates);
82
+ let frontmatter = doc.frontmatter;
83
+ if (customPayload) {
84
+ frontmatter = { ...(frontmatter ?? {}), [FRONTMATTER_CUSTOM_TEMPLATES_KEY]: customPayload };
85
+ } else if (frontmatter && FRONTMATTER_CUSTOM_TEMPLATES_KEY in frontmatter) {
86
+ // The doc has no custom templates anymore — drop the stale
87
+ // frontmatter key so the markdown reflects the current state.
88
+ const { [FRONTMATTER_CUSTOM_TEMPLATES_KEY]: _drop, ...rest } = frontmatter;
89
+ void _drop;
90
+ frontmatter = rest;
91
+ }
92
+
93
+ // Mirror the same round-trip for `Doc.customThemes` (the theme analog).
94
+ const customThemesPayload = writeCustomThemesToFrontmatter(doc.customThemes);
95
+ if (customThemesPayload) {
96
+ frontmatter = { ...(frontmatter ?? {}), [FRONTMATTER_CUSTOM_THEMES_KEY]: customThemesPayload };
97
+ } else if (frontmatter && FRONTMATTER_CUSTOM_THEMES_KEY in frontmatter) {
98
+ const { [FRONTMATTER_CUSTOM_THEMES_KEY]: _dropTheme, ...rest } = frontmatter;
99
+ void _dropTheme;
100
+ frontmatter = rest;
101
+ }
102
+
69
103
  return {
70
104
  type: 'document',
71
105
  children,
106
+ ...(frontmatter && Object.keys(frontmatter).length > 0 ? { frontmatter } : {}),
72
107
  };
73
108
  }
74
109
 
@@ -77,22 +112,56 @@ export function docToMarkdown(doc: Doc): MarkdownDocument {
77
112
  * template and templateOverrides. Returns a (possibly cloned) heading.
78
113
  */
79
114
  function ensureAnnotation(block: Block, heading: MarkdownHeading): MarkdownHeading {
80
- // If the heading already has an annotation, trust it (it came from parsing)
81
- if (heading.templateAnnotation) return heading;
115
+ const attrs = ensureTransitionAttributes(block, heading);
82
116
 
83
117
  // If the block has a non-default template or overrides, inject an annotation
84
- const hasExplicitTemplate = block.template && block.template !== 'sectionHeader';
118
+ const hasExplicitTemplate =
119
+ block.template && block.template !== 'sectionHeader' && block.autoTemplate !== true;
85
120
  const hasOverrides = block.templateOverrides && Object.keys(block.templateOverrides).length > 0;
86
121
 
87
- if (!hasExplicitTemplate && !hasOverrides) return heading;
122
+ // If the heading already has an annotation, trust it (it came from parsing).
123
+ // Transition attrs may still have been injected above if the block changed.
124
+ if (heading.templateAnnotation) {
125
+ return attrs === heading.attributes ? heading : { ...heading, attributes: attrs };
126
+ }
127
+
128
+ if (!hasExplicitTemplate && !hasOverrides) {
129
+ return attrs === heading.attributes ? heading : { ...heading, attributes: attrs };
130
+ }
88
131
 
89
132
  // Clone to avoid mutating the original
90
133
  return {
91
134
  ...heading,
92
135
  children: [...heading.children],
136
+ attributes: attrs,
93
137
  templateAnnotation: {
94
138
  template: block.template ?? 'sectionHeader',
95
139
  ...(hasOverrides ? { params: block.templateOverrides } : {}),
96
140
  },
97
141
  };
98
142
  }
143
+
144
+ function ensureTransitionAttributes(
145
+ block: Block,
146
+ heading: MarkdownHeading,
147
+ ): MarkdownHeading['attributes'] {
148
+ const transition = block.transition;
149
+ if (!transition) return heading.attributes;
150
+
151
+ const attrs = heading.attributes ?? {};
152
+ return {
153
+ ...attrs,
154
+ params: {
155
+ ...(attrs.params ?? {}),
156
+ transition: transition.type,
157
+ ...(transition.duration !== undefined
158
+ ? { transitionDuration: String(transition.duration) }
159
+ : {}),
160
+ ...(transition.direction ? { transitionDirection: transition.direction } : {}),
161
+ },
162
+ blockMeta: {
163
+ ...(attrs.blockMeta ?? {}),
164
+ transition,
165
+ },
166
+ };
167
+ }
@@ -35,7 +35,9 @@ import { VIEWPORT_PRESETS } from '../schemas/Viewport.js';
35
35
  import { createTemplateContext, isTemplateBlock } from '../schemas/BlockTemplates.js';
36
36
  import { DEFAULT_THEME } from '../schemas/themeLibrary.js';
37
37
  import { templateRegistry, resolveTemplateName } from './templates/index.js';
38
- import { expandPersistentLayers } from './templates/persistentLayers.js';
38
+ import { expandPersistentLayers, wrapWithPersistentLayers } from './templates/persistentLayers.js';
39
+ import { applyRenderStyleToLayers } from './utils/applyRenderStyle.js';
40
+ import { fallbackBlockLayers } from './templates/fallbackBlock.js';
39
41
 
40
42
  // ============================================
41
43
  // RenderContext
@@ -109,9 +111,22 @@ export function getLayers(block: DocBlock, context: RenderContext = {}): Layer[]
109
111
  // and the layer list comes back empty.
110
112
  if (isTemplateBlock(block)) {
111
113
  const resolved = resolveTemplateName(block.template);
114
+ const templateCtx = createTemplateContext(theme, blockIndex, totalBlocks, viewport);
112
115
  if (resolved in templateRegistry) {
113
116
  const templateName = resolved as keyof typeof templateRegistry;
114
- const templateCtx = createTemplateContext(theme, blockIndex, totalBlocks, viewport);
117
+ // Aggregate templates (e.g. `diagram`) consume the block's children.
118
+ const maybeChildren = (block as Block).children;
119
+ if (maybeChildren && maybeChildren.length > 0) {
120
+ templateCtx.children = maybeChildren;
121
+ }
122
+ // Effective template input: the block's own fields, then structured
123
+ // body data (```json data fences, GFM tables), then `{[…]}` string
124
+ // overrides — the same merge order buildPreviewDoc uses.
125
+ const { templateData, templateOverrides } = block as Block;
126
+ const input =
127
+ templateData || templateOverrides
128
+ ? ({ ...block, ...templateData, ...templateOverrides } as TemplateBlock)
129
+ : block;
115
130
  let layers: Layer[];
116
131
  try {
117
132
  // Each registry entry accepts its specific TemplateBlock variant; the
@@ -120,21 +135,34 @@ export function getLayers(block: DocBlock, context: RenderContext = {}): Layer[]
120
135
  input: TemplateBlock,
121
136
  ctx: TemplateContext,
122
137
  ) => Layer[];
123
- layers = templateFn(block, templateCtx);
138
+ layers = templateFn(input, templateCtx);
124
139
  if (!Array.isArray(layers)) {
125
- console.error(`Template ${templateName} did not return an array, got:`, typeof layers);
126
- layers = [];
140
+ console.warn(`Template ${templateName} did not return an array, got:`, typeof layers);
141
+ layers = fallbackBlockLayers(block, templateCtx, `Template "${block.template}" failed`);
127
142
  }
128
143
  } catch (err: unknown) {
129
- console.error(`Error expanding template ${templateName}:`, err);
130
- layers = [];
144
+ console.warn(`Error expanding template ${templateName}:`, err);
145
+ layers = fallbackBlockLayers(block, templateCtx, `Template "${block.template}" failed`);
131
146
  }
132
147
 
148
+ // Theme motion defaults apply to template-generated layers only
149
+ // (mirrors expandDocBlocks — the two paths must agree).
150
+ layers = applyRenderStyleToLayers(layers, block as Block, theme);
151
+
133
152
  return injectPersistentLayers(layers, block, context);
134
153
  }
154
+
155
+ // Unknown template — graceful-degradation guarantee: render the
156
+ // block's heading + body text as a plain card with a visible notice
157
+ // instead of a blank slide.
158
+ return injectPersistentLayers(
159
+ fallbackBlockLayers(block, templateCtx, `Unknown template "${block.template}"`),
160
+ block,
161
+ context,
162
+ );
135
163
  }
136
164
 
137
- // 3. Fallback: no layers and no known template
165
+ // 3. Fallback: no layers and no template requested
138
166
  return injectPersistentLayers([], block, context);
139
167
  }
140
168
 
@@ -150,14 +178,9 @@ function injectPersistentLayers(layers: Layer[], block: DocBlock, context: Rende
150
178
  const { persistentLayers } = context;
151
179
  if (!persistentLayers) return layers;
152
180
 
153
- const bottomLayers = expandPersistentLayers(persistentLayers.bottomLayers);
154
- const topLayers = expandPersistentLayers(persistentLayers.topLayers);
155
-
156
- if (bottomLayers.length === 0 && topLayers.length === 0) return layers;
157
-
158
- const templateBlock = block as TemplateBlock;
159
- const useBottom = templateBlock.useBottomLayer !== false;
160
- const useTop = templateBlock.useTopLayer !== false;
181
+ const theme = context.theme ?? DEFAULT_THEME;
182
+ const bottomLayers = expandPersistentLayers(persistentLayers.bottomLayers, theme);
183
+ const topLayers = expandPersistentLayers(persistentLayers.topLayers, theme);
161
184
 
162
- return [...(useBottom ? bottomLayers : []), ...layers, ...(useTop ? topLayers : [])];
185
+ return wrapWithPersistentLayers(layers, block as TemplateBlock, bottomLayers, topLayers);
163
186
  }
package/src/doc/index.ts CHANGED
@@ -1,9 +1,43 @@
1
1
  export * from './templates/index.js';
2
2
  export * from './utils/animationUtils.js';
3
3
  export * from './utils/themeUtils.js';
4
- export { markdownToDoc, flattenBlocks, countBlocks, getBlockDepth } from './markdownToDoc.js';
4
+ export * from './utils/applyRenderStyle.js';
5
+ export * from './utils/imageTreatment.js';
6
+ export * from './templateInputs.js';
7
+ export * from './utils/shapeGeometry.js';
8
+ export {
9
+ markdownToDoc,
10
+ flattenBlocks,
11
+ flattenRenderableBlocks,
12
+ countBlocks,
13
+ getBlockDepth,
14
+ } from './markdownToDoc.js';
5
15
  export type { MarkdownToDocOptions } from './markdownToDoc.js';
6
16
  export { docToMarkdown } from './docToMarkdown.js';
17
+ export {
18
+ encodeLayersForFrontmatter,
19
+ decodeLayersFromFrontmatter,
20
+ readCustomTemplatesFromFrontmatter,
21
+ writeCustomTemplatesToFrontmatter,
22
+ FRONTMATTER_CUSTOM_TEMPLATES_KEY,
23
+ } from './customTemplatesFrontmatter.js';
24
+ export {
25
+ readCustomThemesFromFrontmatter,
26
+ writeCustomThemesToFrontmatter,
27
+ FRONTMATTER_CUSTOM_THEMES_KEY,
28
+ } from './customThemesFrontmatter.js';
29
+ export { resolveThemeForDoc } from './resolveDocTheme.js';
7
30
  export { getLayers } from './getLayers.js';
8
31
  export type { RenderContext } from './getLayers.js';
9
32
  export { resolveAudioMapping, scoreTextSimilarity } from './audioMapping.js';
33
+ export {
34
+ isDataFence,
35
+ parseDataFence,
36
+ parseYamlSubset,
37
+ findFirstTable,
38
+ extractTableData,
39
+ } from './structuredData.js';
40
+ export type { DataFenceParseResult, ExtractedTableData } from './structuredData.js';
41
+ export { validateMarkdownSource, validateMarkdownDoc } from './validate.js';
42
+ export type { ValidateOptions, MarkdownValidationResult } from './validate.js';
43
+ export { fallbackBlockLayers } from './templates/fallbackBlock.js';