From ae3228b9b3e95ace25292d0231e98e6087781c0a Mon Sep 17 00:00:00 2001 From: eug-vs Date: Thu, 9 Apr 2020 11:55:46 +0300 Subject: feat: resolve local urls --- src/lib/Markdown/Markdown.tsx | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'src/lib') diff --git a/src/lib/Markdown/Markdown.tsx b/src/lib/Markdown/Markdown.tsx index 0a71fd3..c929c71 100644 --- a/src/lib/Markdown/Markdown.tsx +++ b/src/lib/Markdown/Markdown.tsx @@ -8,15 +8,23 @@ interface PropTypes { url?: string; } +const resolveUrls = (line: string, baseUrl: string = ''): string => { + return line.replace(/src="(?!http)(.*)"[\s>]/, (match, url, offset, string) => `src="${baseUrl}/${url}?sanitize=true"`) + .replace(/\[(.*\]?.*)\]\((?!http)(.+?)\)/, (match, text, url, offset, string) => `[${text}](${baseUrl}/${url})`); +} + const Markdown: React.FC = ({ data, url }) => { const [markdown, setMarkdown] = useState(data || ''); + if (url) axios.get(url).then(response => setMarkdown(response.data)); + useEffect(() => { if (!url) setMarkdown(data || ''); }, [data, url]); - if (url) axios.get(url).then(response => setMarkdown(response.data)); - return
+ const baseUrl = url?.slice(0, url.lastIndexOf('/')); + const lines = markdown.split(/\r?\n/).map(line => resolveUrls(line, baseUrl)); + return
}; -- cgit v1.2.3