aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Markdown/Markdown.tsx
blob: cfcf117e4cc225c8eaf34ddad7fd33c133fdd588 (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
import React, { useState, useEffect } from 'react';
import axios from 'axios';

import Section from './Section';

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)(.+?)\)/,
  (match, text, url) => `[${text}](${baseUrl}/${url})`,
);

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 lines = markdown.split(/\r?\n/).map(line => resolveUrls(line, baseUrl));
  return <Section rawLines={lines} />;
};


export default Markdown;