Repository navigation
fix(math): load KaTeX lazily and show TeX source when it can't typeset #514
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
onmax
wants to merge
4
commits into
comarkdown:main
Choose a base branch
from
onmax:fix/math-renderers
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+425
−107
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b295736
fix(math): load KaTeX lazily and show TeX source when it can't typeset
onmax 322fb20
fix(math): retry loading KaTeX after a failed load in React and Vue
onmax 1c4637c
test: update bundle size snapshot
onmax 072b46d
fix(math): record a failed KaTeX load outside the React render
onmax File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,40 +1,88 @@ | ||
| import { useState, useEffect } from 'react' | ||
| import katex from 'katex' | ||
| import { Suspense, memo, use } from 'react' | ||
| import { loadKatex, typesetMath } from 'comark/plugins/math' | ||
|
|
||
| export interface MathProps { | ||
| content: string | ||
| className?: string | ||
| } | ||
|
|
||
| export function Math({ content, className = '' }: MathProps) { | ||
| const isInline = className.includes('inline') | ||
| const [mathml, setMathml] = useState<string>('...') | ||
|
|
||
| useEffect(() => { | ||
| try { | ||
| const rendered = katex.renderToString(content, { | ||
| throwOnError: true, | ||
| displayMode: !isInline, | ||
| }) | ||
| setMathml(rendered) | ||
| } catch { | ||
| // Keep loading state on error | ||
| } | ||
| }, [content, isInline]) | ||
| // After a failed load, formulas show their source, and a render this long | ||
| // after the failure loads KaTeX again. | ||
| const RETRY_DELAY = 5000 | ||
|
|
||
| // One promise for every formula, since `use` needs the same one on each render. | ||
| let katexReady: Promise<boolean> | undefined | ||
| let failedAt: number | undefined | ||
|
|
||
| function waitForKatex(): Promise<boolean> { | ||
| if (!katexReady || (failedAt !== undefined && Date.now() - failedAt >= RETRY_DELAY)) { | ||
| failedAt = undefined | ||
| katexReady = loadKatex().then( | ||
| () => true, | ||
| () => { | ||
| failedAt = Date.now() | ||
| return false | ||
| } | ||
| ) | ||
| } | ||
| return katexReady | ||
| } | ||
|
|
||
| // Memoized because streaming re-renders every formula on each chunk. | ||
| const Typeset = memo(function Typeset({ content, isInline }: { content: string; isInline: boolean }) { | ||
| let html = typesetMath(content, !isInline) | ||
| if (html === undefined) { | ||
| use(waitForKatex()) | ||
| html = typesetMath(content, !isInline) | ||
| } | ||
| if (!html) | ||
| return ( | ||
| <Source | ||
| content={content} | ||
| isInline={isInline} | ||
| /> | ||
| ) | ||
|
|
||
| if (isInline) { | ||
| return ( | ||
| <span | ||
| className="math inline" | ||
| dangerouslySetInnerHTML={{ __html: mathml }} | ||
| dangerouslySetInnerHTML={{ __html: html }} | ||
| /> | ||
| ) | ||
| } | ||
|
|
||
| return ( | ||
| <div | ||
| className="math block" | ||
| dangerouslySetInnerHTML={{ __html: mathml }} | ||
| dangerouslySetInnerHTML={{ __html: html }} | ||
| /> | ||
| ) | ||
| }) | ||
|
|
||
| // Unfinished or invalid TeX, and TeX without KaTeX installed, stays readable as its source. | ||
| function Source({ content, isInline }: { content: string; isInline: boolean }) { | ||
| return isInline ? <span className="math inline">{content}</span> : <div className="math block">{content}</div> | ||
| } | ||
|
|
||
| export function Math({ content, className = '' }: MathProps) { | ||
| const isInline = className.includes('inline') | ||
|
|
||
| // KaTeX loads on first use. Streaming server rendering and hydration wait | ||
| // for it; otherwise the source shows until it loads. | ||
| return ( | ||
| <Suspense | ||
| fallback={ | ||
| <Source | ||
| content={content} | ||
| isInline={isInline} | ||
| /> | ||
| } | ||
| > | ||
| <Typeset | ||
| content={content} | ||
| isInline={isInline} | ||
| /> | ||
| </Suspense> | ||
| ) | ||
| } | ||
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| // @vitest-environment happy-dom | ||
| import { StrictMode, act } from 'react' | ||
| import { createRoot } from 'react-dom/client' | ||
| import { expect, it, vi } from 'vitest' | ||
|
|
||
| ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true | ||
|
|
||
| it('shows the TeX source and stops loading KaTeX after a failed load in StrictMode', async () => { | ||
| let attempts = 0 | ||
| vi.doMock('katex', () => { | ||
| attempts++ | ||
| throw new Error('Failed to fetch dynamically imported module') | ||
| }) | ||
| const { Math } = await import('../src/plugins/math') | ||
| const container = document.createElement('div') | ||
| const root = createRoot(container) | ||
|
|
||
| await act(async () => { | ||
| root.render( | ||
| <StrictMode> | ||
| <Math | ||
| content="x^2" | ||
| className="math inline" | ||
| /> | ||
| </StrictMode> | ||
| ) | ||
| }) | ||
| await act(() => new Promise((resolve) => setTimeout(resolve, 100))) | ||
|
|
||
| expect(container.innerHTML).toBe('<span class="math inline">x^2</span>') | ||
| expect(attempts).toBe(1) | ||
|
|
||
| act(() => root.unmount()) | ||
| vi.doUnmock('katex') | ||
| }) |
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: comarkdown/comark
Length of output: 6971
Script executed:
Repository: comarkdown/comark
Length of output: 12101
Schedule a retry render after a failed KaTeX load.
The five-second check runs only when
Typesetrenders.Typesetis memoized, so an unchanged mounted formula does not render again after the failed promise resolves. The failed-load test callsrender()again after advancing the clock and therefore does not cover this mounted path. Add a client-side timer that updates local state afterRETRY_DELAY, so the formula retries and replaces its TeX source when KaTeX becomes available.Suggested fix