Created
June 26, 2024 08:58
-
-
Save Digital39999/204c3402f7c69f2cc7e975107f12c2c6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { isValidElement, Children } from 'react'; | |
import pkg from 'katex'; | |
export function Math({ expression }: { expression: string }) { | |
const equation = pkg.renderToString(expression, { throwOnError: false }); | |
return <span dangerouslySetInnerHTML={{ __html: equation }} />; | |
} | |
export function MathText({ children }: { children: React.ReactNode; }) { | |
const parseMathExpressions = (text: string) => { | |
const parts = []; | |
let lastIndex = 0; | |
const regex = /\$(.+?)\$/g; | |
let match; | |
while ((match = regex.exec(text)) !== null) { | |
const mathExpression = match[1]; | |
if (match.index > lastIndex) parts.push(text.slice(lastIndex, match.index)); | |
parts.push(<Math key={match.index} expression={mathExpression} />); | |
lastIndex = regex.lastIndex; | |
} | |
if (lastIndex < text.length) parts.push(text.slice(lastIndex)); | |
return parts; | |
}; | |
const renderChildren = (children: React.ReactNode) => { | |
return Children.map(children, (child) => { | |
if (typeof child === 'string') return parseMathExpressions(child); | |
else if (isValidElement(child)) return child; | |
else return <></>; | |
}); | |
}; | |
return <>{renderChildren(children)}</>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment