Skip to content

Commit

Permalink
feat: removed the need for unsafe HTML rendering
Browse files Browse the repository at this point in the history
  • Loading branch information
aegroto committed Nov 19, 2024
1 parent f6b2bed commit 0c55fef
Show file tree
Hide file tree
Showing 3 changed files with 178 additions and 311 deletions.
36 changes: 27 additions & 9 deletions components/codeblock.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import { useEffect, useState } from 'react'
import { useMemo, useEffect, useState, Fragment } from 'react'
import { createHighlighter, makeSingletonHighlighter } from 'shiki'
import { toJsxRuntime } from 'hast-util-to-jsx-runtime'
import { jsx, jsxs } from 'react/jsx-runtime'
import './codeblock.module.css'

const SHIKI_LIGHT_THEME = 'github-light'
const SHIKI_DARK_THEME = 'github-dark'

const getHighlighter = makeSingletonHighlighter(createHighlighter)

export const codeToHtml = async ({ code, language }) => {
export const codeToHast = async ({ code, language }) => {
const highlighter = await getHighlighter({
themes: [SHIKI_LIGHT_THEME, SHIKI_DARK_THEME],
langs: [language]
})

return highlighter.codeToHtml(code, {
return highlighter.codeToHast(code, {
lang: language,
themes: {
light: SHIKI_LIGHT_THEME,
Expand All @@ -23,19 +25,35 @@ export const codeToHtml = async ({ code, language }) => {
}

export default function CodeBlock ({ code, language }) {
const [html, setHtml] = useState(undefined)
const [hast, setHast] = useState(undefined)

useEffect(() => {
async function getCode () {
const newHtml = await codeToHtml({
async function processCode () {
const hast = await codeToHast({
code,
language
})
setHtml(newHtml)

setHast(hast)
}

getCode()
processCode()
}, [])

return html ? <div dangerouslySetInnerHTML={{ __html: html }} /> : <div>...</div>
const element = useMemo(() => {
if (!hast) {
return <div>...</div>
}

return toJsxRuntime(hast, {
Fragment,
jsx,
jsxs,
components: {
pre: props => <pre data-custom-codeblock {...props} />
}
})
}, [hast])

return element
}
Loading

0 comments on commit 0c55fef

Please sign in to comment.