-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathCodeBlock.tsx
More file actions
48 lines (41 loc) · 1.19 KB
/
CodeBlock.tsx
File metadata and controls
48 lines (41 loc) · 1.19 KB
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
38
39
40
41
42
43
44
45
46
47
48
import hljs from "highlight.js/lib/core"
import AnsiToHtml from "./ansiToHtml"
import React, { useEffect, useState } from "react"
import { CodeBlockContainer } from "../styles/CodeBlockContainer"
import { getLanguageFromAlias } from "./getLanguageFromAlias"
import { highlightCode } from "./highlightCode"
export type CodeBlockProps = {
content: string
language?: string
}
export function CodeBlock(props: CodeBlockProps) {
const { content, language = "" } = props
const [html, setHtml] = useState("")
useEffect(() => {
highlightCode(language, content)
.then(html => setHtml(html ?? ""))
.catch(() => setHtml(""))
}, [content, language])
if (typeof window === "undefined") {
const safeLanguage = getLanguageFromAlias(language)?.name ?? "plaintext"
return (
<CodeBlockContainer
dangerouslySetInnerHTML={{
__html: safeLanguage == "ansi" ?
AnsiToHtml(content) :
hljs.highlight(safeLanguage, content).value,
}}
/>
)
}
if (!html) {
return <CodeBlockContainer>{content}</CodeBlockContainer>
}
return (
<CodeBlockContainer
dangerouslySetInnerHTML={{
__html: html,
}}
/>
)
}