diff options
Diffstat (limited to 'src/lib/Markdown/Markdown.tsx')
-rw-r--r-- | src/lib/Markdown/Markdown.tsx | 69 |
1 files changed, 59 insertions, 10 deletions
diff --git a/src/lib/Markdown/Markdown.tsx b/src/lib/Markdown/Markdown.tsx index cfcf117..c0389dc 100644 --- a/src/lib/Markdown/Markdown.tsx +++ b/src/lib/Markdown/Markdown.tsx @@ -1,33 +1,82 @@ import React, { useState, useEffect } from 'react'; +import { Link, Typography } from '@material-ui/core'; import axios from 'axios'; +import ReactMarkdown from 'react-markdown'; +import emoji from 'remark-gemoji'; -import Section from './Section'; +import CodeBlock from './CodeBlock'; +import InlineCode from './InlineCode'; +import Heading from './Heading'; +import Image from './Image'; interface PropTypes { - data?: string; + source?: string; url?: string; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + context?: Record<string, any>; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + plugins?: any[] } const resolveUrls = (line: string, baseUrl: string): string => line.replace( /src="(?!http)(.*)"[\s>]/, (match, url) => `src="${baseUrl}/${url}?sanitize=true"`, ).replace( - /\[(.*\]?.*)\]\((?!http)(.+?)\)/, + /\[(.*\]?.*)\]\((?!http)(.+?)\)/g, (match, text, url) => `[${text}](${baseUrl}/${url})`, ); -const Markdown: React.FC<PropTypes> = ({ data, url }) => { - const [markdown, setMarkdown] = useState<string>(data || ''); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const WrappedInlineCode = (context: Record<string, any>): React.FC => ({ children }) => { + if (typeof children === 'string' && children?.startsWith('$')) { + const symbol = children.slice(1); + return context[symbol] || null; + } + return <InlineCode>{children}</InlineCode>; +}; + +const Markdown: React.FC<PropTypes> = ({ + children, + url, + source, + context = {}, + plugins = [], +}) => { + const [markdown, setMarkdown] = useState<string>(source || ''); - if (url) axios.get(url).then(response => setMarkdown(response.data)); + useEffect(() => { + if (url) axios.get(url).then(response => setMarkdown(response.data)); + }, [url]); useEffect(() => { - if (!url) setMarkdown(data || ''); - }, [data, url]); + if (source) setMarkdown(source); + }, [source]); + + useEffect(() => { + if (children && typeof children === 'string') setMarkdown(children); + }, [children]); const baseUrl = url?.slice(0, url.lastIndexOf('/')) || ''; - const lines = markdown.split(/\r?\n/).map(line => resolveUrls(line, baseUrl)); - return <Section rawLines={lines} />; + const sanitized = resolveUrls(markdown, baseUrl); + + const renderers = { + heading: Heading, + code: CodeBlock, + link: Link, + image: Image, + inlineCode: WrappedInlineCode(context), + }; + + return ( + <Typography> + <ReactMarkdown + source={sanitized} + renderers={renderers} + plugins={[emoji, ...plugins]} + allowDangerousHtml + /> + </Typography> + ); }; |