mirror of
https://github.com/d0zingcat/NotionNext.git
synced 2026-05-30 07:26:45 +00:00
refactor Equation component
This commit is contained in:
53
components/KatexReact.js
Normal file
53
components/KatexReact.js
Normal file
@@ -0,0 +1,53 @@
|
||||
import KaTeX from 'katex'
|
||||
import React from 'react'
|
||||
|
||||
const TeX = ({
|
||||
children,
|
||||
math,
|
||||
block,
|
||||
errorColor,
|
||||
renderError,
|
||||
settings,
|
||||
as: asComponent,
|
||||
...props
|
||||
}) => {
|
||||
const Component = asComponent || (block ? 'div' : 'span')
|
||||
const content = (children ?? math)
|
||||
const [state, setState] = React.useState({ innerHtml: '' })
|
||||
|
||||
React.useEffect(() => {
|
||||
try {
|
||||
const innerHtml = KaTeX.renderToString(content, {
|
||||
displayMode: true,
|
||||
errorColor,
|
||||
throwOnError: !!renderError,
|
||||
...settings
|
||||
})
|
||||
|
||||
setState({ innerHtml })
|
||||
} catch (error) {
|
||||
if (error instanceof KaTeX.ParseError || error instanceof TypeError) {
|
||||
if (renderError) {
|
||||
setState({ errorElement: renderError(error) })
|
||||
} else {
|
||||
setState({ innerHtml: error.message })
|
||||
}
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}, [block, content, errorColor, renderError, settings])
|
||||
|
||||
if ('errorElement' in state) {
|
||||
return state.errorElement
|
||||
}
|
||||
|
||||
return (
|
||||
<Component
|
||||
{...props}
|
||||
dangerouslySetInnerHTML={{ __html: state.innerHtml }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(TeX)
|
||||
Reference in New Issue
Block a user