Files
ai-taxonomy-literature-anal…/components/ArticleView.tsx
T
claude-bot a0e401a3d0
Deploy / deploy (push) Successful in 7m26s
Charts: consistent number format
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FbMbJPadPzVwvt9rU9GBNo
2026-10-23 05:48:25 +00:00

173 lines
7.9 KiB
TypeScript

import Link from 'next/link';
import dynamic from 'next/dynamic';
import { Fragment, ReactNode } from 'react';
import type { ArticleData, Block, Section } from '../lib/article-types';
const Mermaid = dynamic(() => import('./Mermaid'), { ssr: false, loading: () => <div className="sub">Loading diagram…</div> });
const PALETTE = ['#2f5bea', '#e0702b', '#1b9e77', '#a14b9c', '#c9a227', '#d6336c', '#37a0d6'];
/* ---------- inline markdown: **bold**, *italic*, `code`, [text](url) ---------- */
const safeHref = (u: string) => /^(https?:\/\/|\/|#|mailto:)/.test(u);
export function inline(s: string): ReactNode[] {
const out: ReactNode[] = [];
const re = /(\[[^\]]+\]\([^)\s]+\))|(\*\*[^*]+\*\*)|(\*[^*\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 [, text, url] = t.match(/^\[([^\]]+)\]\(([^)\s]+)\)$/)!;
if (!safeHref(url)) out.push(text);
else if (url.startsWith('/') || url.startsWith('#')) out.push(<Link key={k++} href={url}>{text}</Link>);
else out.push(<a key={k++} href={url} target="_blank" rel="noreferrer">{text} ↗</a>);
} else if (m[2]) out.push(<strong key={k++}>{inline(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;
}
function MarkdownBlock({ text }: { text: string }) {
return (
<>
{text.replace(/\r/g, '').split(/\n{2,}/).map((raw, i) => {
const src = raw.trim();
if (!src) return null;
const h = src.match(/^(#{3,4})\s+(.*)$/);
if (h && !src.includes('\n')) return h[1].length === 3 ? <h3 key={i} className="md-h">{inline(h[2])}</h3> : <h4 key={i} className="md-h">{inline(h[2])}</h4>;
const lines = src.split('\n');
if (lines.every((l) => /^\s*[-*]\s+/.test(l))) return <ul key={i}>{lines.map((l, j) => <li key={j}>{inline(l.replace(/^\s*[-*]\s+/, ''))}</li>)}</ul>;
if (lines.every((l) => /^\s*\d+[.)]\s+/.test(l))) return <ol key={i}>{lines.map((l, j) => <li key={j}>{inline(l.replace(/^\s*\d+[.)]\s+/, ''))}</li>)}</ol>;
return <p key={i}>{inline(lines.join(' '))}</p>;
})}
</>
);
}
/* ---------- horizontal bar chart (SVG) ---------- */
function BarChart({ d }: { d: Extract<Block, { type: 'chart' }>['data'] }) {
const rowH = 22 + (d.series.length - 1) * 12, W = 640, L = 170, R = 56, top = 8;
const H = top + d.labels.length * (rowH + 8) + 4;
const max = Math.max(...d.series.flatMap((s) => s.values), 0) || 1;
const X = (v: number) => (v / max) * (W - L - R);
const allInt = d.series.every((s) => s.values.every(Number.isInteger));
const fmt = (v: number) => (allInt ? String(v) : v.toFixed(1)) + (d.unit ?? '');
return (
<figure className="chart-fig">
<figcaption className="chart-title">{d.title}</figcaption>
<svg viewBox={`0 0 ${W} ${H}`} width="100%" role="img" aria-label={d.title}>
{d.labels.map((lab, i) => {
const y = top + i * (rowH + 8);
return (
<g key={lab + i}>
<text x={L - 8} y={y + rowH / 2 + 4} textAnchor="end" fontSize="12" fill="currentColor">{lab.length > 26 ? lab.slice(0, 25) + '…' : lab}<title>{lab}</title></text>
{d.series.map((s, j) => {
const h = rowH / d.series.length, yy = y + j * h;
const hi = d.highlight?.includes(i);
return (
<g key={s.name}>
<rect x={L} y={yy} width={Math.max(1, X(s.values[i]))} height={h - 2} rx="3" fill={PALETTE[(d.highlight ? (hi ? 0 : 6) : j) % PALETTE.length]} opacity={d.highlight && !hi ? 0.55 : 1}>
<title>{`${lab}${d.series.length > 1 ? ' · ' + s.name : ''}: ${fmt(s.values[i])}`}</title>
</rect>
<text x={L + X(s.values[i]) + 6} y={yy + h / 2 + 3} fontSize="11" fill="currentColor">{fmt(s.values[i])}</text>
</g>
);
})}
</g>
);
})}
</svg>
{d.series.length > 1 && <div className="legend">{d.series.map((s, j) => <span key={s.name}><i style={{ background: PALETTE[j % PALETTE.length] }} />{s.name}</span>)}</div>}
{d.note && <figcaption className="chart-note">{d.note}</figcaption>}
</figure>
);
}
function BlockView({ b }: { b: Block }) {
switch (b.type) {
case 'markdown': return <MarkdownBlock text={b.data.text} />;
case 'list': {
const Tag = b.data.ordered ? 'ol' : 'ul';
return <Tag>{b.data.items.map((it, i) => <li key={i}>{inline(it)}</li>)}</Tag>;
}
case 'callout':
return <div className={`callout ${b.data.tone ?? 'info'}`}>{b.data.title && <b>{b.data.title}. </b>}{inline(b.data.text)}</div>;
case 'table': {
const d = b.data;
return (
<div className="tbl-wrap">
{d.caption && <div className="chart-title">{d.caption}</div>}
<div style={{ overflowX: 'auto' }}>
<table className={d.numeric ? 'num' : ''}>
<thead><tr>{d.columns.map((c, i) => <th key={i}>{c}</th>)}</tr></thead>
<tbody>{d.rows.map((r, i) => <tr key={i}>{r.map((c, j) => <td key={j} className={j === d.highlightCol ? 'hl' : ''}>{inline(c)}</td>)}</tr>)}</tbody>
</table>
</div>
</div>
);
}
case 'chart': return <BarChart d={b.data} />;
case 'mermaid': return <Mermaid code={b.data.code} caption={b.data.caption} />;
case 'figure':
return /^(https:\/\/|\/)/.test(b.data.src)
? <figure><img src={b.data.src} alt={b.data.alt} style={{ maxWidth: '100%' }} />{b.data.caption && <figcaption className="chart-note">{b.data.caption}</figcaption>}</figure>
: null;
case 'code': return <pre className="code-block"><code>{b.data.text}</code></pre>;
}
}
function SectionView({ s, id }: { s: Section; id: string }) {
const H = (s.level <= 2 ? 'h2' : 'h3') as 'h2' | 'h3';
return (
<section id={`${id}-${s.key}`} className="art-section">
<H>{s.title}</H>
{s.blocks.map((b, i) => <BlockView key={i} b={b} />)}
{s.children.map((c) => <SectionView key={c.key} s={c} id={id} />)}
</section>
);
}
const toc = (secs: Section[], id: string, depth = 0): ReactNode =>
secs.map((s) => (
<Fragment key={s.key}>
<a href={`#${id}-${s.key}`} style={{ paddingLeft: depth * 12 }}>{s.title}</a>
{toc(s.children, id, depth + 1)}
</Fragment>
));
export default function ArticleView({ a }: { a: ArticleData }) {
return (
<article className="analysis">
<div className="analysis-head">
<span className="badge topic">Analysis</span>
<h2 style={{ margin: '6px 0' }}>{a.title}</h2>
{a.summary && <p className="sub" style={{ margin: 0 }}>{a.summary}</p>}
<p className="sub" style={{ margin: '6px 0 0', fontSize: 12 }}>revision {a.revision} · updated {a.updatedAt}</p>
</div>
<div className="article-grid">
<nav className="toc" aria-label="Sections">{toc(a.sections, a.slug)}{a.links.length > 0 && <a href={`#${a.slug}-links`}>Links</a>}</nav>
<div className="art-body">
{a.sections.map((s) => <SectionView key={s.key} s={s} id={a.slug} />)}
{a.links.length > 0 && (
<section id={`${a.slug}-links`} className="art-section">
<h2>Links</h2>
<ul>
{a.links.map((l) => (
<li key={l.url}>
<span className="badge">{l.kind}</span>{' '}
{l.url.startsWith('/') ? <Link href={l.url}>{l.title}</Link> : <a href={l.url} target="_blank" rel="noreferrer">{l.title} ↗</a>}
{l.note && <span className="sub"> — {l.note}</span>}
</li>
))}
</ul>
</section>
)}
</div>
</div>
</article>
);
}