okami.mom/strata

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

Niko1221markdown: keep the list line as it was written (a source guard in ui-do.test.mjs reads it)0fa4288d3

main
8.6 KiB155 linesraw
1import { tr } from '../lib/i18n';
2import { CopyBtn } from './CopyBtn';
3/** Safe, dependency-free rendering of the Markdown structures used in answers. */
4import { Fragment, type ReactNode } from 'react';
5import { CodePreviewBtn } from './CodePreviewBtn';
6import { codePreview } from '../lib/code-preview';
7import type { PreviewArtifact } from '../lib/artifacts';
8import { SyntaxCode } from './SyntaxCode';
9import { MathView } from './MathView';
10import { displayBlock, hasMath, splitMath } from '../lib/math';
11import { imagePlan } from '../lib/markdown-images';
12function inlineMarks(text: string, onOpenLink?: (url: string) => void, imageSession?: string | null): ReactNode {
13    return text.split(/(!\[[^\]]*\]\([^\s)]+\)|`[^`]+`|\*\*[^*]+\*\*|\*[^*\n]+\*|\[[^\]]+\]\([^\s)]+\))/g).map((part, i) => {
14        const image = part.match(/^!\[([^\]]*)\]\(([^\s)]+)\)$/);
15        if (image) {
16            const plan = imagePlan(image[2], imageSession);
17            if (plan.kind === 'img')
18                return <img key={i} src={plan.src} alt={image[1]} className="md-image" loading="lazy" referrerPolicy="no-referrer"/>;
19            if (plan.kind === 'link')
20                return <a key={i} href={plan.href} target="_blank" rel="noreferrer" onClick={e => { if (onOpenLink) {
21                    e.preventDefault();
22                    onOpenLink(plan.href);
23                } }}>{image[1] || plan.href}</a>;
24            return <Fragment key={i}>{image[1] || part}</Fragment>;
25        }
26        if (part.startsWith('`') && part.endsWith('`'))
27            return <code key={i} className="md-code">{part.slice(1, -1)}</code>;
28        if (part.startsWith('**') && part.endsWith('**'))
29            return <strong key={i}>{part.slice(2, -2)}</strong>;
30        if (part.startsWith('*') && part.endsWith('*'))
31            return <em key={i}>{part.slice(1, -1)}</em>;
32        const link = part.match(/^\[([^\]]+)\]\(([^)]+)\)$/);
33        if (link && /^(https?:\/\/|mailto:|#)/i.test(link[2]))
34            return <a key={i} href={link[2]} target="_blank" rel="noreferrer" onClick={e => { if (onOpenLink && /^https?:/i.test(link[2])) {
35                e.preventDefault();
36                onOpenLink(link[2]);
37            } }}>{link[1]}</a>;
38        return <Fragment key={i}>{part}</Fragment>;
39    });
40}
41/** Text with its inline marks and, outside code spans, its math (#3268). Math is cut out first: a * or _ inside a formula is not emphasis. */
42function inline(text: string, onOpenLink?: (url: string) => void, imageSession?: string | null): ReactNode {
43    if (!hasMath(text))
44        return inlineMarks(text, onOpenLink, imageSession);
45    return text.split(/(`[^`]+`)/g).map((chunk, c) => {
46        if (chunk.length > 1 && chunk.startsWith('`') && chunk.endsWith('`'))
47            return <Fragment key={c}>{inlineMarks(chunk, onOpenLink, imageSession)}</Fragment>;
48        return <Fragment key={c}>{splitMath(chunk).map((part, p) => part.kind === 'math'
49            ? <MathView key={p} tex={part.tex} display={part.display}/>
50            : <Fragment key={p}>{inlineMarks(part.text, onOpenLink, imageSession)}</Fragment>)}</Fragment>;
51    });
52}
53/** Does this line continue the paragraph above it, or does it start a block of its own? */
54export function continuesParagraph(lines: string[], at: number): boolean {
55    const line = lines[at];
56    if (!line.trim() || /^\s*```/.test(line) || /^(#{1,6})\s+(.+)$/.test(line) || /^\s*[-*+]\s+\S/.test(line) || /^\s*\d+[.)]\s+\S/.test(line) || /^>\s?/.test(line))
57        return false;
58    if (line.includes('|') && at + 1 < lines.length && /^\s*\|?\s*:?-{3,}/.test(lines[at + 1]))
59        return false;
60    return !displayBlock(lines, at);
61}
62export function Markdown({ text, onOpenLink, previewId, onPreview, onClosePreview, imageSession }: {
63    text: string;
64    onOpenLink?: (url: string) => void;
65    /** Where an HTML or Markdown code block can be shown in the sidebar: the message it belongs to, and the handlers that open and close a preview. */
66    previewId?: string;
67    onPreview?: (a: PreviewArtifact) => void;
68    onClosePreview?: (id: string) => void;
69    /** The chat whose folder a picture path in the answer is read from (the host serves only files inside it). */
70    imageSession?: string | null;
71}) {
72    const nodes: ReactNode[] = [];
73    // A file written on Windows has \r\n: the \r stays at the end of every line, where `.` does not match it, so a list line was never taken and the
74    // list loop below never moved on (an endless loop that filled the page's memory, found in the sidebar preview). Line ends are read as one.
75    const lines = text.split(/\r\n|\r|\n/);
76    for (let i = 0; i < lines.length;) {
77        const line = lines[i];
78        if (!line.trim()) {
79            i++;
80            continue;
81        }
82        if (/^\s*```/.test(line)) {
83            const language = line.trim().slice(3);
84            const body: string[] = [];
85            const key = i++;
86            while (i < lines.length && !/^\s*```/.test(lines[i]))
87                body.push(lines[i++]);
88            i++;
89            const code = body.join('\n');
90            const preview = previewId && onPreview ? codePreview(previewId, language, code) : null;
91            nodes.push(<div className="st-code" key={key}><div className="st-code__head"><span>{language || tr('code')}</span><span className="st-code__actions">{tr(preview && onPreview ? <CodePreviewBtn artifact={preview} onPreview={onPreview} onClose={onClosePreview}/> : null)}<CopyBtn text={code} label="Code" title="Copy code"/></span></div><SyntaxCode text={code} language={language}/></div>);
92            continue;
93        }
94        const block = displayBlock(lines, i);
95        if (block) {
96            nodes.push(<div className="md-math-block" key={i}><MathView tex={block.tex.trim()} display/></div>);
97            i += block.used;
98            continue;
99        }
100        const heading = line.match(/^(#{1,6})\s+(.+)$/);
101        if (heading) {
102            const Tag = heading[1].length <= 2 ? 'h2' : heading[1].length === 3 ? 'h3' : 'h4';
103            nodes.push(<Tag key={i}>{tr(inline(heading[2], onOpenLink, imageSession))}</Tag>);
104            i++;
105            continue;
106        }
107        if (/^\s*[-*+]\s+\S/.test(line) || /^\s*\d+[.)]\s+\S/.test(line)) {
108            const ordered = /^\s*\d+[.)]/.test(line);
109            const items: ReactNode[] = [];
110            const key = i;
111            const re = ordered ? /^\s*\d+[.)]\s+(.+)$/ : /^\s*[-*+]\s+(.+)$/;
112            while (i < lines.length && re.test(lines[i])) {
113                items.push(<li key={i}>{tr(inline(lines[i].replace(re, '$1'), onOpenLink))}</li>);
114                i++;
115            }
116            if (i === key) {              // never stand still: a line the list start accepted but the item pattern did not is shown as text and passed
117                nodes.push(<p key={key}>{line}</p>);
118                i++;
119                continue;
120            }
121            nodes.push(ordered ? <ol key={key}>{tr(items)}</ol> : <ul key={key}>{tr(items)}</ul>);
122            continue;
123        }
124        if (line.includes('|') && i + 1 < lines.length && /^\s*\|?\s*:?-{3,}/.test(lines[i + 1])) {
125            const cells = (row: string) => row.trim().replace(/^\||\|$/g, '').split('|').map(s => s.trim());
126            const header = cells(line);
127            const rows: string[][] = [];
128            const key = i;
129            i += 2;
130            while (i < lines.length && lines[i].includes('|'))
131                rows.push(cells(lines[i++]));
132            nodes.push(<div className="md-table-wrap" key={key}><table className="md-table"><thead><tr>{tr(header.map((c, j) => <th key={j}>{tr(inline(c, onOpenLink, imageSession))}</th>))}</tr></thead><tbody>{tr(rows.map((r, j) => <tr key={j}>{tr(r.map((c, k) => <td key={k}>{tr(inline(c, onOpenLink, imageSession))}</td>))}</tr>))}</tbody></table></div>);
133            continue;
134        }
135        if (/^>\s?/.test(line)) {
136            nodes.push(<blockquote key={i}>{tr(inline(line.replace(/^>\s?/, ''), onOpenLink))}</blockquote>);
137            i++;
138            continue;
139        }
140        // One paragraph: a single newline inside it is a soft break (a space); two spaces or a backslash at the end of a line is a hard break (#3818).
141        const key = i, parts: ReactNode[] = [];
142        let current = line;
143        i++;
144        while (true) {
145            const hard = /( {2,}|\\)$/.test(current);
146            parts.push(<Fragment key={parts.length}>{tr(inline(current.replace(/( {2,}|\\)$/, ''), onOpenLink, imageSession))}</Fragment>);
147            if (i >= lines.length || !continuesParagraph(lines, i))
148                break;
149            parts.push(hard ? <br key={`b${parts.length}`}/> : ' ');
150            current = lines[i++].trimStart();
151        }
152        nodes.push(<p key={key}>{tr(parts)}</p>);
153    }
154    return <>{tr(nodes)}</>;
155}