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

83 lines
1.6 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 "@styles/syntax.css"
import Skeleton from "@components/skeleton"
import { Spinner } from "@geist-ui/core/dist"
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() {
// POST to avoid query string length limit
const method = fileId ? "GET" : "POST"
const path = fileId ? `/api/file/html/${fileId}` : "/api/file/get-html"
const body = fileId
? undefined
: JSON.stringify({
title: title || "",
content: initial
})
2022-11-09 21:38:05 -05:00
const resp = await fetch(path, {
method: method,
headers: {
"Content-Type": "application/json"
},
body
})
if (resp.ok) {
const res = await resp.text()
setPreview(res)
2022-04-09 20:48:19 -04:00
}
2022-04-09 20:48:19 -04:00
setIsLoading(false)
}
fetchPost()
}, [initial, fileId, title])
2022-04-09 20:48:19 -04:00
return (
<>
{isLoading ? (
<><Spinner /></>
2022-04-09 20:48:19 -04:00
) : (
<StaticPreview content={content} height={height} />
2022-04-09 20:48:19 -04:00
)}
</>
)
2022-03-06 19:46:59 -05:00
}
export default memo(MarkdownPreview)
export const StaticPreview = ({
content,
height = 500
}: {
content: string
height: string | number
}) => {
return (
<article
className={styles.markdownPreview}
dangerouslySetInnerHTML={{ __html: content }}
style={{
height
}}
/>
)
}