2022-04-04 21:13:18 -04:00
|
|
|
import Cookies from "js-cookie"
|
2022-03-09 17:57:44 -05:00
|
|
|
import { memo, useEffect, useState } from "react"
|
2022-03-22 23:16:24 -04:00
|
|
|
import styles from './preview.module.css'
|
2022-03-06 19:46:59 -05:00
|
|
|
|
2022-03-09 17:57:44 -05:00
|
|
|
type Props = {
|
|
|
|
height?: number | string
|
2022-03-22 23:06:15 -04:00
|
|
|
fileId?: string
|
|
|
|
content?: string
|
|
|
|
title?: string
|
2022-03-09 17:57:44 -05:00
|
|
|
// file extensions we can highlight
|
|
|
|
}
|
|
|
|
|
2022-03-22 23:06:15 -04:00
|
|
|
const MarkdownPreview = ({ height = 500, fileId, content, title }: Props) => {
|
|
|
|
const [preview, setPreview] = useState<string>(content || "")
|
|
|
|
const [isLoading, setIsLoading] = useState<boolean>(true)
|
2022-03-09 17:57:44 -05:00
|
|
|
useEffect(() => {
|
2022-03-22 23:06:15 -04:00
|
|
|
async function fetchPost() {
|
|
|
|
if (fileId) {
|
2022-03-24 21:24:09 -04:00
|
|
|
const resp = await fetch(`/api/html/${fileId}`, {
|
2022-03-22 23:06:15 -04:00
|
|
|
method: "GET",
|
|
|
|
})
|
|
|
|
if (resp.ok) {
|
|
|
|
const res = await resp.text()
|
|
|
|
setPreview(res)
|
|
|
|
setIsLoading(false)
|
|
|
|
}
|
2022-03-22 23:16:24 -04:00
|
|
|
} else if (content) {
|
2022-04-04 21:13:18 -04:00
|
|
|
const resp = await fetch("/server-api/files/html", {
|
2022-03-22 23:06:15 -04:00
|
|
|
method: "POST",
|
|
|
|
headers: {
|
|
|
|
"Content-Type": "application/json",
|
2022-04-04 21:13:18 -04:00
|
|
|
"Authorization": `Bearer ${Cookies.get("drift-token") || ""}`,
|
2022-03-22 23:06:15 -04:00
|
|
|
},
|
|
|
|
body: JSON.stringify({
|
|
|
|
title,
|
|
|
|
content,
|
|
|
|
}),
|
|
|
|
})
|
2022-04-04 21:13:18 -04:00
|
|
|
|
2022-03-22 23:06:15 -04:00
|
|
|
if (resp.ok) {
|
|
|
|
const res = await resp.text()
|
|
|
|
setPreview(res)
|
|
|
|
setIsLoading(false)
|
|
|
|
}
|
|
|
|
}
|
2022-03-22 23:16:24 -04:00
|
|
|
setIsLoading(false)
|
2022-03-09 17:57:44 -05:00
|
|
|
}
|
2022-03-22 23:06:15 -04:00
|
|
|
fetchPost()
|
|
|
|
}, [content, fileId, title])
|
|
|
|
return (<>
|
2022-03-23 19:28:39 -04:00
|
|
|
{isLoading ? <div>Loading...</div> : <article className={styles.markdownPreview} dangerouslySetInnerHTML={{ __html: preview }} style={{
|
2022-03-22 23:06:15 -04:00
|
|
|
height
|
|
|
|
}} />}
|
|
|
|
</>)
|
|
|
|
|
2022-03-06 19:46:59 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
export default memo(MarkdownPreview)
|