okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3616148bb
main
1/** 2* One formula of an answer (#3268), drawn by KaTeX. KaTeX and its fonts are bundled with the app (no network) and load as a separate 3* chunk the first time an answer holds math, so a chat without math pays nothing. Until the chunk is there, and if it cannot load, 4* the formula shows as its source text, as before. 5*/ 6import { useEffect , useState } from 'react' ; 7 8type Katex = typeof import ( 'katex' ). default ; 9let loading :Promise < Katex > | null = null ; 10const drawn = new Map < string , string >(); 11 12function loadKatex () :Promise < Katex > { 13loading ??= Promise . all ([ import ( 'katex' ), import ( 'katex/dist/katex.min.css' )]). then (([ module ]) => module . default ); 14return loading ; 15} 16 17function draw ( katex :Katex , tex :string , display :boolean ) :string { 18const key = ( display ?'D' :'I' ) + tex ; 19const known = drawn . get ( key ); 20if ( known !== undefined ) 21return known ; 22// trust stays off (no \href, \url, \includegraphics); a broken formula is shown as its source, not as an error page 23const html = katex . renderToString ( tex , { displayMode :display , throwOnError :false , strict :'ignore' , trust :false , maxSize :30 , maxExpand :500 }); 24if ( drawn . size > 400 ) 25drawn . clear (); 26drawn . set ( key , html ); 27return html ; 28} 29 30const source = ( tex :string , display :boolean ) => ( display ?`$$ ${ tex } $$` :`$ ${ tex } $` ); 31 32export function MathView ({ tex, display} :{ tex :string ; display :boolean }) { 33const [ html , setHtml ] = useState < string | null >(() => drawn . get (( display ?'D' :'I' ) + tex ) ?? null ); 34useEffect (() => { 35let live = true ; 36loadKatex (). then ( katex => { if ( live ) setHtml ( draw ( katex , tex , display )); }). catch (() => { /* stays as source text */ }); 37return () => { live = false ; }; 38}, [ tex , display ]); 39const cls = display ?'md-math md-math--display' :'md-math' ; 40if ( html === null ) 41return < code className = { cls + ' md-math--source' }>{ source ( tex , display )}</ code >; 42return < span className = { cls } dangerouslySetInnerHTML = {{ __html :html }}/>; 43}