okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (4c4596746) into f-0213-int22a3d7068

main
2.0 KiB36 linesraw
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 }) {
14    return plain ? <SyntaxCode text={text}/> : <Markdown text={text}/>;
15});
16
17export const PreviewMarkdown = memo(function PreviewMarkdown({ text }: { text: string }) {
18    if (previewTier(text) === 'plain')
19        return <SyntaxCode text={text}/>;
20    return <Sliced text={text}/>;
21});
22
23function Sliced({ text }: { text: string }) {
24    const slices = useMemo(() => previewSlices(text), [text]);
25    const revision = useMemo(() => textRevision(text), [text]);
26    const [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
28    useEffect(() => {
29        if (shown >= slices.length)
30            return;
31        const timer = setTimeout(() => setShown(n => slicesAfter(n, slices.length)), 24);
32        return () => clearTimeout(timer);
33    }, [revision, shown, slices.length]);
34    const count = Math.min(Math.max(shown, slicesAtStart(0, slices.length)), slices.length);
35    return <>{slices.slice(0, count).map(s => <Slice key={s.key} text={s.text} plain={s.plain}/>)}</>;
36}