aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Markdown/Markdown.tsx
blob: 955aeda386776faa1a5d83cd8841b3d01a0f1787 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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 CodeBlock from './CodeBlock';
import InlineCode from './InlineCode';
import Heading from './Heading';
import Image from './Image';

interface PropTypes {
  data?: string;
  url?: string;
}

const resolveUrls = (line: string, baseUrl: string): string => line.replace(
  /src="(?!http)(.*)"[\s>]/,
  (match, url) => `src="${baseUrl}/${url}?sanitize=true"`,
).replace(
  /\[(.*\]?.*)\]\((?!http)(.+?)\)/g,
  (match, text, url) => `[${text}](${baseUrl}/${url})`,
);

const renderers = {
  heading: Heading,
  inlineCode: InlineCode,
  code: CodeBlock,
  link: Link,
  image: Image,
};

const Markdown: React.FC<PropTypes> = ({ data, url }) => {
  const [markdown, setMarkdown] = useState<string>(data || '');

  if (url) axios.get(url).then(response => setMarkdown(response.data));

  useEffect(() => {
    if (!url) setMarkdown(data || '');
  }, [data, url]);

  const baseUrl = url?.slice(0, url.lastIndexOf('/')) || '';

  const sanitized = resolveUrls(markdown, baseUrl);

  return (
    <Typography>
      <ReactMarkdown
        renderers={renderers}
        plugins={[emoji]}
        allowDangerousHtml
      >
        {sanitized}
      </ReactMarkdown>
    </Typography>
  );
};


export default Markdown;