From e27056e3062903d8788870976b37a6a846a03946 Mon Sep 17 00:00:00 2001 From: zaidmukaddam Date: Sat, 10 Aug 2024 10:21:43 +0530 Subject: [PATCH] fix: react-markdown max depth error --- app/page.tsx | 65 ++++++++++++++++++++++++++++++---------------------- 1 file changed, 37 insertions(+), 28 deletions(-) diff --git a/app/page.tsx b/app/page.tsx index 41d3ad5..573e942 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -11,7 +11,7 @@ React, ReactNode, useMemo } from 'react'; -import ReactMarkdown from 'react-markdown'; +import ReactMarkdown, { Components } from 'react-markdown'; import remarkGfm from 'remark-gfm'; import { useChat } from 'ai/react'; import { ToolInvocation } from 'ai'; @@ -174,8 +174,15 @@ export default function Home() { ); }; - const renderCitation = (citationText: string, citationLink: string, index: number) => { - const faviconUrl = `https://www.google.com/s2/favicons?domain=${new URL(citationLink).hostname}`; + interface CitationComponentProps { + href: string; + children: React.ReactNode; + index: number; + } + + const CitationComponent: React.FC = React.memo(({ href, children, index }) => { + const citationText = Array.isArray(children) ? children[0] : children; + const faviconUrl = `https://www.google.com/s2/favicons?domain=${new URL(href).hostname}`; return ( @@ -186,23 +193,21 @@ export default function Home() { Favicon - - {citationLink} + + {href} ); - }; - - const CitationComponent: React.FC<{ href: string; children: ReactNode; index: number }> = React.memo(({ href, children, index }) => { - const citationText = Array.isArray(children) ? children[0] : children; - - return renderCitation(citationText as string, href, index); }); CitationComponent.displayName = "CitationComponent"; - const MarkdownRenderer: React.FC<{ content: string }> = React.memo(({ content }) => { + interface MarkdownRendererProps { + content: string; + } + + const MarkdownRenderer: React.FC = React.memo(({ content }) => { const citationLinks = useMemo(() => { return [...content.matchAll(/\[([^\]]+)\]\(([^)]+)\)/g)].map(([_, text, link]) => ({ text, @@ -210,24 +215,27 @@ export default function Home() { })); }, [content]); + const components: Partial = useMemo(() => ({ + a: ({ href, children }) => { + if (!href) return null; + const index = citationLinks.findIndex((link) => link.link === href); + return index !== -1 ? ( + + {children} + + ) : ( + + {children} + + ); + }, + }), [citationLinks]); + return ( { - const index = citationLinks.findIndex((link: { link: string | undefined; }) => link.link === href); - return index !== -1 ? ( - - {children} - - ) : ( - - {children} - - ); - }, - }} > {content} @@ -236,6 +244,7 @@ export default function Home() { MarkdownRenderer.displayName = "MarkdownRenderer"; + useEffect(() => { if (bottomRef.current) { bottomRef.current.scrollIntoView({ behavior: "smooth" }); @@ -288,7 +297,7 @@ export default function Home() { return (
-
+