2022-11-09 22:46:12 -05:00
|
|
|
import { getCookie } from "cookies-next"
|
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-04-09 20:48:19 -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 = {
|
2022-04-09 20:48:19 -04:00
|
|
|
height?: number | string
|
|
|
|
fileId?: string
|
|
|
|
content?: string
|
|
|
|
title?: string
|
|
|
|
// file extensions we can highlight
|
2022-03-09 17:57:44 -05:00
|
|
|
}
|
|
|
|
|
2022-03-22 23:06:15 -04:00
|
|
|
const MarkdownPreview = ({ height = 500, fileId, content, title }: Props) => {
|
2022-04-09 20:48:19 -04:00
|
|
|
const [preview, setPreview] = useState<string>(content || "")
|
|
|
|
const [isLoading, setIsLoading] = useState<boolean>(true)
|
|
|
|
useEffect(() => {
|
|
|
|
async function fetchPost() {
|
|
|
|
if (fileId) {
|
2022-11-09 21:38:05 -05:00
|
|
|
const resp = await fetch(`/api/file/html/${fileId}`, {
|
2022-04-09 20:48:19 -04:00
|
|
|
method: "GET"
|
|
|
|
})
|
|
|
|
if (resp.ok) {
|
|
|
|
const res = await resp.text()
|
|
|
|
setPreview(res)
|
|
|
|
setIsLoading(false)
|
|
|
|
}
|
|
|
|
} else if (content) {
|
2022-11-09 21:38:05 -05:00
|
|
|
// add title and query to url params
|
|
|
|
const urlQuery = new URLSearchParams({
|
|
|
|
title: title || "",
|
|
|
|
content
|
|
|
|
})
|
|
|
|
|
|
|
|
const resp = await fetch(`/api/files/get-html?${urlQuery}`, {
|
|
|
|
method: "GET",
|
2022-04-09 20:48:19 -04:00
|
|
|
headers: {
|
|
|
|
"Content-Type": "application/json",
|
2022-11-09 22:46:12 -05:00
|
|
|
Authorization: `Bearer ${getCookie("drift-token")}`
|
2022-04-09 20:48:19 -04:00
|
|
|
},
|
2022-11-09 21:38:05 -05:00
|
|
|
|
2022-04-09 20:48:19 -04:00
|
|
|
})
|
2022-03-22 23:06:15 -04:00
|
|
|
|
2022-04-09 20:48:19 -04:00
|
|
|
if (resp.ok) {
|
|
|
|
const res = await resp.text()
|
|
|
|
setPreview(res)
|
|
|
|
setIsLoading(false)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
setIsLoading(false)
|
|
|
|
}
|
|
|
|
fetchPost()
|
|
|
|
}, [content, fileId, title])
|
|
|
|
return (
|
|
|
|
<>
|
|
|
|
{isLoading ? (
|
|
|
|
<div>Loading...</div>
|
|
|
|
) : (
|
|
|
|
<article
|
|
|
|
className={styles.markdownPreview}
|
|
|
|
dangerouslySetInnerHTML={{ __html: preview }}
|
|
|
|
style={{
|
|
|
|
height
|
|
|
|
}}
|
|
|
|
/>
|
|
|
|
)}
|
|
|
|
</>
|
|
|
|
)
|
2022-03-06 19:46:59 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
export default memo(MarkdownPreview)
|