Skip to content

Commit

Permalink
refactor(math rendering): fix bad type usage for KaTeX rendering logic
Browse files Browse the repository at this point in the history
  • Loading branch information
jannikgohr committed Oct 11, 2024
1 parent f23dc7d commit a848501
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 10 deletions.
7 changes: 3 additions & 4 deletions packages/joplin-search-integration/src/lib/katex-render.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Element } from 'hast'
import { Element, Literal } from 'hast'
// @ts-ignore
import katex from 'katex'
import 'katex/dist/katex.min.css'
Expand Down Expand Up @@ -33,16 +33,15 @@ export function processLatex(textNodes: Element[], md: string): void {
})
}

export function unescapeJoplinMathExceptions(textNodes: Node[]): void {
export function unescapeJoplinMathExceptions(textNodes: Literal[]): void {
textNodes.forEach((node) => {
// @ts-ignore
if (node.type === 'text') {
// @ts-ignore
node.value = node.value.replaceAll('$', '$')
}
})
}

// Changes all '$' not marking start/end of math expressions to '$' to ensure math rendering uses the correct ones
export function escapeJoplinMathExceptions(text: string): string {
// Regular expression to match inline LaTeX and block LaTeX for Joplin
const latexInlineRegex = /(?<!\\)\$(\S.+?)(?<!\\)(?<!\s)\$/gm // Inline LaTeX
Expand Down
10 changes: 4 additions & 6 deletions packages/joplin-search-integration/src/lib/md2html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { fromMarkdown } from 'mdast-util-from-markdown'
import { toHast } from 'mdast-util-to-hast'
import { selectAll } from 'unist-util-select'
import { toHtml } from 'hast-util-to-html'
import { Element, Properties } from 'hast'
import { Element, Literal, Properties } from 'hast'
import { math } from 'micromark-extension-math'
import { mathFromMarkdown } from 'mdast-util-math'
import { gfm } from 'micromark-extension-gfm'
Expand Down Expand Up @@ -49,12 +49,10 @@ export function md2html(
it.properties.href = browser.runtime.getURL(`/options.html#/note/${options.currentNoteId}${it.properties.href}`)
})

// Process LaTeX using KaTeX
const codeNodes = selectAll('[tagName="code"]', root)
// @ts-ignore
// Process math using KaTeX
const codeNodes = selectAll('[tagName="code"]', root) as Element[]
processLatex(codeNodes, md)
const textNodes = selectAll('text', root)
// @ts-ignore
const textNodes = selectAll('text', root) as Literal[]
unescapeJoplinMathExceptions(textNodes)

return toHtml(root, { allowDangerousHtml: true })
Expand Down

0 comments on commit a848501

Please sign in to comment.