-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtemplate-blocks.tsx
More file actions
80 lines (70 loc) · 2.11 KB
/
template-blocks.tsx
File metadata and controls
80 lines (70 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import CodeBlock from "@theme/CodeBlock";
import { evaluateSync } from "@mdx-js/mdx";
import { useMDXComponents } from "@mdx-js/react";
import { type ComponentType, type ReactNode, useMemo } from "react";
import * as jsxRuntime from "react/jsx-runtime";
import type { TemplateContentBlock } from "@/lib/template-content";
type TemplateRecipeComponentMap = Record<string, ComponentType>;
type TemplateBlockRendererProps = {
blocks: TemplateContentBlock[];
recipeComponents: TemplateRecipeComponentMap;
};
type MarkdownBlockProps = {
content: string;
};
function TemplateMarkdownBlock({ content }: MarkdownBlockProps): ReactNode {
const components = useMDXComponents();
const Content = useMemo(() => {
return evaluateSync(content, {
...jsxRuntime,
useMDXComponents: () => components,
}).default;
}, [components, content]);
return <Content />;
}
type CodeBlockProps = {
language: string;
content: string;
};
function TemplateCodeBlock({ language, content }: CodeBlockProps): ReactNode {
return (
<CodeBlock language={language} title={language || undefined}>
{content.replace(/\n$/, "")}
</CodeBlock>
);
}
export function TemplateBlockRenderer({
blocks,
recipeComponents,
}: TemplateBlockRendererProps): ReactNode {
return (
<>
{blocks.map((block, index) => {
const key = `${block.type}-${index}`;
switch (block.type) {
case "markdown":
return <TemplateMarkdownBlock key={key} content={block.content} />;
case "code":
return (
<TemplateCodeBlock
key={key}
language={block.language}
content={block.content}
/>
);
case "recipe": {
const RecipeComponent = recipeComponents[block.recipeId];
if (!RecipeComponent) {
throw new Error(
`Missing recipe component for template block: ${block.recipeId}`,
);
}
return <RecipeComponent key={key} />;
}
default:
return null;
}
})}
</>
);
}