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

83 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 "@styles/syntax.css"
import Skeleton from "@components/skeleton"
import { Spinner } from "@components/spinner"
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,
2022-11-16 03:49:12 -05:00
content = "",
title
}: Props) => {
2022-11-16 03:49:12 -05:00
const [preview, setPreview] = useState<string>(content)
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 || "",
2022-11-16 03:49:12 -05:00
content: content
})
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()
2022-11-16 03:49:12 -05:00
}, [content, fileId, title])
2022-04-09 20:48:19 -04:00
return (
<>
{isLoading ? (
<Spinner />
2022-04-09 20:48:19 -04:00
) : (
2022-11-16 03:49:12 -05:00
<StaticPreview preview={preview} 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 = ({
2022-11-16 03:49:12 -05:00
preview,
height = 500
}: {
2022-11-16 03:49:12 -05:00
preview: string
height: string | number
}) => {
return (
<article
className={styles.markdownPreview}
2022-11-16 03:49:12 -05:00
dangerouslySetInnerHTML={{ __html: preview }}
style={{
height
}}
/>
)
}