Files
ai-taxonomy-literature-anal…/components/Blocks.tsx
T
claude-bot 5407bf4dff
Deploy / deploy (push) Successful in 8m0s
Page blocks: papers and content pages as flat lists of story blocks in the database
A page is now an ordered list of independent blocks (analysis.page_block), no sections and no
headings; every block has an id shown on the page so it can be pointed at. Paper detail pages
use page "paper/<conf>/<ext_id>", analysis pages on /contents use "content/<node id>".

- /api/blocks (list, replace a page, add) and /api/blocks/:id (get, patch, move, delete)
- dynamic block types (stats, tool-table, paper-table, benchmark-table) are filled from the
  database at render time; the two content pages are rendered from their blocks (seeded with
  defaults on first view)
- one-time migration copies the legacy articles into blocks (section titles dropped, links
  become a links block); legacy tables are kept untouched
- old /api/articles, ArticleView and PaperGroup removed

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FbMbJPadPzVwvt9rU9GBNo
2026-10-23 22:51:54 +08:00

256 lines
11 KiB
TypeScript

import Link from 'next/link';
import dynamic from 'next/dynamic';
import { ReactNode } from 'react';
import type { Block, PageBlock, Resolved } from '../lib/blocks';
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 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>
);
}
const Caption = ({ text }: { text?: string }) => (text ? <div className="chart-title">{text}</div> : null);
const Note = ({ text, vars }: { text?: string; vars?: Record<string, string | number> }) =>
text ? <p className="sub" style={{ margin: '0 0 10px' }}>{inline(Object.entries(vars ?? {}).reduce((t, [k, v]) => t.split(`{${k}}`).join(String(v)), text))}</p> : null;
function StaticBlock({ b }: { b: Block }) {
switch (b.type) {
case 'markdown': return <MarkdownBlock text={b.data.text} />;
case 'list': {
const Tag = b.data.ordered ? 'ol' : 'ul';
return <>{b.data.lead && <p>{inline(b.data.lead)}</p>}<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">
<Caption text={d.caption} />
<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 style={{ margin: 0 }}><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>;
case 'links':
return (
<ul className="links">
{b.data.items.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>
);
default: return null;
}
}
/** The dynamic blocks: their numbers and rows come from the database each time the page is rendered. */
function LiveBlock({ b, r }: { b: Block; r?: Resolved }) {
if (!r) return null;
if (b.type === 'stats' && r.type === 'stats') {
return (
<div className="cards" style={{ margin: 0 }}>
{r.items.map((s, i) => {
const inner = <><div className="stat">{typeof s.value === 'number' ? s.value.toLocaleString() : s.value}</div>{s.label}</>;
return s.href
? <Link key={i} href={s.href} className="card" style={{ color: 'inherit', textDecoration: 'none' }}>{inner}</Link>
: <div key={i} className="card">{inner}</div>;
})}
</div>
);
}
if (b.type === 'tool-table' && r.type === 'tool-table') {
const t = r.table;
return (
<>
<Caption text={b.data.caption} />
<Note text={b.data.note} vars={{ tools: t.tools, papers: t.papers }} />
{t.rows.length === 0 && <p className="sub">No tools yet. Add them with <code>PUT /api/tool-taxonomy/papers/&lt;conf&gt;/&lt;ext_id&gt;</code>.</p>}
{t.rows.length > 0 && (
<div style={{ overflowX: 'auto' }}>
<table>
<thead><tr><th>Category</th><th>Papers</th><th>Tools (paper)</th></tr></thead>
<tbody>
{t.rows.map((row) => (
<tr key={row.slug} id={row.slug}>
<td title={row.descr ?? undefined}>
{row.path.slice(0, -1).map((x, i) => <span key={i} style={{ color: 'var(--muted)' }}>{x} → </span>)}
<b>{row.title}</b>
</td>
<td>{row.papers || ''}</td>
<td>
{row.entries.length === 0 ? '—' : row.entries.map((e, i) => (
<div key={i}>
<code title={e.descr ?? undefined}>{e.tool}</code>{' '}
({e.paperId ? <Link href={`/papers/${e.paperId}`}>{e.paperLabel}</Link> : e.paperLabel})
{e.via && <span style={{ color: 'var(--muted)' }}> · via {e.via}</span>}
</div>
))}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{t.uncategorised.length > 0 && (
<p className="sub">
Not in any category yet: {t.uncategorised.map((e, i) => (
<span key={i}>{i ? ', ' : ''}<code>{e.tool}</code> ({e.paperId ? <Link href={`/papers/${e.paperId}`}>{e.paperLabel}</Link> : e.paperLabel})</span>
))}
</p>
)}
</>
);
}
if (b.type === 'paper-table' && r.type === 'paper-table') {
return (
<>
<Caption text={b.data.caption} />
<Note text={b.data.note} />
<div style={{ overflowX: 'auto' }}>
<table>
<thead><tr><th>Paper</th><th>Venue</th><th>Date</th><th>Analysis</th></tr></thead>
<tbody>
{r.papers.map((p) => (
<tr key={p.id}>
<td><Link href={`/papers/${p.id}`}>{p.title}</Link></td>
<td style={{ whiteSpace: 'nowrap' }}>{p.conf_short}</td>
<td style={{ whiteSpace: 'nowrap' }}>{p.date}</td>
<td>{p.analysed ? '✓' : ''}</td>
</tr>
))}
</tbody>
</table>
</div>
</>
);
}
if (b.type === 'benchmark-table' && r.type === 'benchmark-table') {
if (!r.rows.length) return null;
return (
<>
<Caption text={b.data.caption} />
<Note text={b.data.note} />
<div style={{ overflowX: 'auto' }}>
<table>
<thead><tr><th>Benchmark</th><th>Papers</th>{r.showNew && <th>Introduced in 2026</th>}</tr></thead>
<tbody>{r.rows.map((x) => <tr key={x.id}><td><Link href={`/benchmarks/${x.id}`}>{x.name}</Link></td><td>{x.n}</td>{r.showNew && <td>{x.n_new || ''}</td>}</tr>)}</tbody>
</table>
</div>
</>
);
}
return null;
}
const LIVE = ['stats', 'tool-table', 'paper-table', 'benchmark-table'];
/** A page body: independent blocks, one after the other. Each shows its id (#123) so it can be pointed at. */
export default function Blocks({ blocks }: { blocks: PageBlock[] }) {
return (
<div className="blocks">
{blocks.map((pb) => {
const live = LIVE.includes(pb.block.type);
if (live && !pb.resolved) return null;
return (
<div key={pb.id} id={`b${pb.id}`} className={`block block-${pb.block.type}${pb.block.type === 'stats' ? ' bare' : ''}`}>
<a className="block-id" href={`#b${pb.id}`} title={`block ${pb.id} · revision ${pb.revision} · updated ${pb.updatedAt}`}>#{pb.id}</a>
{live ? <LiveBlock b={pb.block} r={pb.resolved} /> : <StaticBlock b={pb.block} />}
</div>
);
})}
</div>
);
}