aboutsummaryrefslogtreecommitdiffhomepage
path: root/frontend/app/components/Gaming/CodeBlock.tsx
blob: 0a9a2e50e126074c34e858ed62e613efdcde3b32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { useEffect, useState } from "react";
import { codeToHtml } from "shiki";

type Props = {
	code: string;
	language: string;
};

export default function CodeBlock({ code, language }: Props) {
	const [highlightedCode, setHighlightedCode] = useState<string | null>(null);

	useEffect(() => {
		let isMounted = true;

		(async () => {
			const highlighted = await codeToHtml(code, {
				lang: language,
				theme: "github-light",
			});
			if (isMounted) {
				setHighlightedCode(highlighted);
			}
		})();

		return () => {
			isMounted = false;
		};
	}, [code, language]);

	return (
		<pre className="h-full w-full p-2 bg-gray-50 rounded-lg border border-gray-300 whitespace-pre-wrap break-words">
			{highlightedCode === null ? null : (
				<code dangerouslySetInnerHTML={{ __html: highlightedCode }} />
			)}
		</pre>
	);
}