okami.mom/strata

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

Niko1221markdown: a file with Windows line ends no longer runs the page out of memory (follow-up to 68bead108)90c77357f

main
5.8 KiB125 linesraw
1/**
2 * Work limits for the Markdown preview in the sidebar (#5180).
3 *
4 * The preview used to parse and rebuild the whole file on every render of the chat, which is once per group of streamed tokens, and a
5 * 60 KB file with many tables and code blocks is tens of thousands of React elements each time. The pieces here are pure text work:
6 *   - a revision key of the text, so an unchanged file is the same key however often the chat renders;
7 *   - the file cut into slices at block boundaries, each with its own key, so a change in one place re-renders one slice;
8 *   - limits: how many slices are drawn at once, when a block is shown as plain text, and when the whole file is.
9 * The components that use them are components/PreviewMarkdown.tsx and components/ArtifactPanel.tsx.
10 */
11
12/** Slices of about this many characters; a slice is the unit that is rendered, kept and skipped. */
13export const PREVIEW_SLICE_CHARS = 6000;
14/** Slices drawn at once when a file opens; the rest follow a few at a time, so the first paint is bounded however long the file is. */
15export const PREVIEW_FIRST_SLICES = 2;
16/** Slices added by each step after that. At most one step is waiting at any time. */
17export const PREVIEW_STEP_SLICES = 2;
18/** One block (a table or a fenced code block that cannot be cut) above this is shown as plain text, not parsed. */
19export const PREVIEW_BLOCK_LIMIT = 40_000;
20/** A file above this is shown as plain text (the Source view); the Read view would be thousands of elements per render. */
21export const PREVIEW_RENDER_LIMIT = 200_000;
22
23/** 32-bit FNV-1a over the UTF-16 units, in base 36; with the length it is the revision key of a text. Not a security hash. */
24export function textRevision(text: string): string {
25    let h = 0x811c9dc5;
26    for (let i = 0; i < text.length; i++) {
27        h ^= text.charCodeAt(i);
28        h = Math.imul(h, 0x01000193) >>> 0;
29    }
30    return `${text.length.toString(36)}-${h.toString(36)}`;
31}
32
33export interface PreviewSlice {
34    /** Stable for the same text at the same place: a slice that did not change keeps its key and is not rendered again. */
35    key: string;
36    text: string;
37    /** Too large to parse: shown as plain text. */
38    plain: boolean;
39}
40
41/** The longest run of lines a `$$` or `\[` block may span; lib/math.ts displayBlock reads at most this many. */
42const MATH_LINES = 60;
43
44/**
45 * Cut Markdown into slices of about `target` characters, only at a blank line that is outside a fenced code block and outside a
46 * display-math block. Blank lines already end a paragraph, a list and a table in components/Markdown.tsx, so the slices drawn one
47 * after the other are the same elements as the whole text drawn once.
48 */
49export function splitPreview(text: string, target = PREVIEW_SLICE_CHARS): PreviewSlice[] {
50    const lines = text.split(/\r\n|\r|\n/);
51    const slices: PreviewSlice[] = [];
52    let start = 0, size = 0, fenced = false, mathEnd = -1;
53    const emit = (end: number) => {
54        const body = lines.slice(start, end).join('\n');
55        if (body.trim()) {
56            const plain = body.length > PREVIEW_BLOCK_LIMIT;
57            slices.push({ key: `${slices.length}:${textRevision(body)}`, text: body, plain });
58        }
59        start = end;
60        size = 0;
61    };
62    for (let i = 0; i < lines.length; i++) {
63        const line = lines[i];
64        size += line.length + 1;
65        if (/^\s*```/.test(line)) {
66            fenced = !fenced;
67            continue;
68        }
69        if (fenced)
70            continue;
71        const t = line.trim();
72        if (i > mathEnd) {
73            const opens = t.startsWith('$$') ? '$$' : t.startsWith('\\[') ? '\\[' : '';
74            if (opens && !t.slice(2).includes(opens === '$$' ? '$$' : '\\]'))
75                mathEnd = i + MATH_LINES;
76        }
77        else if (t.includes('$$') || t.includes('\\]'))
78            mathEnd = -1;
79        // a blank line outside code and math, once the slice is big enough, ends it (the blank line goes with the slice before)
80        if (!t && i > mathEnd && size >= target && i + 1 < lines.length)
81            emit(i + 1);
82    }
83    emit(lines.length);
84    return slices;
85}
86
87/** How a file is shown: drawn as Markdown in slices, or as plain text when it is above the limit. */
88export function previewTier(text: string): 'markdown' | 'plain' {
89    return text.length > PREVIEW_RENDER_LIMIT ? 'plain' : 'markdown';
90}
91
92/**
93 * How many slices are drawn after a step. `shown` is the count now; the new text may have fewer or more slices than before. A change
94 * in the file never takes back slices already on screen (the page would jump), it only adds what is still missing.
95 */
96export function slicesAfter(shown: number, total: number, step = PREVIEW_STEP_SLICES): number {
97    return Math.min(total, Math.max(shown, 0) + step);
98}
99
100/** The count to draw before any step has run for this text: the ones already shown, or the first few. */
101export function slicesAtStart(shown: number, total: number): number {
102    return Math.min(total, Math.max(shown, PREVIEW_FIRST_SLICES));
103}
104
105/**
106 * Parsing cache: the slices of the last few texts, found by revision. A chat that renders again with the same file asks for the same
107 * text, and the answer is the same array (same identity), so nothing downstream sees a change. `stats.cuts` counts the real work.
108 */
109const cache = new Map<string, { text: string; slices: PreviewSlice[] }>();
110export const previewStats = { cuts: 0 };
111export function previewSlices(text: string): PreviewSlice[] {
112    const key = textRevision(text);
113    const known = cache.get(key);
114    if (known && known.text === text) {
115        cache.delete(key);
116        cache.set(key, known);
117        return known.slices;
118    }
119    previewStats.cuts++;
120    const slices = splitPreview(text);
121    cache.set(key, { text, slices });
122    if (cache.size > 4)
123        cache.delete(cache.keys().next().value as string);
124    return slices;
125}