From 12c551468f9989bef32dba83a48b805bcba7de6f Mon Sep 17 00:00:00 2001 From: spencerwooo Date: Tue, 31 Aug 2021 13:59:31 +0100 Subject: [PATCH] render relative path images in markdown, close #10 --- components/FileListing.tsx | 4 +-- components/previews/MarkdownPreview.tsx | 40 ++++++++++++++++++++----- 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/components/FileListing.tsx b/components/FileListing.tsx index 8c0c2f3..c59731e 100644 --- a/components/FileListing.tsx +++ b/components/FileListing.tsx @@ -274,7 +274,7 @@ const FileListing: FunctionComponent<{ query?: ParsedUrlQuery }> = ({ query }) = {renderReadme && (
- +
)} @@ -303,7 +303,7 @@ const FileListing: FunctionComponent<{ query?: ParsedUrlQuery }> = ({ query }) = return case preview.markdown: - return + return case preview.video: return diff --git a/components/previews/MarkdownPreview.tsx b/components/previews/MarkdownPreview.tsx index 7addc37..4957c58 100644 --- a/components/previews/MarkdownPreview.tsx +++ b/components/previews/MarkdownPreview.tsx @@ -1,4 +1,4 @@ -import { useEffect, FunctionComponent } from 'react' +import { useEffect, FunctionComponent, CSSProperties } from 'react' import Prism from 'prismjs' import ReactMarkdown from 'react-markdown' import gfm from 'remark-gfm' @@ -13,13 +13,35 @@ import Loading from '../Loading' import DownloadBtn from '../DownloadBtn' import { useStaleSWR } from '../../utils/tools' -const MarkdownPreview: FunctionComponent<{ file: any; standalone?: boolean }> = ({ file, standalone = true }) => { +const MarkdownPreview: FunctionComponent<{ file: any; path: string; standalone?: boolean }> = ({ + file, + path, + standalone = true, +}) => { const { data, error } = useStaleSWR(file['@microsoft.graph.downloadUrl']) + // The parent folder of the markdown file, which is also the relative image folder + const parentPath = path.substring(0, path.lastIndexOf('/')) + // Check if the image is relative path instead of a absolute url + const isUrlAbsolute = url => url.indexOf('://') > 0 || url.indexOf('//') === 0 + // Custom renderer to render images with relative path + const relativeImagePathRenderer = { + img: ({ alt, src, title, style }: { alt?: string; src?: string; title?: string; style?: CSSProperties }) => { + if (isUrlAbsolute(src as string)) { + return ( + // eslint-disable-next-line @next/next/no-img-element + {alt} + ) + } + return ( + // eslint-disable-next-line @next/next/no-img-element + {alt} + ) + }, + } + useEffect(() => { - if (typeof window !== 'undefined') { - Prism.highlightAll() - } + Prism.highlightAll() }, [data]) if (error) { @@ -46,8 +68,12 @@ const MarkdownPreview: FunctionComponent<{ file: any; standalone?: boolean }> = : 'markdown-body p-3 dark:text-white' } > - {/* Using rehypeRaw to render HTML inside Markdown, is potentially dangerous, use under safe environments. (#18) */} - + {/* Using rehypeRaw to render HTML inside Markdown is potentially dangerous, use under safe environments. (#18) */} + {data}