|
1 | | -import React, { useMemo } from "react"; |
| 1 | +import React, { useEffect, useMemo } from "react"; |
2 | 2 | import { View } from "react-native"; |
3 | 3 | import { parseMarkdown } from "./parser"; |
4 | 4 | import { renderNode } from "./renderNode"; |
5 | 5 | import { createRenderers, type RendererColors } from "./renderers"; |
6 | 6 | import type { HastNode, RenderersMap } from "./types"; |
7 | 7 | import { useRuntime } from "@creatorem/ai-chat/runtime"; |
| 8 | +import type { RootContent, Element } from "hast"; |
8 | 9 |
|
9 | 10 | type Props = { |
10 | 11 | content: string; |
11 | 12 | colors: RendererColors; |
12 | 13 | renderers?: Partial<RenderersMap>; |
13 | 14 | }; |
14 | 15 |
|
| 16 | +function collectElementTags(nodes: RootContent[], tags: Set<string>): void { |
| 17 | + for (const node of nodes) { |
| 18 | + if (node.type !== "element") continue; |
| 19 | + const element = node as Element; |
| 20 | + tags.add(element.tagName); |
| 21 | + if (element.children?.length) { |
| 22 | + collectElementTags(element.children as RootContent[], tags); |
| 23 | + } |
| 24 | + } |
| 25 | +} |
| 26 | + |
15 | 27 | export function Markdown({ content, colors, renderers: customRenderers }: Props) { |
16 | 28 | const components = useRuntime().components |
17 | 29 |
|
18 | | - const renderers = useMemo(() => { |
| 30 | + const renderers = useMemo<RenderersMap>(() => { |
19 | 31 | const defaults = createRenderers(colors, components); |
20 | 32 | if (!customRenderers) return defaults; |
21 | | - return { ...defaults, ...customRenderers }; |
22 | | - }, [colors, customRenderers]); |
| 33 | + return { ...defaults, ...customRenderers } as RenderersMap; |
| 34 | + }, [colors, customRenderers, components]); |
23 | 35 |
|
24 | 36 | const tree = useMemo(() => parseMarkdown(content), [content]); |
| 37 | + const customRendererKeys = useMemo( |
| 38 | + () => new Set(Object.keys(customRenderers ?? {})), |
| 39 | + [customRenderers], |
| 40 | + ); |
| 41 | + |
| 42 | + useEffect(() => { |
| 43 | + if (!__DEV__) return; |
| 44 | + |
| 45 | + const usedTags = new Set<string>(); |
| 46 | + collectElementTags(tree.children as RootContent[], usedTags); |
| 47 | + |
| 48 | + const nonCustomizedTags = Array.from(usedTags) |
| 49 | + .filter((tag) => !customRendererKeys.has(tag)) |
| 50 | + .sort(); |
| 51 | + |
| 52 | + if (nonCustomizedTags.length > 0) { |
| 53 | + console.log( |
| 54 | + "[MarkdownRenderer] Tags using default renderer:", |
| 55 | + nonCustomizedTags, |
| 56 | + ); |
| 57 | + } |
| 58 | + }, [tree, customRendererKeys]); |
25 | 59 |
|
26 | 60 | return ( |
27 | 61 | <View> |
|
0 commit comments