summaryrefslogtreecommitdiffhomepage
path: root/packages/web/src/components/CodeBlock.tsx
blob: 4c6aab48e8c4511553127c4ca4746713c06907ca (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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import {
  type JSX,
  onCleanup,
  splitProps,
  createEffect,
  createResource,
} from "solid-js"
import { codeToHtml } from "shiki"
import styles from "./codeblock.module.css"
import { transformerNotationDiff } from "@shikijs/transformers"

interface CodeBlockProps extends JSX.HTMLAttributes<HTMLDivElement> {
  code: string
  lang?: string
  onRendered?: () => void
}
function CodeBlock(props: CodeBlockProps) {
  const [local, rest] = splitProps(props, ["code", "lang", "onRendered"])
  let containerRef!: HTMLDivElement

  const [html] = createResource(
    () => [local.code, local.lang],
    async ([code, lang]) => {
      return (await codeToHtml(code || "", {
        lang: lang || "text",
        themes: {
          light: "github-light",
          dark: "github-dark",
        },
        transformers: [transformerNotationDiff()],
      })) as string
    },
  )

  onCleanup(() => {
    if (containerRef) containerRef.innerHTML = ""
  })

  createEffect(() => {
    if (html() && containerRef) {
      containerRef.innerHTML = html() as string

      local.onRendered?.()
    }
  })

  return (
    <>
      {html() ? (
        <div ref={containerRef} class={styles.codeblock} {...rest}></div>
      ) : null}
    </>
  )
}

export default CodeBlock