import React, { useEffect, useState } from "react"; import type { PrismTheme, Language } from "prism-react-renderer"; import Highlight, { defaultProps } from "prism-react-renderer"; import useDocusaurusContext from "@docusaurus/useDocusaurusContext"; import clsx from "clsx"; import downloadFile from "js-file-download"; import styles from "./Codeblock.module.css"; type ThemeValue = "light" | "dark"; const getTheme = () => (document.documentElement.dataset.theme || "light") as ThemeValue; function useGlobalTheme() { const [theme, setTheme] = useState(getTheme); useEffect(() => { const mo = new MutationObserver(() => { setTheme(getTheme()); }); mo.observe(document.documentElement, { subtree: false, attributeFilter: ["data-theme"], }); return () => mo.disconnect(); }); return theme; } function Codeblock({ children, language = "markup", enableCopy = false, download, }: { children: string; language?: Language; enableCopy?: boolean; download?: { fileName: string; mime: string }; }): JSX.Element { const { siteConfig } = useDocusaurusContext(); const theme = useGlobalTheme(); // eslint-disable-next-line @typescript-eslint/no-explicit-any const codeThemeLight = (siteConfig.themeConfig.prism as any) .theme as PrismTheme; // eslint-disable-next-line @typescript-eslint/no-explicit-any const codeThemeDark = (siteConfig.themeConfig.prism as any) .darkTheme as PrismTheme; const codeTheme = theme === "light" ? codeThemeLight : codeThemeDark; const handleCopy = async () => { try { navigator.clipboard.writeText(children); } catch { // Copying did unfortunately not work, but we'll not crash the app // beacause of that... } }; const handleDownload = () => { if (!download || !download.fileName || !download.mime) return; downloadFile(children, download.fileName, download.mime); }; return (
{({ className, style, tokens, getLineProps, getTokenProps }) => (
						{tokens.map((line, i) => (
							// eslint-disable-next-line react/jsx-key
							
{line.map((token, key) => ( // eslint-disable-next-line react/jsx-key ))}
))}
)}
{(enableCopy || download) && (
{enableCopy && ( )} {download && ( )}
)}
); } export default Codeblock;