f5d014a022
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FbMbJPadPzVwvt9rU9GBNo
49 lines
2.4 KiB
TypeScript
49 lines
2.4 KiB
TypeScript
import Link from 'next/link';
|
|
import { Fragment, ReactNode } from 'react';
|
|
|
|
/** Minimal, safe markdown: paragraphs, ###/#### headings, -/1. lists, **bold**, *italic*, `code`, citations [#id] / [#a, #b]. */
|
|
export default function Markdown({ text, cite }: { text: string; cite: Record<number, number> }) {
|
|
const blocks = (text ?? '').replace(/\r/g, '').split(/\n{2,}/);
|
|
return <>{blocks.map((b, i) => <Block key={i} src={b.trim()} cite={cite} />)}</>;
|
|
}
|
|
|
|
function Block({ src, cite }: { src: string; cite: Record<number, number> }) {
|
|
if (!src) return null;
|
|
const h = src.match(/^(#{2,4})\s+(.*)$/);
|
|
if (h && !src.includes('\n')) {
|
|
const lvl = h[1].length;
|
|
return lvl <= 3 ? <h3 className="md-h">{inline(h[2], cite)}</h3> : <h4 className="md-h">{inline(h[2], cite)}</h4>;
|
|
}
|
|
const lines = src.split('\n');
|
|
if (lines.every((l) => /^\s*[-*]\s+/.test(l))) return <ul>{lines.map((l, i) => <li key={i}>{inline(l.replace(/^\s*[-*]\s+/, ''), cite)}</li>)}</ul>;
|
|
if (lines.every((l) => /^\s*\d+[.)]\s+/.test(l))) return <ol>{lines.map((l, i) => <li key={i}>{inline(l.replace(/^\s*\d+[.)]\s+/, ''), cite)}</li>)}</ol>;
|
|
return <p>{inline(lines.join(' '), cite)}</p>;
|
|
}
|
|
|
|
export function inline(s: string, cite: Record<number, number>): ReactNode[] {
|
|
const out: ReactNode[] = [];
|
|
const re = /(\[#\d+(?:\s*[,;]\s*#?\d+)*\])|(\*\*[^*]+\*\*)|(\*[^*\s][^*]*\*)|(`[^`]+`)/g;
|
|
let last = 0; let m: RegExpExecArray | null; let k = 0;
|
|
while ((m = re.exec(s))) {
|
|
if (m.index > last) out.push(s.slice(last, m.index));
|
|
const t = m[0];
|
|
if (m[1]) {
|
|
const ids = [...t.matchAll(/(\d+)/g)].map((x) => Number(x[1]));
|
|
out.push(<sup key={k++} className="cite">[{ids.map((id, j) => (
|
|
<Fragment key={id}>{j > 0 && ','}<a href={`#ref-${id}`} title={`paper ${id}`}>{cite[id] ?? '?'}</a></Fragment>
|
|
))}]</sup>);
|
|
} else if (m[2]) out.push(<strong key={k++}>{t.slice(2, -2)}</strong>);
|
|
else if (m[3]) out.push(<em key={k++}>{t.slice(1, -1)}</em>);
|
|
else out.push(<code key={k++}>{t.slice(1, -1)}</code>);
|
|
last = m.index + t.length;
|
|
}
|
|
if (last < s.length) out.push(s.slice(last));
|
|
return out;
|
|
}
|
|
|
|
/** Inline list of citation chips for id arrays (tables). */
|
|
export function Cites({ ids, cite }: { ids: number[]; cite: Record<number, number> }) {
|
|
return <>{ids.map((id) => <a key={id} className="cite-chip" href={`#ref-${id}`}>[{cite[id] ?? '?'}]</a>)}</>;
|
|
}
|
|
export { Link };
|