Debian Codegraph @

web/src/components/MarkdownContent.jsx

raw
1 import * as React from "react";
2 import { useEffect } from "react";
3 import { useRemark } from "react-remark";
4 import styled from "@emotion/styled";
5 import { sanitizeUrl } from "../app/utils";
6
7 // Strip unsafe URL protocols (javascript:, data:, ...) from links and images. Without
8 // this, React blocks javascript: URLs at render time and throws an uncaught "React has
9 // blocked a javascript: URL" error.
10 const SafeLink = ({ href, children, ...props }) => (
11 <a href={sanitizeUrl(href)} {...props}>
12 {children}
13 </a>
14 );
15
16 const SafeImage = ({ src, alt, ...props }) => <img src={sanitizeUrl(src)} alt={alt} {...props} />;
17
18 const MarkdownContainer = styled("div")`
19 line-height: 1;
20
21 h1,
22 h2,
23 h3,
24 h4,
25 h5,
26 h6,
27 p,
28 pre,
29 ul,
30 ol,
31 blockquote {
32 margin: 0;
33 }
34
35 p {
36 line-height: 1.5;
37 }
38
39 blockquote,
40 pre {
41 border-radius: 3px;
42 background: ${(props) => (props.theme.palette.mode === "light" ? "#f5f5f5" : "#333")};
43 }
44
45 pre {
46 overflow-x: scroll;
47 padding: 0.9rem;
48 }
49
50 ul,
51 ol,
52 blockquote {
53 padding-inline: 1rem;
54 }
55
56 img {
57 max-width: 100%;
58 }
59 `;
60
61 // Renders text/markdown notification bodies. react-remark (and its remark/unified
62 // dependency stack) is heavy, so this component lives in its own module and is loaded
63 // lazily by Notifications.jsx -- it only ships when a markdown message is actually shown.
64 const MarkdownContent = ({ content }) => {
65 const [reactContent, setMarkdownSource] = useRemark({
66 rehypeReactOptions: { components: { a: SafeLink, img: SafeImage } },
67 });
68
69 useEffect(() => {
70 setMarkdownSource(content);
71 }, [content]);
72
73 return <MarkdownContainer>{reactContent}</MarkdownContainer>;
74 };
75
76 export default MarkdownContent;