-
-
Save brunosabot/9b54f6191dd73013648e75c954b3f32e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useMemo, useState } from "react"; | |
import classes from "./Post.module.css"; | |
import PrismAsyncLight from "react-syntax-highlighter/dist/cjs/prism-async-light"; | |
import darkStyle from "react-syntax-highlighter/dist/cjs/styles/prism/material-dark"; | |
import lightStyle from "react-syntax-highlighter/dist/cjs/styles/prism/material-light"; | |
interface IGistProps { | |
lang: string; | |
file?: string; | |
code: string; | |
} | |
const Gist: React.FC<IGistProps> = ({ lang, file, code }) => { | |
const [isReady, setIsReady] = useState(false); | |
const [isDarkMode, setIsDarkMode] = useState(true); | |
useEffect(() => { | |
if (lang === "text") { | |
setIsReady(true); | |
} else { | |
import(`react-syntax-highlighter/dist/cjs/languages/prism/${lang}`).then( | |
(module) => { | |
PrismAsyncLight.registerLanguage(lang, module.default); | |
setIsReady(true); | |
} | |
); | |
} | |
}, [lang]); | |
useEffect(() => { | |
setIsDarkMode(window.matchMedia("(prefers-color-scheme: dark)").matches); | |
}, []); | |
if (isReady === false) return null; | |
return ( | |
<> | |
{file ? ( | |
<div className={classes["blog-post-gist-filename"]}>{file}</div> | |
) : null} | |
<PrismAsyncLight | |
language={lang === "" ? "text" : lang} | |
showLineNumbers={lang !== "text"} | |
wrapLines | |
wrapLongLines={lang === "text"} | |
style={isDarkMode ? darkStyle : lightStyle} | |
> | |
{code} | |
</PrismAsyncLight> | |
</> | |
); | |
}; | |
export default Gist; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment