import { useEffect, FunctionComponent, CSSProperties } from 'react' import Prism from 'prismjs' import ReactMarkdown from 'react-markdown' import gfm from 'remark-gfm' import remarkMath from 'remark-math' import rehypeKatex from 'rehype-katex' import rehypeRaw from 'rehype-raw' import 'katex/dist/katex.min.css' import FourOhFour from '../FourOhFour' import Loading from '../Loading' import DownloadBtn from '../DownloadBtn' import { useStaleSWR } from '../../utils/tools' 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: string | string[]) => url.indexOf('://') > 0 || url.indexOf('//') === 0 // Custom renderer to render images with relative path const relativeImagePathRenderer = { img: ({ alt, src, title, width, height, style, }: { alt?: string src?: string title?: string width?: string | number height?: string | number 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(() => { Prism.highlightAll() }, [data]) if (error) { return (
) } if (!data) { return (
) } return ( <>
{/* Using rehypeRaw to render HTML inside Markdown is potentially dangerous, use under safe environments. (#18) */} {data}
{standalone && (
)} ) } export default MarkdownPreview