import { tr } from '../lib/i18n'; import { CopyBtn } from './CopyBtn'; /** Safe, dependency-free rendering of the Markdown structures used in answers. */ import { Fragment, type ReactNode } from 'react'; import { CodePreviewBtn } from './CodePreviewBtn'; import { codePreview } from '../lib/code-preview'; import type { PreviewArtifact } from '../lib/artifacts'; import { SyntaxCode } from './SyntaxCode'; import { MathView } from './MathView'; import { displayBlock, hasMath, splitMath } from '../lib/math'; import { imagePlan } from '../lib/markdown-images'; function inlineMarks(text: string, onOpenLink?: (url: string) => void, imageSession?: string | null): ReactNode { return text.split(/(!\[[^\]]*\]\([^\s)]+\)|`[^`]+`|\*\*[^*]+\*\*|\*[^*\n]+\*|\[[^\]]+\]\([^\s)]+\))/g).map((part, i) => { const image = part.match(/^!\[([^\]]*)\]\(([^\s)]+)\)$/); if (image) { const plan = imagePlan(image[2], imageSession); if (plan.kind === 'img') return {image[1]}; if (plan.kind === 'link') return { if (onOpenLink) { e.preventDefault(); onOpenLink(plan.href); } }}>{image[1] || plan.href}; return {image[1] || part}; } if (part.startsWith('`') && part.endsWith('`')) return {part.slice(1, -1)}; if (part.startsWith('**') && part.endsWith('**')) return {part.slice(2, -2)}; if (part.startsWith('*') && part.endsWith('*')) return {part.slice(1, -1)}; const link = part.match(/^\[([^\]]+)\]\(([^)]+)\)$/); if (link && /^(https?:\/\/|mailto:|#)/i.test(link[2])) return { if (onOpenLink && /^https?:/i.test(link[2])) { e.preventDefault(); onOpenLink(link[2]); } }}>{link[1]}; return {part}; }); } /** 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. */ function inline(text: string, onOpenLink?: (url: string) => void, imageSession?: string | null): ReactNode { if (!hasMath(text)) return inlineMarks(text, onOpenLink, imageSession); return text.split(/(`[^`]+`)/g).map((chunk, c) => { if (chunk.length > 1 && chunk.startsWith('`') && chunk.endsWith('`')) return {inlineMarks(chunk, onOpenLink, imageSession)}; return {splitMath(chunk).map((part, p) => part.kind === 'math' ? : {inlineMarks(part.text, onOpenLink, imageSession)})}; }); } /** Does this line continue the paragraph above it, or does it start a block of its own? */ export function continuesParagraph(lines: string[], at: number): boolean { const line = lines[at]; 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)) return false; if (line.includes('|') && at + 1 < lines.length && /^\s*\|?\s*:?-{3,}/.test(lines[at + 1])) return false; return !displayBlock(lines, at); } export function Markdown({ text, onOpenLink, previewId, onPreview, onClosePreview, imageSession }: { text: string; onOpenLink?: (url: string) => void; /** 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. */ previewId?: string; onPreview?: (a: PreviewArtifact) => void; onClosePreview?: (id: string) => void; /** The chat whose folder a picture path in the answer is read from (the host serves only files inside it). */ imageSession?: string | null; }) { const nodes: ReactNode[] = []; // 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 // 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. const lines = text.split(/\r\n|\r|\n/); for (let i = 0; i < lines.length;) { const line = lines[i]; if (!line.trim()) { i++; continue; } if (/^\s*```/.test(line)) { const language = line.trim().slice(3); const body: string[] = []; const key = i++; while (i < lines.length && !/^\s*```/.test(lines[i])) body.push(lines[i++]); i++; const code = body.join('\n'); const preview = previewId && onPreview ? codePreview(previewId, language, code) : null; nodes.push(
{language || tr('code')}{tr(preview && onPreview ? : null)}
); continue; } const block = displayBlock(lines, i); if (block) { nodes.push(
); i += block.used; continue; } const heading = line.match(/^(#{1,6})\s+(.+)$/); if (heading) { const Tag = heading[1].length <= 2 ? 'h2' : heading[1].length === 3 ? 'h3' : 'h4'; nodes.push({tr(inline(heading[2], onOpenLink, imageSession))}); i++; continue; } if (/^\s*[-*+]\s+\S/.test(line) || /^\s*\d+[.)]\s+\S/.test(line)) { const ordered = /^\s*\d+[.)]/.test(line); const items: ReactNode[] = []; const key = i; const re = ordered ? /^\s*\d+[.)]\s+(.+)$/ : /^\s*[-*+]\s+(.+)$/; while (i < lines.length && re.test(lines[i])) { items.push(
  • {tr(inline(lines[i].replace(re, '$1'), onOpenLink))}
  • ); i++; } if (i === key) { // never stand still: a line the list start accepted but the item pattern did not is shown as text and passed nodes.push(

    {line}

    ); i++; continue; } nodes.push(ordered ?
      {tr(items)}
    : ); continue; } if (line.includes('|') && i + 1 < lines.length && /^\s*\|?\s*:?-{3,}/.test(lines[i + 1])) { const cells = (row: string) => row.trim().replace(/^\||\|$/g, '').split('|').map(s => s.trim()); const header = cells(line); const rows: string[][] = []; const key = i; i += 2; while (i < lines.length && lines[i].includes('|')) rows.push(cells(lines[i++])); nodes.push(
    {tr(header.map((c, j) => ))}{tr(rows.map((r, j) => {tr(r.map((c, k) => ))}))}
    {tr(inline(c, onOpenLink, imageSession))}
    {tr(inline(c, onOpenLink, imageSession))}
    ); continue; } if (/^>\s?/.test(line)) { nodes.push(
    {tr(inline(line.replace(/^>\s?/, ''), onOpenLink))}
    ); i++; continue; } // 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). const key = i, parts: ReactNode[] = []; let current = line; i++; while (true) { const hard = /( {2,}|\\)$/.test(current); parts.push({tr(inline(current.replace(/( {2,}|\\)$/, ''), onOpenLink, imageSession))}); if (i >= lines.length || !continuesParagraph(lines, i)) break; parts.push(hard ?
    : ' '); current = lines[i++].trimStart(); } nodes.push(

    {tr(parts)}

    ); } return <>{tr(nodes)}; }