refactor Equation component

This commit is contained in:
tangly1024.com
2023-02-08 14:45:57 +08:00
parent 5030357509
commit 1678caee9a
4 changed files with 80 additions and 2 deletions

25
components/Equation.js Normal file
View File

@@ -0,0 +1,25 @@
import * as React from 'react'
import Katex from '@/components/KatexReact'
import { getBlockTitle } from 'notion-utils'
const katexSettings = {
throwOnError: false,
strict: false
}
export const Equation = ({ block, math, inline = false, className, ...rest }) => {
// const { recordMap } = useNotionContext()
math = math || getBlockTitle(block, null)
if (!math) return null
return (
<span
role='button'
tabIndex={0}
className={`notion-equation ${inline ? 'notion-equation-inline' : 'notion-equation-block'}`}
>
<Katex math={math} settings={katexSettings} {...rest} />
</span>
)
}

53
components/KatexReact.js Normal file
View 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)

View File

@@ -10,7 +10,7 @@ import { Code } from 'react-notion-x/build/third-party/code'
import 'katex/dist/katex.min.css'
const Equation = dynamic(() =>
import('react-notion-x/build/third-party/equation').then(async (m) => {
import('@/components/Equation').then(async (m) => {
// 化学方程式
await import('@/lib/mhchem')
return m.Equation

View File

@@ -53,7 +53,7 @@
"react-dom": "^18.2.0",
"react-facebook": "^8.1.4",
"react-messenger-customer-chat": "^0.8.0",
"react-notion-x": "6.15.6",
"react-notion-x": "6.15.8",
"react-share": "^4.4.0",
"smoothscroll-polyfill": "^0.4.4",
"twikoo": "^1.6.8",