diff options
author | Eugene Sokolov <eug-vs@keemail.me> | 2021-01-11 22:15:33 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-01-11 22:15:33 +0200 |
commit | 5f72950c56ea8853b41b64a092a2e98dbf53cf3f (patch) | |
tree | 240101bb69aea59c72e1e6fa328b9c5e1729f367 /src/lib/Markdown/Markdown.tsx | |
parent | bc288a43c90ab830019bf077d72081fade76c06e (diff) | |
parent | aa4493b08baae2d41a4c4346b9a5c63b08df471e (diff) | |
download | react-benzin-5f72950c56ea8853b41b64a092a2e98dbf53cf3f.tar.gz |
Merge pull request #20 from eug-vs/feat/react-markdown
Feat: use react-markdown library and support context
Diffstat (limited to 'src/lib/Markdown/Markdown.tsx')
-rw-r--r-- | src/lib/Markdown/Markdown.tsx | 45 |
1 files changed, 40 insertions, 5 deletions
diff --git a/src/lib/Markdown/Markdown.tsx b/src/lib/Markdown/Markdown.tsx index cfcf117..4fa6a9a 100644 --- a/src/lib/Markdown/Markdown.tsx +++ b/src/lib/Markdown/Markdown.tsx @@ -1,22 +1,31 @@ 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; url?: string; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + context?: Record<string, 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: React.FC<PropTypes> = ({ data, url, context = {} }) => { const [markdown, setMarkdown] = useState<string>(data || ''); if (url) axios.get(url).then(response => setMarkdown(response.data)); @@ -26,8 +35,34 @@ const Markdown: React.FC<PropTypes> = ({ data, url }) => { }, [data, url]); 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 WrappedInlineCode: React.FC = ({ children }) => { + if (typeof children === 'string' && children?.startsWith('$')) { + const symbol = children.slice(1); + return context[symbol] || null; + } + return <InlineCode>{children}</InlineCode>; + }; + + const renderers = { + heading: Heading, + code: CodeBlock, + link: Link, + image: Image, + inlineCode: WrappedInlineCode, + }; + + return ( + <Typography> + <ReactMarkdown + source={sanitized} + renderers={renderers} + plugins={[emoji]} + allowDangerousHtml + /> + </Typography> + ); }; |