Skip to content

Commit

Permalink
feat(frontend): add katex render for inline markdown
Browse files Browse the repository at this point in the history
  • Loading branch information
GZTimeWalker committed Aug 4, 2023
1 parent 9f7545e commit 9d6e7ad
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
27 changes: 22 additions & 5 deletions src/GZCTF/ClientApp/src/components/MarkdownRender.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,35 @@ const RenderReplacer = (func: any, replacer: (text: string) => string) => {
}
}

const InlineRegex = /\$([\s\S]+?)\$/g
const BlockRegex = /\$\$([\s\S]+?)\$\$/g

export const InlineMarkdownRender = forwardRef<HTMLParagraphElement, InlineMarkdownProps>(
(props, ref) => {
const { source, ...others } = props
const { classes, cx } = useInlineStyles()

const renderer = new marked.Renderer()

const replacer = (text: string) =>
text.replace(InlineRegex, (_, expression) => {
return katex.renderToString(expression, { displayMode: false, throwOnError: false })
})

renderer.text = RenderReplacer(renderer.text, replacer)

marked.setOptions({
renderer,
silent: true,
})

return (
<Text
ref={ref}
className={others.className ? cx(classes.root, others.className) : classes.root}
{...others}
dangerouslySetInnerHTML={{
__html: marked.parseInline(source, { silent: true }) ?? '',
__html: marked.parseInline(source) ?? '',
}}
/>
)
Expand All @@ -47,17 +64,17 @@ export const MarkdownRender = forwardRef<HTMLDivElement, MarkdownProps>((props,

const renderer = new marked.Renderer()

const replacer = ((blockRegex, inlineRegex) => (text: string) => {
text = text.replace(blockRegex, (_, expression) => {
const replacer = (text: string) => {
text = text.replace(BlockRegex, (_, expression) => {
return katex.renderToString(expression, { displayMode: true, throwOnError: false })
})

text = text.replace(inlineRegex, (_, expression) => {
text = text.replace(InlineRegex, (_, expression) => {
return katex.renderToString(expression, { displayMode: false, throwOnError: false })
})

return text
})(/\$\$([\s\S]+?)\$\$/g, /\$([\s\S]+?)\$/g)
}

renderer.paragraph = RenderReplacer(renderer.paragraph, replacer)
renderer.text = RenderReplacer(renderer.text, replacer)
Expand Down
1 change: 0 additions & 1 deletion src/GZCTF/ClientApp/src/utils/useTypographyStyles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,6 @@ export const useInlineStyles = createStyles((theme) => {

return {
root: {
overflowX: 'auto',
wordBreak: 'break-word',
wordWrap: 'break-word',

Expand Down

0 comments on commit 9d6e7ad

Please sign in to comment.