onedrive/components/previews/MarkdownPreview.tsx

59 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-06-25 15:08:04 +00:00
import { useEffect, FunctionComponent } from 'react'
import axios from 'axios'
import useSWR from 'swr'
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 'katex/dist/katex.min.css'
import 'github-markdown-css/github-markdown.css'
import FourOhFour from '../FourOhFour'
import Loading from '../Loading'
import DownloadBtn from '../DownloadBtn'
const fetcher = (url: string) => axios.get(url).then(res => res.data)
2021-06-30 11:53:17 +00:00
const MarkdownPreview: FunctionComponent<{ file: any; standalone?: boolean }> = ({ file, standalone = true }) => {
2021-06-25 15:08:04 +00:00
const { data, error } = useSWR(file['@microsoft.graph.downloadUrl'], fetcher)
useEffect(() => {
if (typeof window !== 'undefined') {
Prism.highlightAll()
}
}, [data])
if (error) {
return (
2021-06-30 11:53:17 +00:00
<div className={`${standalone ? 'shadow bg-white rounded p-3' : ''}`}>
2021-06-25 15:08:04 +00:00
<FourOhFour errorMsg={error.message} />
</div>
)
}
if (!data) {
return (
2021-06-30 11:53:17 +00:00
<div className={standalone ? 'shadow bg-white rounded p-3' : ''}>
2021-06-25 15:08:04 +00:00
<Loading loadingText="Loading file content..." />
</div>
)
}
return (
<>
2021-06-30 11:53:17 +00:00
<div className={standalone ? 'markdown-body shadow bg-white rounded p-3' : 'markdown-body p-3'}>
2021-06-25 15:08:04 +00:00
<ReactMarkdown remarkPlugins={[gfm, remarkMath]} rehypePlugins={[rehypeKatex]}>
{data}
</ReactMarkdown>
</div>
2021-06-30 11:53:17 +00:00
{standalone && (
<div className="mt-4">
<DownloadBtn downloadUrl={file['@microsoft.graph.downloadUrl']} />
</div>
)}
2021-06-25 15:08:04 +00:00
</>
)
}
export default MarkdownPreview