@bendyline/squisq 1.4.1 → 1.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -1
- package/dist/{ContentContainer-DNx460y8.d.ts → ContentContainer-BXUlIf18.d.ts} +6 -2
- package/dist/{Doc-BeSeH2iX.d.ts → Doc-BBVGq1_9.d.ts} +922 -273
- package/dist/{ImageEditDoc-BTIvw0oq.d.ts → ImageEditDoc-FuyGtt6o.d.ts} +11 -4
- package/dist/{chunk-ZTX4PFFT.js → chunk-2OIBZYKP.js} +75 -2
- package/dist/chunk-2OIBZYKP.js.map +1 -0
- package/dist/chunk-2UQOHYE2.js +45 -0
- package/dist/chunk-2UQOHYE2.js.map +1 -0
- package/dist/chunk-6ATE2PSM.js +344 -0
- package/dist/chunk-6ATE2PSM.js.map +1 -0
- package/dist/{chunk-57CVQCFX.js → chunk-A4O7GIWE.js} +74 -23
- package/dist/chunk-A4O7GIWE.js.map +1 -0
- package/dist/{chunk-5WFRKURX.js → chunk-DLXZMS5K.js} +4 -2
- package/dist/chunk-DLXZMS5K.js.map +1 -0
- package/dist/chunk-ET53IIEP.js +1 -0
- package/dist/chunk-ET53IIEP.js.map +1 -0
- package/dist/chunk-HWVFJAAH.js +362 -0
- package/dist/chunk-HWVFJAAH.js.map +1 -0
- package/dist/{chunk-2TMAWB4Y.js → chunk-IMSCRLLV.js} +1 -1
- package/dist/chunk-IMSCRLLV.js.map +1 -0
- package/dist/{chunk-B4EEON3N.js → chunk-KKNUBQ6Y.js} +536 -103
- package/dist/chunk-KKNUBQ6Y.js.map +1 -0
- package/dist/chunk-LDQ2HJIX.js +596 -0
- package/dist/chunk-LDQ2HJIX.js.map +1 -0
- package/dist/chunk-LH7I6SH7.js +7208 -0
- package/dist/chunk-LH7I6SH7.js.map +1 -0
- package/dist/chunk-PGGGKYWG.js +1 -0
- package/dist/chunk-PGGGKYWG.js.map +1 -0
- package/dist/{chunk-7UDSRZKG.js → chunk-Q3ROPT5H.js} +35 -14
- package/dist/chunk-Q3ROPT5H.js.map +1 -0
- package/dist/chunk-QE7TWGVT.js +178 -0
- package/dist/chunk-QE7TWGVT.js.map +1 -0
- package/dist/chunk-RUDYOTA6.js +345 -0
- package/dist/chunk-RUDYOTA6.js.map +1 -0
- package/dist/{chunk-K32VJONL.js → chunk-T5UK6YOB.js} +41 -2
- package/dist/chunk-T5UK6YOB.js.map +1 -0
- package/dist/{chunk-3K5OG6KI.js → chunk-TEEEILMP.js} +412 -186
- package/dist/chunk-TEEEILMP.js.map +1 -0
- package/dist/{chunk-FR2RBTKO.js → chunk-TQWLI6S2.js} +93 -27
- package/dist/chunk-TQWLI6S2.js.map +1 -0
- package/dist/{chunk-WMOI7FN3.js → chunk-UY7KGQ5R.js} +12 -2
- package/dist/{chunk-WMOI7FN3.js.map → chunk-UY7KGQ5R.js.map} +1 -1
- package/dist/{chunk-3E5F2XMR.js → chunk-VWUFZ6ZG.js} +29 -2
- package/dist/chunk-VWUFZ6ZG.js.map +1 -0
- package/dist/chunk-ZLQKNOZQ.js +1 -0
- package/dist/chunk-ZLQKNOZQ.js.map +1 -0
- package/dist/doc/index.d.ts +5 -5
- package/dist/doc/index.js +135 -8
- package/dist/generate/index.d.ts +3 -74
- package/dist/generate/index.js +2 -7
- package/dist/icons/index.d.ts +3 -26
- package/dist/icons/index.js +13 -0
- package/dist/icons/inlineIconMarker.d.ts +1 -0
- package/dist/icons/inlineIconMarker.js +15 -0
- package/dist/icons/inlineIconMarker.js.map +1 -0
- package/dist/imageEdit/index.d.ts +12 -6
- package/dist/imageEdit/index.js +4 -1
- package/dist/index.d.ts +14 -11
- package/dist/index.js +265 -37
- package/dist/inlineIconMarker-CiE8Hlvz.d.ts +59 -0
- package/dist/jsonForm/index.d.ts +42 -1
- package/dist/jsonForm/index.js +9 -1
- package/dist/markdown/index.d.ts +228 -3
- package/dist/markdown/index.js +42 -7
- package/dist/recommend/index.d.ts +1 -1
- package/dist/recommend/index.js +3 -2
- package/dist/schemas/index.d.ts +28 -8
- package/dist/schemas/index.js +36 -8
- package/dist/spatial/index.d.ts +9 -4
- package/dist/spatial/index.js +1 -1
- package/dist/storage/index.d.ts +2 -2
- package/dist/storage/index.js +1 -1
- package/dist/story/index.d.ts +1021 -41
- package/dist/story/index.js +135 -8
- package/dist/{themeLibrary-BHjJ0Qx6.d.ts → themeLibrary-CehcJhzz.d.ts} +1 -1
- package/dist/timing/index.js +3 -5
- package/dist/transform/index.d.ts +48 -10
- package/dist/transform/index.js +17 -481
- package/dist/transform/index.js.map +1 -1
- package/dist/{types-BdZkdJ3z.d.ts → types-DlAZ7MW4.d.ts} +115 -1
- package/dist/versions/index.d.ts +1 -1
- package/package.json +6 -1
- package/src/__tests__/animationUtils.test.ts +40 -0
- package/src/__tests__/annotationCoercion.test.ts +243 -0
- package/src/__tests__/applyRenderStyle.test.ts +146 -0
- package/src/__tests__/atmosphereLayers.test.ts +108 -0
- package/src/__tests__/attrTokens.test.ts +162 -0
- package/src/__tests__/contentExtractor.test.ts +60 -0
- package/src/__tests__/coverBlock.test.ts +46 -1
- package/src/__tests__/customTemplateSample.test.ts +144 -0
- package/src/__tests__/customTemplatesFrontmatter.test.ts +236 -0
- package/src/__tests__/customThemesFrontmatter.test.ts +145 -0
- package/src/__tests__/diagramBlock.test.ts +122 -0
- package/src/__tests__/diagramLayout.test.ts +134 -0
- package/src/__tests__/drawing.test.ts +109 -0
- package/src/__tests__/drawingBlock.test.ts +124 -0
- package/src/__tests__/drawingLayout.test.ts +171 -0
- package/src/__tests__/geohash.test.ts +6 -5
- package/src/__tests__/getLayers.test.ts +6 -2
- package/src/__tests__/getLayersFallback.test.ts +103 -0
- package/src/__tests__/imageEditExportSvg.test.ts +70 -0
- package/src/__tests__/imageEditVersions.test.ts +72 -0
- package/src/__tests__/inlineIconMarker.test.ts +36 -0
- package/src/__tests__/inputDescriptors.test.ts +162 -0
- package/src/__tests__/jsonForm.tokens.test.ts +84 -0
- package/src/__tests__/layoutBlock.test.ts +83 -0
- package/src/__tests__/layoutLayout.test.ts +169 -0
- package/src/__tests__/markdown.test.ts +87 -0
- package/src/__tests__/markdownSanitize.test.ts +79 -0
- package/src/__tests__/markdownToDoc.test.ts +391 -2
- package/src/__tests__/mediaAnnotations.test.ts +91 -0
- package/src/__tests__/mediaSchedule.test.ts +118 -0
- package/src/__tests__/pandocAttrParse.test.ts +187 -0
- package/src/__tests__/resolveDocTheme.test.ts +55 -0
- package/src/__tests__/rootExports.test.ts +43 -0
- package/src/__tests__/shapeGeometry.test.ts +89 -0
- package/src/__tests__/shapeVocabulary.test.ts +133 -0
- package/src/__tests__/structuredData.test.ts +249 -0
- package/src/__tests__/templateAnnotationParse.test.ts +108 -0
- package/src/__tests__/templateMetadata.test.ts +31 -0
- package/src/__tests__/templates.test.ts +257 -4
- package/src/__tests__/themeCompile.test.ts +42 -0
- package/src/__tests__/themeValidator.test.ts +6 -0
- package/src/__tests__/transformV2.test.ts +137 -0
- package/src/__tests__/transitionNormalize.test.ts +61 -0
- package/src/__tests__/validateDoc.test.ts +260 -0
- package/src/doc/annotationBlocks.ts +117 -0
- package/src/doc/customTemplatesFrontmatter.ts +314 -0
- package/src/doc/customThemesFrontmatter.ts +95 -0
- package/src/doc/docToMarkdown.ts +104 -5
- package/src/doc/getLayers.ts +49 -17
- package/src/doc/index.ts +47 -1
- package/src/doc/markdownToDoc.ts +411 -13
- package/src/doc/mediaAnnotations.ts +100 -0
- package/src/doc/resolveDocTheme.ts +55 -0
- package/src/doc/standaloneAnnotation.ts +58 -0
- package/src/doc/structuredData.ts +301 -0
- package/src/doc/templateInputs.ts +240 -0
- package/src/doc/templates/__tests__/customTemplate.test.ts +170 -0
- package/src/doc/templates/__tests__/customTemplateRegistry.test.ts +110 -0
- package/src/doc/templates/accentImage.ts +30 -6
- package/src/doc/templates/captionUtils.ts +23 -0
- package/src/doc/templates/comparisonBar.ts +33 -18
- package/src/doc/templates/coverBlock.ts +35 -5
- package/src/doc/templates/customTemplate.ts +51 -0
- package/src/doc/templates/dataTable.ts +37 -19
- package/src/doc/templates/dateEvent.ts +41 -20
- package/src/doc/templates/definitionCard.ts +26 -18
- package/src/doc/templates/diagramBlock.ts +204 -0
- package/src/doc/templates/diagramLayout.ts +159 -0
- package/src/doc/templates/drawingBlock.ts +325 -0
- package/src/doc/templates/drawingLayout.ts +539 -0
- package/src/doc/templates/factCard.ts +54 -26
- package/src/doc/templates/fallbackBlock.ts +123 -0
- package/src/doc/templates/featureBlock.ts +20 -13
- package/src/doc/templates/fullBleedQuote.ts +18 -8
- package/src/doc/templates/imageWithCaption.ts +30 -15
- package/src/doc/templates/index.ts +225 -46
- package/src/doc/templates/inputDescriptors.ts +432 -0
- package/src/doc/templates/layoutBlock.ts +43 -0
- package/src/doc/templates/layoutLayout.ts +243 -0
- package/src/doc/templates/listBlock.ts +56 -30
- package/src/doc/templates/mapBlock.ts +15 -12
- package/src/doc/templates/metadata.ts +120 -0
- package/src/doc/templates/persistentLayers.ts +129 -11
- package/src/doc/templates/photoGrid.ts +22 -34
- package/src/doc/templates/pullQuote.ts +30 -12
- package/src/doc/templates/quoteBlock.ts +54 -29
- package/src/doc/templates/sectionHeader.ts +25 -11
- package/src/doc/templates/statHighlight.ts +39 -22
- package/src/doc/templates/titleBlock.ts +59 -21
- package/src/doc/templates/tokens/__tests__/resolveTokens.test.ts +487 -0
- package/src/doc/templates/tokens/resolveTokens.ts +453 -0
- package/src/doc/templates/twoColumn.ts +48 -30
- package/src/doc/templates/videoPullQuote.ts +22 -12
- package/src/doc/templates/videoWithCaption.ts +21 -15
- package/src/doc/utils/animationUtils.ts +267 -3
- package/src/doc/utils/applyRenderStyle.ts +113 -0
- package/src/doc/utils/imageTreatment.ts +70 -0
- package/src/doc/utils/nearest.ts +59 -0
- package/src/doc/utils/shapeGeometry.ts +464 -0
- package/src/doc/utils/themeUtils.ts +75 -1
- package/src/doc/validate.ts +575 -0
- package/src/generate/contentExtractor.ts +148 -35
- package/src/generate/index.ts +0 -3
- package/src/icons/index.ts +8 -0
- package/src/icons/inlineIconMarker.ts +73 -0
- package/src/imageEdit/export.ts +85 -2
- package/src/imageEdit/index.ts +1 -0
- package/src/imageEdit/persistence.ts +51 -0
- package/src/index.ts +2 -0
- package/src/jsonForm/index.ts +2 -0
- package/src/jsonForm/tokens.ts +78 -0
- package/src/markdown/annotationCoercion.ts +295 -0
- package/src/markdown/attrTokens.ts +241 -0
- package/src/markdown/convert.ts +229 -26
- package/src/markdown/index.ts +37 -0
- package/src/markdown/sanitize.ts +318 -0
- package/src/markdown/stringify.ts +96 -6
- package/src/markdown/types.ts +66 -0
- package/src/markdown/utils.ts +111 -2
- package/src/recommend/templates.ts +24 -0
- package/src/schemas/BlockTemplates.ts +133 -4
- package/src/schemas/CustomTemplates.ts +126 -0
- package/src/schemas/Doc.ts +387 -65
- package/src/schemas/ImageEditDoc.ts +11 -4
- package/src/schemas/Media.ts +169 -0
- package/src/schemas/Theme.ts +23 -1
- package/src/schemas/Transitions.ts +224 -0
- package/src/schemas/colorUtils.ts +33 -0
- package/src/schemas/fontStacks.ts +5 -2
- package/src/schemas/index.ts +3 -0
- package/src/schemas/themeCompile.ts +24 -5
- package/src/schemas/themeValidator.ts +49 -11
- package/src/schemas/themes/cinematic.json +69 -12
- package/src/schemas/themes/documentary.json +58 -11
- package/src/schemas/themes/gezellig.json +60 -11
- package/src/schemas/themes/magazine.json +54 -9
- package/src/schemas/themes/morning-light.json +52 -9
- package/src/schemas/themes/standard-dark.json +48 -13
- package/src/schemas/themes/standard.json +44 -12
- package/src/schemas/themes/tech-dark.json +65 -12
- package/src/spatial/Geohash.ts +52 -21
- package/src/storage/ContentContainer.ts +6 -2
- package/src/transform/applyTransform.ts +43 -4
- package/src/transform/index.ts +1 -0
- package/src/transform/registry.ts +44 -13
- package/src/transform/styles/dataDriven.ts +2 -1
- package/src/transform/styles/documentary.ts +2 -1
- package/src/transform/styles/magazine.ts +3 -1
- package/src/transform/styles/minimal.ts +2 -1
- package/src/transform/styles/narrative.ts +3 -1
- package/src/transform/templateSelector.ts +87 -11
- package/src/transform/types.ts +35 -2
- package/dist/chunk-2TMAWB4Y.js.map +0 -1
- package/dist/chunk-3E5F2XMR.js.map +0 -1
- package/dist/chunk-3K5OG6KI.js.map +0 -1
- package/dist/chunk-4X3JQXNM.js +0 -35
- package/dist/chunk-4X3JQXNM.js.map +0 -1
- package/dist/chunk-57CVQCFX.js.map +0 -1
- package/dist/chunk-5WFRKURX.js.map +0 -1
- package/dist/chunk-7UDSRZKG.js.map +0 -1
- package/dist/chunk-B4EEON3N.js.map +0 -1
- package/dist/chunk-FR2RBTKO.js.map +0 -1
- package/dist/chunk-H3AXU4MJ.js +0 -179
- package/dist/chunk-H3AXU4MJ.js.map +0 -1
- package/dist/chunk-K32VJONL.js.map +0 -1
- package/dist/chunk-KSWJR66U.js +0 -3706
- package/dist/chunk-KSWJR66U.js.map +0 -1
- package/dist/chunk-MYIH7FWD.js +0 -145
- package/dist/chunk-MYIH7FWD.js.map +0 -1
- package/dist/chunk-ZTX4PFFT.js.map +0 -1
- package/src/__tests__/slideshowGenerator.test.ts +0 -128
- package/src/generate/slideshowGenerator.ts +0 -273
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { validateMarkdownSource } from '../doc/validate.js';
|
|
3
|
+
import { writeCustomTemplatesToFrontmatter } from '../doc/customTemplatesFrontmatter';
|
|
4
|
+
import type { CustomTemplateDefinition } from '../schemas/CustomTemplates.js';
|
|
5
|
+
|
|
6
|
+
function codes(md: string, options?: Parameters<typeof validateMarkdownSource>[1]): string[] {
|
|
7
|
+
return validateMarkdownSource(md, options).diagnostics.map((d) => d.code);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
describe('validateMarkdownSource — templates', () => {
|
|
11
|
+
it('passes a clean document', () => {
|
|
12
|
+
const result = validateMarkdownSource('# Title\n\nBody.\n\n## Section {[quote]}\n\nA quote.\n');
|
|
13
|
+
expect(result.diagnostics).toEqual([]);
|
|
14
|
+
expect(result.errorCount).toBe(0);
|
|
15
|
+
expect(result.warningCount).toBe(0);
|
|
16
|
+
expect(result.infoCount).toBe(0);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('flags unknown templates with a did-you-mean suggestion', () => {
|
|
20
|
+
const result = validateMarkdownSource('## Gallery {[photGrid columns=3]}');
|
|
21
|
+
expect(result.warningCount).toBe(1);
|
|
22
|
+
const d = result.diagnostics[0];
|
|
23
|
+
expect(d.code).toBe('unknown-template');
|
|
24
|
+
expect(d.message).toContain('photGrid');
|
|
25
|
+
expect(d.message).toContain('Did you mean "photoGrid"?');
|
|
26
|
+
expect(d.line).toBe(1);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('accepts legacy template aliases', () => {
|
|
30
|
+
expect(codes('## X {[titleBlock]}')).toEqual([]);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('accepts extra templates supplied by the host app', () => {
|
|
34
|
+
expect(codes('## X {[hero]}', { extraTemplates: ['hero'] })).toEqual([]);
|
|
35
|
+
expect(codes('## X {[hero]}')).toEqual(['unknown-template']);
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
describe('validateMarkdownSource — unparsed annotations', () => {
|
|
40
|
+
it('flags {[…]} text in body content (annotations are heading-only)', () => {
|
|
41
|
+
const result = validateMarkdownSource('## X\n\n- {[imageWithCaption src=photo.jpg]}\n');
|
|
42
|
+
const d = result.diagnostics.find((x) => x.code === 'unparsed-annotation');
|
|
43
|
+
expect(d).toBeDefined();
|
|
44
|
+
expect(d!.message).toContain('headings');
|
|
45
|
+
expect(d!.line).toBe(3);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('flags non-trailing {[…]} text left in a heading', () => {
|
|
49
|
+
const result = validateMarkdownSource('## The {[chart]} section\n');
|
|
50
|
+
expect(result.diagnostics.map((d) => d.code)).toContain('unparsed-annotation');
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('does not flag resolved inline icons or code blocks', () => {
|
|
54
|
+
const md = '## X\n\nUse {[github]} for code.\n\n```\nliteral {[notathing]}\n```\n';
|
|
55
|
+
expect(codes(md)).toEqual([]);
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
describe('validateMarkdownSource — attributes and structure', () => {
|
|
60
|
+
it('surfaces malformed heading-attribute values', () => {
|
|
61
|
+
const result = validateMarkdownSource('## X {#a x=abc}');
|
|
62
|
+
const d = result.diagnostics.find((x) => x.code === 'invalid-attribute');
|
|
63
|
+
expect(d).toBeDefined();
|
|
64
|
+
expect(d!.message).toContain('x');
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('includes conversion diagnostics (duplicate ids, bad fences)', () => {
|
|
68
|
+
const md = '## A {#dup}\n\n## B {#dup}\n\n```json data\nnot json\n```\n';
|
|
69
|
+
const result = validateMarkdownSource(md);
|
|
70
|
+
const found = result.diagnostics.map((d) => d.code);
|
|
71
|
+
expect(found).toContain('duplicate-id');
|
|
72
|
+
expect(found).toContain('data-fence-parse');
|
|
73
|
+
expect(result.errorCount).toBe(2);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
describe('validateMarkdownSource — conflicting annotation keys', () => {
|
|
78
|
+
it('flags a block-meta key set differently in both {[…]} and {…}', () => {
|
|
79
|
+
const result = validateMarkdownSource('## X {[sectionHeader duration=8]} {#x duration=10}\n');
|
|
80
|
+
const d = result.diagnostics.find((x) => x.code === 'conflicting-annotation-key');
|
|
81
|
+
expect(d).toBeDefined();
|
|
82
|
+
expect(d!.severity).toBe('info');
|
|
83
|
+
expect(d!.message).toBe(
|
|
84
|
+
'"duration" is set in both {[…]} (8) and {…} (10) — the {…} value wins.',
|
|
85
|
+
);
|
|
86
|
+
expect(d!.blockId).toBe('x');
|
|
87
|
+
expect(d!.line).toBe(1);
|
|
88
|
+
expect(result.infoCount).toBe(1);
|
|
89
|
+
expect(result.errorCount).toBe(0);
|
|
90
|
+
expect(result.warningCount).toBe(0);
|
|
91
|
+
// Precedence itself is unchanged: the Pandoc value is in effect.
|
|
92
|
+
expect(result.doc.blocks[0].duration).toBe(10);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('stays silent when both forms agree', () => {
|
|
96
|
+
expect(codes('## X {[sectionHeader duration=8]} {#x duration=8}\n')).toEqual([]);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('ignores non-block-meta keys (they land in different channels)', () => {
|
|
100
|
+
// `style` goes to templateOverrides ({[…]}) and metadata ({…}) — no conflict.
|
|
101
|
+
expect(codes('## X {[factCard style=minimal]} {#x style=bold}\n')).toEqual([]);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it('reports each conflicting key separately', () => {
|
|
105
|
+
const result = validateMarkdownSource(
|
|
106
|
+
'## X {[sectionHeader duration=8 startTime=1]} {#x duration=10 startTime=2}\n',
|
|
107
|
+
);
|
|
108
|
+
const found = result.diagnostics.filter((d) => d.code === 'conflicting-annotation-key');
|
|
109
|
+
expect(found).toHaveLength(2);
|
|
110
|
+
expect(result.infoCount).toBe(2);
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
describe('validateMarkdownSource — assets', () => {
|
|
115
|
+
it('flags relative image references missing from the asset set', () => {
|
|
116
|
+
const result = validateMarkdownSource('## X\n\n\n', {
|
|
117
|
+
assets: new Set<string>(),
|
|
118
|
+
});
|
|
119
|
+
const d = result.diagnostics.find((x) => x.code === 'missing-asset');
|
|
120
|
+
expect(d).toBeDefined();
|
|
121
|
+
expect(d!.message).toContain('images/hero.jpg');
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('passes when the asset exists, and skips absolute/external URLs', () => {
|
|
125
|
+
const md =
|
|
126
|
+
'## X\n\n\n\n\n\n\n';
|
|
127
|
+
expect(codes(md, { assets: new Set(['images/hero.jpg']) })).toEqual([]);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('checks media params from {[…]} annotations', () => {
|
|
131
|
+
const result = validateMarkdownSource('## X {[imageWithCaption src=missing.png]}', {
|
|
132
|
+
assets: new Set<string>(),
|
|
133
|
+
});
|
|
134
|
+
expect(result.diagnostics.map((d) => d.code)).toContain('missing-asset');
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it('skips asset checks entirely when no asset set is provided', () => {
|
|
138
|
+
expect(codes('## X\n\n\n')).toEqual([]);
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
describe('validateMarkdownSource — template inputs', () => {
|
|
143
|
+
it('flags an unknown input with a did-you-mean suggestion', () => {
|
|
144
|
+
const result = validateMarkdownSource('## Where {[map centre="47.6,-122.3"]}');
|
|
145
|
+
const d = result.diagnostics.find((x) => x.code === 'unknown-input');
|
|
146
|
+
expect(d).toBeDefined();
|
|
147
|
+
expect(d!.severity).toBe('warning');
|
|
148
|
+
expect(d!.message).toContain('centre');
|
|
149
|
+
expect(d!.message).toContain('Did you mean "center"?');
|
|
150
|
+
expect(d!.line).toBe(1);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it('flags a value outside a closed enum', () => {
|
|
154
|
+
const result = validateMarkdownSource('## Where {[map center="1,2" mapStyle="nope"]}');
|
|
155
|
+
const d = result.diagnostics.find((x) => x.code === 'invalid-input-value');
|
|
156
|
+
expect(d).toBeDefined();
|
|
157
|
+
expect(d!.message).toContain('mapStyle');
|
|
158
|
+
expect(d!.message).toContain('terrain');
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('flags a missing required input', () => {
|
|
162
|
+
const codesFor = codes('## Compare {[twoColumn]}');
|
|
163
|
+
expect(codesFor.filter((c) => c === 'missing-input')).toEqual([
|
|
164
|
+
'missing-input',
|
|
165
|
+
'missing-input',
|
|
166
|
+
]);
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it('does not fire missing-input when the value is derivable from the body', () => {
|
|
170
|
+
const md = '## Caption {[imageWithCaption]}\n\n\n';
|
|
171
|
+
// imageSrc is required, but derivable from the body image → no warning.
|
|
172
|
+
expect(codes(md)).not.toContain('missing-input');
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it('does fire missing-input when the value is not derivable and absent', () => {
|
|
176
|
+
// No body image → imageSrc is neither present nor derivable.
|
|
177
|
+
expect(codes('## Caption {[imageWithCaption]}')).toContain('missing-input');
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it('does not lint blocks that resolve to a doc-declared custom template', () => {
|
|
181
|
+
// A custom template that shadows the built-in "map" name carries its own
|
|
182
|
+
// arbitrary inputs — the built-in descriptors must not be applied to it.
|
|
183
|
+
const custom: CustomTemplateDefinition = {
|
|
184
|
+
name: 'map',
|
|
185
|
+
label: 'My Map',
|
|
186
|
+
description: 'custom',
|
|
187
|
+
viewport: { width: 1920, height: 1080 },
|
|
188
|
+
layers: [
|
|
189
|
+
{
|
|
190
|
+
id: 't',
|
|
191
|
+
type: 'text',
|
|
192
|
+
position: { x: '5%', y: '10%' },
|
|
193
|
+
content: { text: '{title}', style: { fontSize: 40, color: '#000' } },
|
|
194
|
+
},
|
|
195
|
+
],
|
|
196
|
+
};
|
|
197
|
+
const encoded = writeCustomTemplatesToFrontmatter([custom])!;
|
|
198
|
+
const md = `---\nsquisq-custom-templates: ${encoded}\n---\n\n## Hi {[map foo="bar"]}\n`;
|
|
199
|
+
const codesFor = validateMarkdownSource(md).diagnostics.map((d) => d.code);
|
|
200
|
+
expect(codesFor).not.toContain('unknown-input');
|
|
201
|
+
expect(codesFor).not.toContain('missing-input');
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
it('does not lint templates without descriptors', () => {
|
|
205
|
+
// sectionHeader has no input descriptors → arbitrary keys are not flagged.
|
|
206
|
+
expect(codes('## Break {[sectionHeader whatever=5]}')).toEqual([]);
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
it('leaves a clean, fully-specified block with no findings', () => {
|
|
210
|
+
const md = '## Where {[map center="47.6,-122.3" zoom=9 mapStyle="terrain"]}';
|
|
211
|
+
expect(codes(md)).toEqual([]);
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
describe('validateMarkdownSource — standalone annotations (S2)', () => {
|
|
216
|
+
it('does not flag a valid standalone template annotation as unparsed', () => {
|
|
217
|
+
const result = validateMarkdownSource('# H\n\n{[quote]}\n\nquoted\n');
|
|
218
|
+
expect(result.diagnostics.find((d) => d.code === 'unparsed-annotation')).toBeUndefined();
|
|
219
|
+
expect(result.diagnostics.find((d) => d.code === 'unknown-template')).toBeUndefined();
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it('reports unknown-template for a standalone annotation with a bad name', () => {
|
|
223
|
+
const result = validateMarkdownSource('# H\n\n{[quotte]}\n\nquoted\n');
|
|
224
|
+
const d = result.diagnostics.find((x) => x.code === 'unknown-template');
|
|
225
|
+
expect(d).toBeDefined();
|
|
226
|
+
expect(d!.message).toContain('quotte');
|
|
227
|
+
// Not double-reported as an unparsed annotation.
|
|
228
|
+
expect(result.diagnostics.find((x) => x.code === 'unparsed-annotation')).toBeUndefined();
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
it('still flags {[…]} nested inside a list (not a standalone block)', () => {
|
|
232
|
+
const result = validateMarkdownSource('## X\n\n- {[imageWithCaption src=x.jpg]}\n');
|
|
233
|
+
const d = result.diagnostics.find((x) => x.code === 'unparsed-annotation');
|
|
234
|
+
expect(d).toBeDefined();
|
|
235
|
+
expect(d!.message).toContain('standalone paragraphs');
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
describe('validateMarkdownSource — possible-data-fence (S3)', () => {
|
|
240
|
+
const info = (md: string) =>
|
|
241
|
+
validateMarkdownSource(md).diagnostics.filter((d) => d.code === 'possible-data-fence');
|
|
242
|
+
|
|
243
|
+
it('nudges an unmarked json fence inside a template-annotated block', () => {
|
|
244
|
+
const md = '## Numbers {[dataTable]}\n\n```json\n{ "headers": ["A"], "rows": [] }\n```\n';
|
|
245
|
+
const d = info(md);
|
|
246
|
+
expect(d).toHaveLength(1);
|
|
247
|
+
expect(d[0].severity).toBe('info');
|
|
248
|
+
expect(d[0].message).toContain('```json data');
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it('does not fire for a code sample in a non-templated prose section', () => {
|
|
252
|
+
const md = '## Notes\n\n```json\n{ "a": 1 }\n```\n';
|
|
253
|
+
expect(info(md)).toHaveLength(0);
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
it('does not fire when the fence already has the data marker', () => {
|
|
257
|
+
const md = '## Numbers {[dataTable]}\n\n```json data\n{ "headers": ["A"], "rows": [] }\n```\n';
|
|
258
|
+
expect(info(md)).toHaveLength(0);
|
|
259
|
+
});
|
|
260
|
+
});
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standalone template-annotation block extraction.
|
|
3
|
+
*
|
|
4
|
+
* A paragraph whose entire trimmed text is exactly `{[templateName key=value …]}`
|
|
5
|
+
* — where `templateName` is not a media name (media annotations are extracted
|
|
6
|
+
* first, into typed clips) — becomes a *heading-less template block*. The body
|
|
7
|
+
* nodes that follow it, up to the next heading or the next standalone
|
|
8
|
+
* annotation, become that block's `contents`.
|
|
9
|
+
*
|
|
10
|
+
* This is the block analog of {@link import('./mediaAnnotations.js').extractMediaFromContents}:
|
|
11
|
+
* both walk a block's body `contents` and lift standalone `{[…]}` paragraphs
|
|
12
|
+
* out, sharing the {@link parseStandaloneAnnotation} parser. Runs AFTER media
|
|
13
|
+
* extraction (so media names keep their meaning) and BEFORE structured-data
|
|
14
|
+
* parsing (so `json data` / `yaml data` fences attach to the new blocks).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { Block } from '../schemas/Doc.js';
|
|
18
|
+
import type { MarkdownBlockNode } from '../markdown/types.js';
|
|
19
|
+
import { coerceAnnotationValues, type CoercedBlockMeta } from '../markdown/annotationCoercion.js';
|
|
20
|
+
import { resolveTemplateName } from './templates/index.js';
|
|
21
|
+
import { isMediaAnnotationName } from './mediaAnnotations.js';
|
|
22
|
+
import { parseStandaloneAnnotation, type ParsedAnnotation } from './standaloneAnnotation.js';
|
|
23
|
+
|
|
24
|
+
/** Configuration for {@link extractTemplateBlocksFromContents}. */
|
|
25
|
+
export interface StandaloneBlockOptions {
|
|
26
|
+
/** Produce a unique block id for a parsed standalone annotation. */
|
|
27
|
+
makeId: (parsed: ParsedAnnotation) => string;
|
|
28
|
+
/** Initial `duration` for a produced block (the timing pass overrides it). */
|
|
29
|
+
defaultDuration: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The split produced by {@link extractTemplateBlocksFromContents}. */
|
|
33
|
+
export interface TemplateBlockExtraction {
|
|
34
|
+
/** Contents before the first standalone template annotation (stay on the
|
|
35
|
+
* containing block). */
|
|
36
|
+
leading: MarkdownBlockNode[];
|
|
37
|
+
/** Heading-less blocks, each carrying the body nodes that followed its
|
|
38
|
+
* annotation up to the next annotation / end of contents. */
|
|
39
|
+
blocks: Block[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Apply coerced block-meta values onto a produced block. Mirrors
|
|
44
|
+
* `markdownToDoc`'s `applyBlockMeta` so a standalone `{[quote duration=8]}`
|
|
45
|
+
* honors the same block-meta keys a heading `{[…]}` annotation would.
|
|
46
|
+
*/
|
|
47
|
+
function applyBlockMeta(block: Block, m: CoercedBlockMeta): void {
|
|
48
|
+
if (m.x != null) block.x = m.x;
|
|
49
|
+
if (m.y != null) block.y = m.y;
|
|
50
|
+
if (m.startTime != null) block.startTime = m.startTime;
|
|
51
|
+
if (m.duration != null) block.duration = m.duration;
|
|
52
|
+
if (m.connectsTo) block.connectsTo = m.connectsTo;
|
|
53
|
+
if (m.transition) block.transition = m.transition;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Build a heading-less block from a parsed standalone template annotation. */
|
|
57
|
+
function makeStandaloneBlock(parsed: ParsedAnnotation, options: StandaloneBlockOptions): Block {
|
|
58
|
+
// `parsed.template` is guaranteed defined by the caller's guard.
|
|
59
|
+
const rawTemplate = parsed.template as string;
|
|
60
|
+
const params = parsed.params;
|
|
61
|
+
const hasParams = Object.keys(params).length > 0;
|
|
62
|
+
|
|
63
|
+
const block: Block = {
|
|
64
|
+
id: options.makeId(parsed),
|
|
65
|
+
startTime: 0,
|
|
66
|
+
duration: options.defaultDuration,
|
|
67
|
+
audioSegment: 0,
|
|
68
|
+
template: resolveTemplateName(rawTemplate),
|
|
69
|
+
standaloneAnnotation: true,
|
|
70
|
+
// Keep the raw (un-resolved) name so validation can report the exact
|
|
71
|
+
// requested name — symmetric with `sourceHeading.templateAnnotation`.
|
|
72
|
+
sourceAnnotation: { template: rawTemplate, ...(hasParams ? { params } : {}) },
|
|
73
|
+
// Only carry a display title when the author supplied one.
|
|
74
|
+
...(params.title ? { title: params.title } : {}),
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
if (hasParams) {
|
|
78
|
+
block.templateOverrides = params;
|
|
79
|
+
applyBlockMeta(block, coerceAnnotationValues(params).blockMeta);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return block;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Walk `contents`, lifting standalone template-annotation paragraphs into
|
|
87
|
+
* heading-less blocks. Nodes after an annotation (until the next annotation
|
|
88
|
+
* or the end of `contents`) attach to that block. Media annotations are left
|
|
89
|
+
* in place — they are extracted separately, before this runs. `contents` is
|
|
90
|
+
* not mutated; the split is returned.
|
|
91
|
+
*/
|
|
92
|
+
export function extractTemplateBlocksFromContents(
|
|
93
|
+
contents: MarkdownBlockNode[] | undefined,
|
|
94
|
+
options: StandaloneBlockOptions,
|
|
95
|
+
): TemplateBlockExtraction {
|
|
96
|
+
const leading: MarkdownBlockNode[] = [];
|
|
97
|
+
const blocks: Block[] = [];
|
|
98
|
+
let current: Block | null = null;
|
|
99
|
+
|
|
100
|
+
for (const node of contents ?? []) {
|
|
101
|
+
const parsed = parseStandaloneAnnotation(node);
|
|
102
|
+
const isTemplateAnnotation =
|
|
103
|
+
parsed != null && parsed.template != null && !isMediaAnnotationName(parsed.template);
|
|
104
|
+
|
|
105
|
+
if (isTemplateAnnotation) {
|
|
106
|
+
const block = makeStandaloneBlock(parsed as ParsedAnnotation, options);
|
|
107
|
+
blocks.push(block);
|
|
108
|
+
current = block;
|
|
109
|
+
} else if (current) {
|
|
110
|
+
(current.contents ??= []).push(node);
|
|
111
|
+
} else {
|
|
112
|
+
leading.push(node);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return { leading, blocks };
|
|
117
|
+
}
|
|
@@ -0,0 +1,314 @@
|
|
|
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
|
+
options?: { pretty?: boolean },
|
|
229
|
+
): string | undefined {
|
|
230
|
+
if (!templates || templates.length === 0) return undefined;
|
|
231
|
+
const map: Record<string, Record<string, unknown>> = {};
|
|
232
|
+
for (const def of templates) {
|
|
233
|
+
const entry: Record<string, unknown> = { lb: def.label };
|
|
234
|
+
if (def.description) entry.ds = def.description;
|
|
235
|
+
if (!isDefaultViewport(def.viewport)) entry.vp = def.viewport;
|
|
236
|
+
entry.ly = renameKeys(def.layers, LONG_TO_SHORT);
|
|
237
|
+
map[def.name] = entry;
|
|
238
|
+
}
|
|
239
|
+
// Pretty output is multi-line, so it rides out as a YAML literal block
|
|
240
|
+
// scalar (see `formatBlockScalar` / stringify's frontmatter path) and
|
|
241
|
+
// parses back via `JSON.parse`. Default stays compact (single line) so
|
|
242
|
+
// existing docs and snapshots are byte-unchanged. The compact key codec
|
|
243
|
+
// (LONG_TO_SHORT) is applied in both modes.
|
|
244
|
+
return JSON.stringify(map, null, options?.pretty ? 2 : undefined);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function readViewport(raw: unknown): { width: number; height: number } {
|
|
248
|
+
if (raw && typeof raw === 'object') {
|
|
249
|
+
const v = raw as Record<string, unknown>;
|
|
250
|
+
const w = typeof v.width === 'number' ? v.width : DEFAULT_VIEWPORT.width;
|
|
251
|
+
const h = typeof v.height === 'number' ? v.height : DEFAULT_VIEWPORT.height;
|
|
252
|
+
return { width: w, height: h };
|
|
253
|
+
}
|
|
254
|
+
return DEFAULT_VIEWPORT;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Expand the compact, name-keyed map into full-keyed definition objects
|
|
259
|
+
* that {@link readCustomTemplatesFromFrontmatter}'s validation loop
|
|
260
|
+
* understands. The `name` comes from the map key.
|
|
261
|
+
*/
|
|
262
|
+
function expandCompactMap(map: Record<string, unknown>): unknown[] {
|
|
263
|
+
return Object.entries(map).map(([name, raw]) => {
|
|
264
|
+
const e = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>;
|
|
265
|
+
const def: Record<string, unknown> = {
|
|
266
|
+
name,
|
|
267
|
+
label: e.lb,
|
|
268
|
+
viewport: e.vp ?? { ...DEFAULT_VIEWPORT },
|
|
269
|
+
layers: renameKeys(e.ly ?? [], SHORT_TO_LONG),
|
|
270
|
+
};
|
|
271
|
+
if (typeof e.ds === 'string') def.description = e.ds;
|
|
272
|
+
return def;
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Turn a parsed value into a list of full-keyed definition objects. */
|
|
277
|
+
function fromParsed(parsed: unknown): unknown[] | null {
|
|
278
|
+
if (Array.isArray(parsed)) return parsed; // legacy structured array
|
|
279
|
+
if (parsed && typeof parsed === 'object')
|
|
280
|
+
return expandCompactMap(parsed as Record<string, unknown>);
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function tryJson(s: string): unknown | undefined {
|
|
285
|
+
try {
|
|
286
|
+
return JSON.parse(s);
|
|
287
|
+
} catch {
|
|
288
|
+
return undefined;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Normalize any supported payload shape into a list of full-keyed
|
|
294
|
+
* definition objects. Returns null when the value is none of them.
|
|
295
|
+
*/
|
|
296
|
+
function normalizeCandidates(raw: unknown): unknown[] | null {
|
|
297
|
+
if (raw == null) return null;
|
|
298
|
+
if (Array.isArray(raw)) return raw;
|
|
299
|
+
if (typeof raw === 'object') return expandCompactMap(raw as Record<string, unknown>);
|
|
300
|
+
if (typeof raw !== 'string') return null;
|
|
301
|
+
|
|
302
|
+
// Current format: a JSON object/array literal stored verbatim.
|
|
303
|
+
const direct = tryJson(raw.trim());
|
|
304
|
+
if (direct !== undefined) return fromParsed(direct);
|
|
305
|
+
|
|
306
|
+
// Legacy format: base64-encoded JSON.
|
|
307
|
+
try {
|
|
308
|
+
const decoded = tryJson(base64ToUtf8(raw));
|
|
309
|
+
if (decoded !== undefined) return fromParsed(decoded);
|
|
310
|
+
} catch {
|
|
311
|
+
// not valid base64 either
|
|
312
|
+
}
|
|
313
|
+
return null;
|
|
314
|
+
}
|