|
| 1 | +import { css } from "@emotion/react"; |
| 2 | +import styled from "@emotion/styled"; |
| 3 | +import hljs from "highlight.js"; |
| 4 | +import { useEffect, useRef } from "react"; |
| 5 | +import Markdown from "react-markdown"; |
| 6 | +import remarkGfm from "remark-gfm"; |
| 7 | +import { borderRadiusConstants } from "../../Styles/constants"; |
| 8 | + |
| 9 | +export const MarkdownOuterContainer = styled.div( |
| 10 | + ({ theme }) => css` |
| 11 | + padding: 30px; |
| 12 | + * { |
| 13 | + margin: revert; |
| 14 | + padding: revert; |
| 15 | + font-family: revert; |
| 16 | + font-weight: revert; |
| 17 | + } |
| 18 | + blockquote p { |
| 19 | + color: ${theme.augustGrey}; |
| 20 | + } |
| 21 | + pre:has(code) { |
| 22 | + padding: 1rem 2rem; |
| 23 | + border-radius: ${borderRadiusConstants.small}; |
| 24 | + width: 100%; |
| 25 | + background-color: #1c1b1b; |
| 26 | + } |
| 27 | + em { |
| 28 | + font-style: italic; |
| 29 | + } |
| 30 | + a { |
| 31 | + text-decoration: underline; |
| 32 | + } |
| 33 | + h1 { |
| 34 | + font-size: 2rem; |
| 35 | + } |
| 36 | + h2 { |
| 37 | + font-size: 1.7rem; |
| 38 | + } |
| 39 | + h3 { |
| 40 | + font-size: 1.5rem; |
| 41 | + } |
| 42 | + h4 { |
| 43 | + font-size: 1.2rem; |
| 44 | + } |
| 45 | + h5 { |
| 46 | + font-size: 1rem; |
| 47 | + } |
| 48 | + ` |
| 49 | +); |
| 50 | + |
| 51 | +const MarkdownRenderer = ({ markdown }: { markdown: string }) => { |
| 52 | + const mdContainerRef = useRef<HTMLDivElement | null>(null); |
| 53 | + |
| 54 | + // Highlight the content when it's rendered. |
| 55 | + useEffect(() => { |
| 56 | + if (!markdown || !mdContainerRef.current) { |
| 57 | + return; |
| 58 | + } |
| 59 | + // Highlight each code element. |
| 60 | + // This is faster than doing `hljs.highlightAll()`. |
| 61 | + const codeElements = mdContainerRef.current.querySelectorAll("code"); |
| 62 | + for (let i = 0; i < codeElements.length; i++) { |
| 63 | + hljs.highlightElement(codeElements[i]); |
| 64 | + } |
| 65 | + return () => { |
| 66 | + // If this "data-highlighted" attribute isn't reset, it may not |
| 67 | + // highlight the code correctly when the page is revisited. |
| 68 | + for (let i = 0; i < codeElements.length; i++) { |
| 69 | + codeElements[i]?.removeAttribute("data-highlighted"); |
| 70 | + } |
| 71 | + }; |
| 72 | + }, [markdown, mdContainerRef.current]); |
| 73 | + |
| 74 | + return ( |
| 75 | + <MarkdownOuterContainer ref={mdContainerRef}> |
| 76 | + <Markdown remarkPlugins={[remarkGfm]}>{markdown}</Markdown> |
| 77 | + </MarkdownOuterContainer> |
| 78 | + ); |
| 79 | +}; |
| 80 | + |
| 81 | +export default MarkdownRenderer; |
0 commit comments