CoastalCommitsPastes/client/app/(posts)/components/preview/index.tsx

82 lines
1.5 KiB
TypeScript
Raw Normal View History

import { memo, useEffect, useState } from "react"
2022-04-09 20:48:19 -04:00
import styles from "./preview.module.css"
import "@styles/markdown.css"
import "./marked.css"
2022-03-06 19:46:59 -05:00
type Props = {
2022-04-09 20:48:19 -04:00
height?: number | string
fileId?: string
content?: string
title?: string
}
const MarkdownPreview = ({
height = 500,
fileId,
content: initial = "",
title
}: Props) => {
const [content, setPreview] = useState<string>(initial)
2022-04-09 20:48:19 -04:00
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
const urlQuery = new URLSearchParams({
title: title || "",
content
})
const resp = await fetch(`/api/file/get-html?${urlQuery}`, {
2022-11-12 03:58:21 -05:00
method: "GET"
2022-04-09 20:48:19 -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>
) : (
<StaticPreview content={content} height={height} />
2022-04-09 20:48:19 -04:00
)}
</>
)
2022-03-06 19:46:59 -05:00
}
export default MarkdownPreview
export const StaticPreview = ({
content,
height = 500
}: {
content: string
height: string | number
}) => {
return (
<article
className={styles.markdownPreview}
dangerouslySetInnerHTML={{ __html: content }}
style={{
height
}}
/>
)
}