okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
22a3d7068
main
1/** 2* The Markdown preview of the sidebar, bounded (#5180). Same elements as <Markdown>, but: 3* - memoised by the text, so a chat that renders for every group of streamed tokens does not rebuild an unchanged file; 4* - drawn in slices (lib/preview-render.ts) that are memoised one by one, so a file changed in one place re-renders that slice; 5* - only a few slices at a time, the rest added by one waiting step that a newer text or leaving the view cancels; 6* - a block too large to parse, and a file above the limit, shown as plain text. 7*/ 8import { memo , useEffect , useMemo , useState } from 'react' ; 9import { Markdown } from './Markdown' ; 10import { SyntaxCode } from './SyntaxCode' ; 11import { previewSlices , previewTier , slicesAfter , slicesAtStart , textRevision } from '../lib/preview-render' ; 12 13const Slice = memo ( function Slice ({ text, plain} :{ text :string ; plain :boolean }) { 14return plain ?< SyntaxCode text = { text }/> :< Markdown text = { text }/>; 15}); 16 17export const PreviewMarkdown = memo ( function PreviewMarkdown ({ text} :{ text :string }) { 18if ( previewTier ( text ) === 'plain' ) 19return < SyntaxCode text = { text }/>; 20return < Sliced text = { text }/>; 21}); 22 23function Sliced ({ text} :{ text :string }) { 24const slices = useMemo (() => previewSlices ( text ), [ text ]); 25const revision = useMemo (() => textRevision ( text ), [ text ]); 26const [ shown , setShown ] = useState (() => slicesAtStart ( 0 , slices . length )); 27// one step waiting at most; a new revision or leaving the view clears it, so work for an old text never runs 28useEffect (() => { 29if ( shown >= slices . length ) 30return ; 31const timer = setTimeout (() => setShown ( n => slicesAfter ( n , slices . length )), 24 ); 32return () => clearTimeout ( timer ); 33}, [ revision , shown , slices . length ]); 34const count = Math . min ( Math . max ( shown , slicesAtStart ( 0 , slices . length )), slices . length ); 35return <>{ slices . slice ( 0 , count ). map ( s => < Slice key = { s . key } text = { s . text } plain = { s . plain }/>)}</>; 36}