diff --git a/components/Equation.js b/components/Equation.js new file mode 100644 index 00000000..4872ad87 --- /dev/null +++ b/components/Equation.js @@ -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 ( + + + + ) +} diff --git a/components/KatexReact.js b/components/KatexReact.js new file mode 100644 index 00000000..5a585e13 --- /dev/null +++ b/components/KatexReact.js @@ -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 ( + + ) +} + +export default React.memo(TeX) diff --git a/components/NotionPage.js b/components/NotionPage.js index be168b31..af8c9f2d 100644 --- a/components/NotionPage.js +++ b/components/NotionPage.js @@ -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 diff --git a/package.json b/package.json index 12ae826d..79d8809a 100644 --- a/package.json +++ b/package.json @@ -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",