Page blocks: papers and content pages as flat lists of story blocks in the database
Deploy / deploy (push) Successful in 8m0s
Deploy / deploy (push) Successful in 8m0s
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
This commit is contained in:
@@ -1,172 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
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/<conf>/<ext_id></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>
|
||||
);
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
import type { PaperListContent } from '../lib/content-papers';
|
||||
|
||||
/** Body of an analysis page about a group of papers (kind 'papers'). */
|
||||
export default function PaperGroup({ list }: { list: PaperListContent }) {
|
||||
return (
|
||||
<>
|
||||
<div className="cards">
|
||||
<div className="card"><div className="stat">{list.total}</div>papers in this group</div>
|
||||
<div className="card"><div className="stat">{list.analysed.length}</div>analysed in depth</div>
|
||||
{list.byVenue.slice(0, 4).map((v) => <div key={v.conf_short} className="card"><div className="stat">{v.n}</div>at {v.conf_short}</div>)}
|
||||
</div>
|
||||
|
||||
{list.benchmarks.length > 0 && (
|
||||
<>
|
||||
<h2>Benchmarks these papers use</h2>
|
||||
<table>
|
||||
<thead><tr><th>Benchmark</th><th>Papers</th></tr></thead>
|
||||
<tbody>{list.benchmarks.map((b) => <tr key={b.id}><td><Link href={`/benchmarks/${b.id}`}>{b.name}</Link></td><td>{b.n}</td></tr>)}</tbody>
|
||||
</table>
|
||||
</>
|
||||
)}
|
||||
|
||||
<h2>All papers in the group</h2>
|
||||
<p className="sub">Matched by text (title, abstract, keywords); a paper may be a false match.</p>
|
||||
<table>
|
||||
<thead><tr><th>Paper</th><th>Venue</th><th>Date</th><th>Analysis</th></tr></thead>
|
||||
<tbody>
|
||||
{list.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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+20
-1
@@ -1,10 +1,29 @@
|
||||
import { query } from './db';
|
||||
import { migrateLegacyArticles } from './legacy-migrate';
|
||||
|
||||
// Schema "analysis": persistent, written through the API (pages/api/*), never touched by the data rebuild
|
||||
// (which replaces schema "live" on every deploy). Created on first use.
|
||||
const DDL = `
|
||||
CREATE SCHEMA IF NOT EXISTS analysis;
|
||||
|
||||
-- Page blocks (current content model): a page is a flat, ordered list of independent blocks ("stories").
|
||||
-- page = 'paper/<conf>/<ext_id>' (a paper's detail page) or 'content/<node id>' (an analysis page on /contents).
|
||||
-- type = markdown | list | callout | table | chart | mermaid | figure | code | links (static)
|
||||
-- stats | tool-table | paper-table | benchmark-table (filled from the database when rendered)
|
||||
CREATE TABLE IF NOT EXISTS analysis.page_block (
|
||||
id bigserial PRIMARY KEY,
|
||||
page text NOT NULL,
|
||||
position integer NOT NULL,
|
||||
type text NOT NULL,
|
||||
data jsonb NOT NULL,
|
||||
revision integer NOT NULL DEFAULT 1,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_page_block_page ON analysis.page_block (page, position);
|
||||
CREATE TABLE IF NOT EXISTS analysis.migration (name text PRIMARY KEY, done_at timestamptz NOT NULL DEFAULT now());
|
||||
|
||||
-- LEGACY (kept, no longer written or rendered): articles with sections. Copied once into page_block by lib/legacy-migrate.ts.
|
||||
-- Articles: one per (paper, topic); each has ordered, nestable sections; each section is an ordered list of typed blocks.
|
||||
CREATE TABLE IF NOT EXISTS analysis.article (
|
||||
id bigserial PRIMARY KEY,
|
||||
@@ -82,6 +101,6 @@ let ready: Promise<unknown> | null = null;
|
||||
|
||||
/** Create the analysis schema if it is missing (cached per process). */
|
||||
export function ensureAnalysisSchema(): Promise<unknown> {
|
||||
if (!ready) ready = query(DDL).catch((e) => { ready = null; throw e; });
|
||||
if (!ready) ready = query(DDL).then(() => migrateLegacyArticles()).catch((e) => { ready = null; throw e; });
|
||||
return ready;
|
||||
}
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ export class HttpError extends Error {
|
||||
constructor(public status: number, message: string) { super(message); }
|
||||
}
|
||||
|
||||
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE';
|
||||
type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
||||
type Handler = (req: NextApiRequest) => Promise<unknown>;
|
||||
|
||||
/** Dispatch by HTTP method; a handler returns the JSON to send, or throws HttpError. */
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
import { query, tx } from './db';
|
||||
import { ensureAnalysisSchema } from './analysis-schema';
|
||||
import { HttpError } from './api';
|
||||
|
||||
// Block shapes (data column) — see lib/article-types.ts for the typed version:
|
||||
// markdown {text} list {items[], ordered?} callout {text, title?, tone} table {columns[], rows[][], caption?, numeric?, highlightCol?}
|
||||
// chart {kind:'bar', title, labels[], series:[{name, values[]}], unit?, note?, highlight?[]} mermaid {code, caption?}
|
||||
// figure {src, alt, caption?} code {text, lang?}
|
||||
const TYPES = ['markdown', 'list', 'callout', 'table', 'chart', 'mermaid', 'figure', 'code'];
|
||||
const KINDS = ['paper', 'code', 'project', 'demo', 'dataset', 'related', 'other'];
|
||||
|
||||
export interface SectionInput { key: string; title: string; level?: number; blocks?: { type: string; data: any }[]; children?: SectionInput[] }
|
||||
export interface ArticleInput {
|
||||
slug: string; title: string; summary?: string | null;
|
||||
subject: { conf: string; ext_id: string };
|
||||
sections: SectionInput[];
|
||||
links?: { kind: string; title: string; url: string; note?: string | null; section?: string | null }[];
|
||||
}
|
||||
|
||||
const bad = (msg: string): never => { throw new HttpError(400, msg); };
|
||||
|
||||
export function validateArticle(a: any): ArticleInput {
|
||||
if (!a || typeof a !== 'object') bad('article must be a JSON object');
|
||||
if (typeof a.slug !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(a.slug)) bad('slug must be lowercase letters, digits and dashes');
|
||||
if (typeof a.title !== 'string' || !a.title.trim()) bad('missing title');
|
||||
if (!a.subject || typeof a.subject.conf !== 'string' || typeof a.subject.ext_id !== 'string') bad('missing subject.conf / subject.ext_id (the paper, e.g. {"conf":"acl2026","ext_id":"2026.acl-long.1"})');
|
||||
if (!Array.isArray(a.sections) || !a.sections.length) bad('no sections');
|
||||
const keys = new Set<string>();
|
||||
const walk = (secs: any[]) => {
|
||||
for (const s of secs) {
|
||||
if (!s.key || !s.title) bad('every section needs key and title');
|
||||
if (keys.has(s.key)) bad(`duplicate section key ${s.key}`);
|
||||
keys.add(s.key);
|
||||
(s.blocks || []).forEach((b: any, i: number) => {
|
||||
const at = `${s.key}[${i}]`;
|
||||
if (!TYPES.includes(b.type)) bad(`${at}: unknown block type ${b.type}`);
|
||||
const d = b.data || {};
|
||||
if (b.type === 'markdown' && typeof d.text !== 'string') bad(`${at}: markdown needs text`);
|
||||
if (b.type === 'list' && !Array.isArray(d.items)) bad(`${at}: list needs items`);
|
||||
if (b.type === 'mermaid' && typeof d.code !== 'string') bad(`${at}: mermaid needs code`);
|
||||
if (b.type === 'table' && !(Array.isArray(d.columns) && Array.isArray(d.rows) && d.rows.every((r: any[]) => r.length === d.columns.length))) bad(`${at}: table rows must match columns`);
|
||||
if (b.type === 'chart' && !(Array.isArray(d.labels) && Array.isArray(d.series) && d.series.every((x: any) => Array.isArray(x.values) && x.values.length === d.labels.length))) bad(`${at}: chart series must match labels`);
|
||||
});
|
||||
walk(s.children || []);
|
||||
}
|
||||
};
|
||||
walk(a.sections);
|
||||
for (const l of a.links || []) {
|
||||
if (!KINDS.includes(l.kind) || !l.url || !l.title) bad(`bad link ${JSON.stringify(l)} (kind must be one of ${KINDS.join(', ')})`);
|
||||
if (l.section && !keys.has(l.section)) bad(`link "${l.title}" points to unknown section ${l.section}`);
|
||||
}
|
||||
return a as ArticleInput;
|
||||
}
|
||||
|
||||
/** Insert or replace a whole article (sections, blocks, links) in one transaction. */
|
||||
export async function saveArticle(input: unknown) {
|
||||
const a = validateArticle(input);
|
||||
await ensureAnalysisSchema();
|
||||
const saved = await tx(async (q) => {
|
||||
const ex = await q<{ id: number }>('SELECT id FROM analysis.article WHERE slug = ?', [a.slug]);
|
||||
let id: number;
|
||||
let created = false;
|
||||
if (ex.length) {
|
||||
id = ex[0].id;
|
||||
await q('DELETE FROM analysis.link WHERE article_id = ?', [id]);
|
||||
await q('DELETE FROM analysis.section WHERE article_id = ?', [id]); // cascades to blocks
|
||||
await q('UPDATE analysis.article SET subject_conf=?, subject_ext_id=?, title=?, summary=?, revision=revision+1, updated_at=now() WHERE id=?',
|
||||
[a.subject.conf, a.subject.ext_id, a.title, a.summary ?? null, id]);
|
||||
} else {
|
||||
created = true;
|
||||
id = (await q<{ id: number }>('INSERT INTO analysis.article(slug, subject_conf, subject_ext_id, title, summary) VALUES (?,?,?,?,?) RETURNING id',
|
||||
[a.slug, a.subject.conf, a.subject.ext_id, a.title, a.summary ?? null]))[0].id;
|
||||
}
|
||||
const secIds: Record<string, number> = {};
|
||||
let blocks = 0;
|
||||
const insert = async (secs: SectionInput[], parent: number | null) => {
|
||||
for (let i = 0; i < secs.length; i++) {
|
||||
const s = secs[i];
|
||||
const sid = (await q<{ id: number }>('INSERT INTO analysis.section(article_id, parent_id, key, title, level, position) VALUES (?,?,?,?,?,?) RETURNING id',
|
||||
[id, parent, s.key, s.title, s.level ?? (parent ? 3 : 2), i]))[0].id;
|
||||
secIds[s.key] = sid;
|
||||
const bl = s.blocks || [];
|
||||
for (let j = 0; j < bl.length; j++) {
|
||||
await q('INSERT INTO analysis.block(section_id, position, type, data) VALUES (?,?,?,?::jsonb)', [sid, j, bl[j].type, JSON.stringify(bl[j].data)]);
|
||||
blocks++;
|
||||
}
|
||||
await insert(s.children || [], sid);
|
||||
}
|
||||
};
|
||||
await insert(a.sections, null);
|
||||
const links = a.links || [];
|
||||
for (let i = 0; i < links.length; i++) {
|
||||
const l = links[i];
|
||||
await q('INSERT INTO analysis.link(article_id, section_id, position, kind, title, url, note) VALUES (?,?,?,?,?,?,?)',
|
||||
[id, l.section ? secIds[l.section] : null, i, l.kind, l.title, l.url, l.note ?? null]);
|
||||
}
|
||||
const rev = (await q<{ revision: number }>('SELECT revision FROM analysis.article WHERE id = ?', [id]))[0].revision;
|
||||
return { slug: a.slug, created, revision: rev, sections: Object.keys(secIds).length, blocks, links: links.length };
|
||||
});
|
||||
// does the paper exist in the current data build? (the article is stored either way, keyed by conf + ext_id)
|
||||
const [paper] = await query<{ id: number; title: string }>('SELECT id, title FROM papers WHERE conf = ? AND ext_id = ?', [a.subject.conf, a.subject.ext_id]);
|
||||
return { ...saved, paper: paper ? { id: paper.id, title: paper.title, url: `/papers/${paper.id}` } : null };
|
||||
}
|
||||
|
||||
export async function listArticles() {
|
||||
await ensureAnalysisSchema();
|
||||
return query(`SELECT slug, title, subject_conf AS conf, subject_ext_id AS ext_id, revision, updated_at FROM analysis.article ORDER BY updated_at DESC`);
|
||||
}
|
||||
|
||||
/** The article in the same JSON shape that saveArticle accepts, so GET then PUT round-trips. */
|
||||
export async function exportArticle(slug: string): Promise<ArticleInput & { revision: number }> {
|
||||
await ensureAnalysisSchema();
|
||||
const [a] = await query<any>('SELECT id, slug, subject_conf, subject_ext_id, title, summary, revision FROM analysis.article WHERE slug = ?', [slug]);
|
||||
if (!a) throw new HttpError(404, `no article with slug ${slug}`);
|
||||
const [secs, blocks, links] = await Promise.all([
|
||||
query<any>('SELECT id, parent_id, key, title, level FROM analysis.section WHERE article_id = ? ORDER BY position, id', [a.id]),
|
||||
query<any>('SELECT b.section_id, b.type, b.data FROM analysis.block b JOIN analysis.section s ON s.id = b.section_id WHERE s.article_id = ? ORDER BY b.position', [a.id]),
|
||||
query<any>('SELECT l.kind, l.title, l.url, l.note, s.key AS section FROM analysis.link l LEFT JOIN analysis.section s ON s.id = l.section_id WHERE l.article_id = ? ORDER BY l.position, l.id', [a.id]),
|
||||
]);
|
||||
const node = new Map<number, SectionInput>();
|
||||
for (const s of secs) node.set(s.id, { key: s.key, title: s.title, level: s.level, blocks: blocks.filter((b) => b.section_id === s.id).map((b) => ({ type: b.type, data: b.data })), children: [] });
|
||||
const roots: SectionInput[] = [];
|
||||
for (const s of secs) (s.parent_id && node.has(s.parent_id) ? node.get(s.parent_id)!.children! : roots).push(node.get(s.id)!);
|
||||
return {
|
||||
slug: a.slug, title: a.title, summary: a.summary, revision: a.revision,
|
||||
subject: { conf: a.subject_conf, ext_id: a.subject_ext_id },
|
||||
sections: roots,
|
||||
links: links.map((l) => ({ kind: l.kind, title: l.title, url: l.url, note: l.note, section: l.section })),
|
||||
};
|
||||
}
|
||||
|
||||
export async function deleteArticle(slug: string) {
|
||||
await ensureAnalysisSchema();
|
||||
const r = await query<{ id: number }>('DELETE FROM analysis.article WHERE slug = ? RETURNING id', [slug]);
|
||||
if (!r.length) throw new HttpError(404, `no article with slug ${slug}`);
|
||||
return { deleted: slug };
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
// Client-safe types for analysis articles (schema: lib/analysis-schema.ts; written through /api/articles).
|
||||
export type Block =
|
||||
| { type: 'markdown'; data: { text: string } }
|
||||
| { type: 'list'; data: { items: string[]; ordered?: boolean } }
|
||||
| { type: 'callout'; data: { text: string; title?: string; tone?: 'info' | 'note' | 'warn' } }
|
||||
| { type: 'table'; data: { columns: string[]; rows: string[][]; caption?: string; numeric?: boolean; highlightCol?: number } }
|
||||
| { type: 'chart'; data: { kind: 'bar'; title: string; labels: string[]; series: { name: string; values: number[] }[]; unit?: string; note?: string; highlight?: number[] } }
|
||||
| { type: 'mermaid'; data: { code: string; caption?: string } }
|
||||
| { type: 'figure'; data: { src: string; alt: string; caption?: string } }
|
||||
| { type: 'code'; data: { text: string; lang?: string } };
|
||||
|
||||
export interface Section { key: string; title: string; level: number; blocks: Block[]; children: Section[] }
|
||||
export interface ArticleLink { kind: string; title: string; url: string; note: string | null }
|
||||
export interface ArticleData { slug: string; title: string; summary: string | null; revision: number; updatedAt: string; sections: Section[]; links: ArticleLink[] }
|
||||
@@ -1,41 +0,0 @@
|
||||
import { query } from './db';
|
||||
import { ensureAnalysisSchema } from './analysis-schema';
|
||||
import type { ArticleData, Block, Section } from './article-types';
|
||||
|
||||
/** Analysis articles about one paper, looked up by the paper's stable key (conf, ext_id). */
|
||||
export async function getArticlesFor(conf: string, extId: string | null): Promise<ArticleData[]> {
|
||||
if (!extId) return [];
|
||||
try {
|
||||
await ensureAnalysisSchema();
|
||||
const articles = await query<{ id: number; slug: string; title: string; summary: string | null; revision: number; updated_at: Date }>(
|
||||
`SELECT id, slug, title, summary, revision, updated_at FROM analysis.article WHERE subject_conf = ? AND subject_ext_id = ? ORDER BY created_at, id`,
|
||||
[conf, extId]);
|
||||
if (!articles.length) return [];
|
||||
const ids = articles.map((a) => a.id);
|
||||
const [secs, blocks, links] = await Promise.all([
|
||||
query<{ id: number; article_id: number; parent_id: number | null; key: string; title: string; level: number; position: number }>(
|
||||
`SELECT id, article_id, parent_id, key, title, level, position FROM analysis.section WHERE article_id = ANY(?) ORDER BY position, id`, [ids]),
|
||||
query<{ section_id: number; type: Block['type']; data: Block['data'] }>(
|
||||
`SELECT b.section_id, b.type, b.data FROM analysis.block b JOIN analysis.section s ON s.id = b.section_id WHERE s.article_id = ANY(?) ORDER BY b.position`, [ids]),
|
||||
query<{ article_id: number; kind: string; title: string; url: string; note: string | null }>(
|
||||
`SELECT article_id, kind, title, url, note FROM analysis.link WHERE article_id = ANY(?) ORDER BY position, id`, [ids]),
|
||||
]);
|
||||
const bySection = new Map<number, Block[]>();
|
||||
for (const b of blocks) (bySection.get(b.section_id) ?? bySection.set(b.section_id, []).get(b.section_id)!).push({ type: b.type, data: b.data } as Block);
|
||||
const node = new Map<number, Section & { _parent: number | null; _article: number }>();
|
||||
for (const s of secs) node.set(s.id, { key: s.key, title: s.title, level: s.level, blocks: bySection.get(s.id) ?? [], children: [], _parent: s.parent_id, _article: s.article_id });
|
||||
const roots = new Map<number, Section[]>();
|
||||
for (const s of secs) {
|
||||
const n = node.get(s.id)!;
|
||||
if (n._parent && node.has(n._parent)) node.get(n._parent)!.children.push(n);
|
||||
else (roots.get(s.article_id) ?? roots.set(s.article_id, []).get(s.article_id)!).push(n);
|
||||
}
|
||||
return articles.map((a) => ({
|
||||
slug: a.slug, title: a.title, summary: a.summary, revision: a.revision, updatedAt: new Date(a.updated_at).toISOString().slice(0, 10),
|
||||
sections: roots.get(a.id) ?? [],
|
||||
links: links.filter((l) => l.article_id === a.id).map(({ kind, title, url, note }) => ({ kind, title, url, note })),
|
||||
}));
|
||||
} catch {
|
||||
return []; // database not reachable or schema not creatable: show the paper without articles
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { getContent } from './content';
|
||||
import { getPaperList } from './content-papers';
|
||||
import { findNode } from './content-tree';
|
||||
import { getToolTable } from './tool-taxonomy';
|
||||
import type { PageBlock, Resolved, StatItem } from './blocks';
|
||||
|
||||
type Content = Awaited<ReturnType<typeof getContent>>;
|
||||
type List = Awaited<ReturnType<typeof getPaperList>>;
|
||||
|
||||
/** Fill the dynamic blocks of a page (stats, tables) with live numbers. Static blocks pass through unchanged. */
|
||||
export async function resolveBlocks(blocks: PageBlock[]): Promise<PageBlock[]> {
|
||||
const contents = new Map<string, Promise<Content | null>>();
|
||||
const lists = new Map<string, Promise<List | null>>();
|
||||
const content = (id: string) => {
|
||||
const n = findNode(id);
|
||||
return contents.get(id) ?? contents.set(id, n?.kind === 'tools' ? getContent(n) : Promise.resolve(null)).get(id)!;
|
||||
};
|
||||
const list = (id: string) => {
|
||||
const n = findNode(id);
|
||||
return lists.get(id) ?? lists.set(id, n?.kind === 'papers' ? getPaperList(n) : Promise.resolve(null)).get(id)!;
|
||||
};
|
||||
let tools: ReturnType<typeof getToolTable> | null = null;
|
||||
|
||||
return Promise.all(blocks.map(async (pb): Promise<PageBlock> => {
|
||||
const b = pb.block;
|
||||
let resolved: Resolved | undefined;
|
||||
switch (b.type) {
|
||||
case 'stats': {
|
||||
const [c, l] = await Promise.all([content(b.data.node), list(b.data.node)]);
|
||||
const items: StatItem[] = [];
|
||||
for (const it of b.data.items) {
|
||||
const fill = (name: string) => it.label.replace('{name}', name);
|
||||
switch (it.metric) {
|
||||
case 'area-papers': if (c) items.push({ value: c.total, label: fill('') }); break;
|
||||
case 'benchmark-count': if (c) items.push({ value: c.benchmarks.length, label: fill('') }); break;
|
||||
case 'taxonomy-papers': {
|
||||
const t = c?.taxonomy.find((x) => x.id === it.arg);
|
||||
if (t) items.push({ value: t.n, label: fill(t.label), href: it.href ?? `/papers?node=${t.id}` });
|
||||
break;
|
||||
}
|
||||
case 'group-papers': if (l) items.push({ value: l.total, label: fill('') }); break;
|
||||
case 'group-analysed': if (l) items.push({ value: l.analysed.length, label: fill('') }); break;
|
||||
case 'group-venues': if (l) for (const v of l.byVenue.slice(0, Number(it.arg) || 4)) items.push({ value: v.n, label: fill(v.conf_short) }); break;
|
||||
default: if (it.value !== undefined) items.push({ value: it.value, label: fill(''), href: it.href });
|
||||
}
|
||||
}
|
||||
resolved = { type: 'stats', items };
|
||||
break;
|
||||
}
|
||||
case 'tool-table': resolved = { type: 'tool-table', table: await (tools ??= getToolTable()) }; break;
|
||||
case 'paper-table': {
|
||||
const l = await list(b.data.node);
|
||||
resolved = { type: 'paper-table', papers: l?.papers ?? [] };
|
||||
break;
|
||||
}
|
||||
case 'benchmark-table': {
|
||||
if (b.data.scope === 'areas') resolved = { type: 'benchmark-table', rows: (await content(b.data.node))?.benchmarks ?? [], showNew: true };
|
||||
else resolved = { type: 'benchmark-table', rows: (await list(b.data.node))?.benchmarks ?? [], showNew: false };
|
||||
break;
|
||||
}
|
||||
}
|
||||
return resolved ? { ...pb, resolved } : pb;
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { query, tx } from './db';
|
||||
import { ensureAnalysisSchema } from './analysis-schema';
|
||||
import { HttpError } from './api';
|
||||
import { BLOCK_TYPES, LINK_KINDS, Block, PageBlock } from './blocks';
|
||||
|
||||
const bad = (msg: string): never => { throw new HttpError(400, msg); };
|
||||
const PAGE = /^(paper\/[^/\s]+\/[^/\s]+|content\/[a-z0-9][a-z0-9-]*)$/;
|
||||
|
||||
export function checkPage(page: unknown): string {
|
||||
if (typeof page !== 'string' || !PAGE.test(page)) bad('page must be "paper/<conf>/<ext_id>" (a paper) or "content/<node id>" (an analysis page), e.g. paper/acl2026/2026.acl-long.139');
|
||||
return page as string;
|
||||
}
|
||||
|
||||
const isStr = (x: unknown) => typeof x === 'string';
|
||||
const strs = (x: unknown) => Array.isArray(x) && x.every(isStr);
|
||||
|
||||
/** Validate one block; throws HttpError(400) with a message naming the problem. */
|
||||
export function validateBlock(type: unknown, data: any, at = 'block'): void {
|
||||
if (!isStr(type) || !BLOCK_TYPES.includes(type as string)) bad(`${at}: unknown block type ${JSON.stringify(type)} (one of ${BLOCK_TYPES.join(', ')})`);
|
||||
if (!data || typeof data !== 'object' || Array.isArray(data)) bad(`${at}: data must be an object`);
|
||||
const noHeading = (t: string) => { if (/^\s*#{1,6}\s/m.test(t)) bad(`${at}: no headings in blocks (a block is a story, not a section); remove the "#" line`); };
|
||||
switch (type) {
|
||||
case 'markdown': if (!isStr(data.text) || !data.text.trim()) bad(`${at}: markdown needs text`); noHeading(data.text); break;
|
||||
case 'list': if (!strs(data.items) || !data.items.length) bad(`${at}: list needs items (strings)`); if (data.lead !== undefined && !isStr(data.lead)) bad(`${at}: lead must be a string`); break;
|
||||
case 'callout': if (!isStr(data.text) || !data.text.trim()) bad(`${at}: callout needs text`); if (data.tone && !['info', 'note', 'warn'].includes(data.tone)) bad(`${at}: tone is info, note or warn`); break;
|
||||
case 'table':
|
||||
if (!strs(data.columns) || !Array.isArray(data.rows) || !data.rows.every((r: unknown) => strs(r) && (r as string[]).length === data.columns.length)) bad(`${at}: table rows must be string arrays as long as columns`);
|
||||
break;
|
||||
case 'chart':
|
||||
if (!isStr(data.title) || !strs(data.labels) || !Array.isArray(data.series) || !data.series.length || !data.series.every((s: any) => isStr(s.name) && Array.isArray(s.values) && s.values.length === data.labels.length && s.values.every((v: unknown) => typeof v === 'number')))
|
||||
bad(`${at}: chart needs title, labels[] and series[{name, values[]}] with one number per label`);
|
||||
break;
|
||||
case 'mermaid': if (!isStr(data.code) || !data.code.trim()) bad(`${at}: mermaid needs code`); break;
|
||||
case 'figure': if (!isStr(data.src) || !isStr(data.alt)) bad(`${at}: figure needs src and alt`); break;
|
||||
case 'code': if (!isStr(data.text)) bad(`${at}: code needs text`); break;
|
||||
case 'links':
|
||||
if (!Array.isArray(data.items) || !data.items.length || !data.items.every((l: any) => LINK_KINDS.includes(l?.kind) && isStr(l.title) && isStr(l.url))) bad(`${at}: links needs items[{kind, title, url, note?}], kind one of ${LINK_KINDS.join(', ')}`);
|
||||
break;
|
||||
case 'stats':
|
||||
if (!isStr(data.node) || !Array.isArray(data.items) || !data.items.every((i: any) => isStr(i.label) && (i.metric !== undefined || i.value !== undefined))) bad(`${at}: stats needs node and items[{label, metric? | value?}]`);
|
||||
break;
|
||||
case 'tool-table': break;
|
||||
case 'paper-table': if (!isStr(data.node)) bad(`${at}: paper-table needs node`); break;
|
||||
case 'benchmark-table': if (!isStr(data.node) || !['areas', 'papers'].includes(data.scope)) bad(`${at}: benchmark-table needs node and scope ("areas" or "papers")`); break;
|
||||
}
|
||||
}
|
||||
|
||||
interface Row { id: number; position: number; type: string; data: any; revision: number; updated_at: Date }
|
||||
const toBlock = (r: Row): PageBlock => ({ id: r.id, position: r.position, revision: r.revision, updatedAt: new Date(r.updated_at).toISOString().slice(0, 10), block: { type: r.type, data: r.data } as Block });
|
||||
|
||||
/** The blocks of a page in order (empty if none). */
|
||||
export async function getBlocks(page: string): Promise<PageBlock[]> {
|
||||
await ensureAnalysisSchema();
|
||||
return (await query<Row>('SELECT id, position, type, data, revision, updated_at FROM analysis.page_block WHERE page = ? ORDER BY position, id', [checkPage(page)])).map(toBlock);
|
||||
}
|
||||
|
||||
/** Pages that have blocks, with counts. */
|
||||
export async function listPages() {
|
||||
await ensureAnalysisSchema();
|
||||
return query<{ page: string; blocks: number; updated_at: Date }>('SELECT page, COUNT(*) AS blocks, MAX(updated_at) AS updated_at FROM analysis.page_block GROUP BY page ORDER BY MAX(updated_at) DESC');
|
||||
}
|
||||
|
||||
/** Replace all blocks of a page (new ids). */
|
||||
export async function replacePage(page: string, blocks: unknown) {
|
||||
checkPage(page);
|
||||
if (!Array.isArray(blocks) || !blocks.length) bad('send {"blocks":[{"type","data"}, ...]} with at least one block');
|
||||
(blocks as any[]).forEach((b, i) => validateBlock(b?.type, b?.data, `blocks[${i}]`));
|
||||
await ensureAnalysisSchema();
|
||||
await tx(async (q) => {
|
||||
await q('SELECT pg_advisory_xact_lock(hashtext(?::text))', [page]);
|
||||
await q('DELETE FROM analysis.page_block WHERE page = ?', [page]);
|
||||
for (let i = 0; i < (blocks as any[]).length; i++) {
|
||||
const b = (blocks as any[])[i];
|
||||
await q('INSERT INTO analysis.page_block(page, position, type, data) VALUES (?,?,?,?::jsonb)', [page, i, b.type, JSON.stringify(b.data)]);
|
||||
}
|
||||
});
|
||||
return { page, blocks: await getBlocks(page) };
|
||||
}
|
||||
|
||||
/** Add one block: at the end, or right after / before another block of the same page. */
|
||||
export async function addBlock(page: string, body: any) {
|
||||
checkPage(page);
|
||||
validateBlock(body?.type, body?.data);
|
||||
await ensureAnalysisSchema();
|
||||
const id = await tx(async (q) => {
|
||||
await q('SELECT pg_advisory_xact_lock(hashtext(?::text))', [page]);
|
||||
const at = await placeAt(q, page, body);
|
||||
await q('UPDATE analysis.page_block SET position = position + 1 WHERE page = ? AND position >= ?', [page, at]);
|
||||
return (await q<{ id: number }>('INSERT INTO analysis.page_block(page, position, type, data) VALUES (?,?,?,?::jsonb) RETURNING id', [page, at, body.type, JSON.stringify(body.data)]))[0].id;
|
||||
});
|
||||
return getBlock(id);
|
||||
}
|
||||
|
||||
type Q = <R = any>(sql: string, params?: unknown[]) => Promise<R[]>;
|
||||
async function placeAt(q: Q, page: string, body: { after?: number; before?: number }): Promise<number> {
|
||||
const ref = body.after ?? body.before;
|
||||
if (ref === undefined || ref === null) return (await q<{ n: number }>('SELECT COALESCE(MAX(position) + 1, 0) AS n FROM analysis.page_block WHERE page = ?', [page]))[0].n;
|
||||
const r = await q<{ position: number }>('SELECT position FROM analysis.page_block WHERE id = ? AND page = ?', [ref, page]);
|
||||
if (!r.length) throw new HttpError(404, `block ${ref} is not on page ${page}`);
|
||||
return body.after !== undefined && body.after !== null ? r[0].position + 1 : r[0].position;
|
||||
}
|
||||
|
||||
export async function getBlock(id: number) {
|
||||
await ensureAnalysisSchema();
|
||||
const r = await query<Row & { page: string }>('SELECT id, page, position, type, data, revision, updated_at FROM analysis.page_block WHERE id = ?', [id]);
|
||||
if (!r.length) throw new HttpError(404, `no block ${id}`);
|
||||
return { page: r[0].page, ...toBlock(r[0]) };
|
||||
}
|
||||
|
||||
/** Change a block: `data` replaces its data, `set` merges top-level keys (null removes a key), `type` changes its type,
|
||||
* `after` / `before` (a block id of the same page) moves it. */
|
||||
export async function patchBlock(id: number, body: any) {
|
||||
if (!body || typeof body !== 'object') bad('body must be a JSON object');
|
||||
const cur = await getBlock(id);
|
||||
let type: string = body.type ?? cur.block.type;
|
||||
let data: any = body.data ?? cur.block.data;
|
||||
if (body.set) {
|
||||
if (typeof body.set !== 'object' || Array.isArray(body.set)) bad('set must be an object of keys to change');
|
||||
data = { ...data, ...body.set };
|
||||
for (const k of Object.keys(body.set)) if (body.set[k] === null) delete data[k];
|
||||
}
|
||||
validateBlock(type, data);
|
||||
await tx(async (q) => {
|
||||
await q('SELECT pg_advisory_xact_lock(hashtext(?::text))', [cur.page]);
|
||||
if (body.after !== undefined || body.before !== undefined) {
|
||||
if ((body.after ?? body.before) === id) bad('cannot move a block next to itself');
|
||||
await q('UPDATE analysis.page_block SET position = -1 WHERE id = ?', [id]);
|
||||
const at = await placeAt(q, cur.page, body);
|
||||
await q('UPDATE analysis.page_block SET position = position + 1 WHERE page = ? AND position >= ?', [cur.page, at]);
|
||||
await q('UPDATE analysis.page_block SET position = ? WHERE id = ?', [at, id]);
|
||||
await renumber(q, cur.page);
|
||||
}
|
||||
await q('UPDATE analysis.page_block SET type = ?, data = ?::jsonb, revision = revision + 1, updated_at = now() WHERE id = ?', [type, JSON.stringify(data), id]);
|
||||
});
|
||||
return getBlock(id);
|
||||
}
|
||||
|
||||
async function renumber(q: Q, page: string) {
|
||||
await q('UPDATE analysis.page_block b SET position = r.n FROM (SELECT id, ROW_NUMBER() OVER (ORDER BY position, id) - 1 AS n FROM analysis.page_block WHERE page = ?) r WHERE b.id = r.id', [page]);
|
||||
}
|
||||
|
||||
export async function deleteBlock(id: number) {
|
||||
const cur = await getBlock(id);
|
||||
await tx(async (q) => {
|
||||
await q('SELECT pg_advisory_xact_lock(hashtext(?::text))', [cur.page]);
|
||||
await q('DELETE FROM analysis.page_block WHERE id = ?', [id]);
|
||||
await renumber(q, cur.page);
|
||||
});
|
||||
return { deleted: id, page: cur.page };
|
||||
}
|
||||
|
||||
/** Insert `defaults` as the blocks of `page` if it has none yet (safe against concurrent first views). */
|
||||
export async function seedPage(page: string, defaults: { type: string; data: any }[]) {
|
||||
checkPage(page);
|
||||
await ensureAnalysisSchema();
|
||||
await tx(async (q) => {
|
||||
await q('SELECT pg_advisory_xact_lock(hashtext(?::text))', [page]);
|
||||
if ((await q('SELECT 1 FROM analysis.page_block WHERE page = ? LIMIT 1', [page])).length) return;
|
||||
for (let i = 0; i < defaults.length; i++) {
|
||||
validateBlock(defaults[i].type, defaults[i].data, `default block ${i}`);
|
||||
await q('INSERT INTO analysis.page_block(page, position, type, data) VALUES (?,?,?,?::jsonb)', [page, i, defaults[i].type, JSON.stringify(defaults[i].data)]);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// Client-safe types for page blocks (schema: lib/analysis-schema.ts, table analysis.page_block; API: /api/blocks).
|
||||
// A page is a flat list of independent blocks. A block has no title and no relation to its neighbours: one block, one aspect.
|
||||
import type { ToolTable } from './tool-taxonomy';
|
||||
import type { ListedPaper } from './content-papers';
|
||||
|
||||
export interface StatItem { value: number | string; label: string; href?: string }
|
||||
export interface LinkItem { kind: string; title: string; url: string; note?: string | null }
|
||||
|
||||
export type Block =
|
||||
| { type: 'markdown'; data: { text: string } }
|
||||
| { type: 'list'; data: { items: string[]; ordered?: boolean; lead?: string } }
|
||||
| { type: 'callout'; data: { text: string; title?: string; tone?: 'info' | 'note' | 'warn' } }
|
||||
| { type: 'table'; data: { columns: string[]; rows: string[][]; caption?: string; numeric?: boolean; highlightCol?: number } }
|
||||
| { type: 'chart'; data: { kind: 'bar'; title: string; labels: string[]; series: { name: string; values: number[] }[]; unit?: string; note?: string; highlight?: number[] } }
|
||||
| { type: 'mermaid'; data: { code: string; caption?: string } }
|
||||
| { type: 'figure'; data: { src: string; alt: string; caption?: string } }
|
||||
| { type: 'code'; data: { text: string; lang?: string } }
|
||||
| { type: 'links'; data: { items: LinkItem[] } }
|
||||
// filled from the database when the page is rendered (see lib/block-resolve.ts)
|
||||
| { type: 'stats'; data: { node: string; items: { metric?: string; arg?: string | number; value?: number | string; label: string; href?: string }[] } }
|
||||
| { type: 'tool-table'; data: { caption?: string; note?: string } }
|
||||
| { type: 'paper-table'; data: { node: string; caption?: string; note?: string } }
|
||||
| { type: 'benchmark-table'; data: { node: string; scope: 'areas' | 'papers'; caption?: string; note?: string } };
|
||||
|
||||
export type BlockType = Block['type'];
|
||||
export const STATIC_TYPES = ['markdown', 'list', 'callout', 'table', 'chart', 'mermaid', 'figure', 'code', 'links'] as const;
|
||||
export const DYNAMIC_TYPES = ['stats', 'tool-table', 'paper-table', 'benchmark-table'] as const;
|
||||
export const BLOCK_TYPES: readonly string[] = [...STATIC_TYPES, ...DYNAMIC_TYPES];
|
||||
export const LINK_KINDS = ['paper', 'code', 'project', 'demo', 'dataset', 'related', 'other'];
|
||||
|
||||
export type Resolved =
|
||||
| { type: 'stats'; items: StatItem[] }
|
||||
| { type: 'tool-table'; table: ToolTable }
|
||||
| { type: 'paper-table'; papers: ListedPaper[] }
|
||||
| { type: 'benchmark-table'; rows: { id: number; name: string; n: number; n_new?: number }[]; showNew: boolean };
|
||||
|
||||
/** A block as the page gets it: its id (what you point at), its place, its data, and the live data for dynamic types. */
|
||||
export interface PageBlock { id: number; position: number; revision: number; updatedAt: string; block: Block; resolved?: Resolved }
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { ContentNode } from './content-tree';
|
||||
|
||||
/** The blocks a content page starts with (written to the database the first time the page is opened; edit them afterwards
|
||||
* through /api/blocks, not here). */
|
||||
export function defaultBlocks(n: ContentNode): { type: string; data: any }[] {
|
||||
if (n.kind === 'tools') {
|
||||
return [
|
||||
{ type: 'stats', data: { node: n.id, items: [
|
||||
{ metric: 'area-papers', label: 'papers in this area' },
|
||||
...n.taxonomy.map((t) => ({ metric: 'taxonomy-papers', arg: t, label: 'in taxonomy: {name}' })),
|
||||
{ metric: 'benchmark-count', label: 'benchmarks most used here' },
|
||||
] } },
|
||||
{ type: 'tool-table', data: { caption: 'Tools by category', note: '{tools} tools from {papers} papers. A tool can sit in several categories. A category lists every tool filed under it or under a category below it (marked “via …”); each tool links to the paper that designed it.' } },
|
||||
{ type: 'benchmark-table', data: { node: n.id, scope: 'areas', caption: 'Benchmarks used' } },
|
||||
];
|
||||
}
|
||||
return [
|
||||
{ type: 'stats', data: { node: n.id, items: [
|
||||
{ metric: 'group-papers', label: 'papers in this group' },
|
||||
{ metric: 'group-analysed', label: 'analysed in depth' },
|
||||
{ metric: 'group-venues', arg: 4, label: 'at {name}' },
|
||||
] } },
|
||||
{ type: 'benchmark-table', data: { node: n.id, scope: 'papers', caption: 'Benchmarks these papers use' } },
|
||||
{ type: 'paper-table', data: { node: n.id, caption: 'All papers in the group', note: 'Matched by text (title, abstract, keywords); a paper may be a false match.' } },
|
||||
];
|
||||
}
|
||||
+10
-8
@@ -3,7 +3,7 @@ import { ensureAnalysisSchema } from './analysis-schema';
|
||||
import type { ContentNode } from './content-tree';
|
||||
|
||||
export interface ListedPaper { id: number; conf: string; ext_id: string | null; title: string; conf_short: string; date: string; analysed: boolean }
|
||||
export interface AnalysedArticle { slug: string; title: string; summary: string | null; paperId: number; paperTitle: string; updatedAt: string }
|
||||
export interface AnalysedArticle { paperId: number; paperTitle: string; updatedAt: string }
|
||||
export interface PaperListContent {
|
||||
total: number;
|
||||
papers: ListedPaper[];
|
||||
@@ -30,19 +30,21 @@ export async function getPaperList(node: ContentNode): Promise<PaperListContent>
|
||||
FROM papers p JOIN conferences c ON c.slug = p.conf
|
||||
WHERE ${w.sql} ORDER BY date DESC, p.id`, w.params);
|
||||
|
||||
let articles: { slug: string; title: string; summary: string | null; subject_conf: string; subject_ext_id: string; updated_at: Date }[] = [];
|
||||
// a paper counts as analysed when its detail page has blocks (page = paper/<conf>/<ext_id>)
|
||||
let pages: { page: string; updated_at: Date }[] = [];
|
||||
try {
|
||||
await ensureAnalysisSchema();
|
||||
articles = await query(`SELECT slug, title, summary, subject_conf, subject_ext_id, updated_at FROM analysis.article ORDER BY updated_at DESC`);
|
||||
} catch { /* no analysis schema reachable: list the papers without articles */ }
|
||||
pages = await query(`SELECT page, MAX(updated_at) AS updated_at FROM analysis.page_block WHERE page LIKE 'paper/%' GROUP BY page ORDER BY MAX(updated_at) DESC`);
|
||||
} catch { /* no analysis schema reachable: list the papers without analyses */ }
|
||||
const byKey = new Map(papers.map((p) => [`${p.conf}/${p.ext_id}`, p]));
|
||||
const analysed: AnalysedArticle[] = [];
|
||||
const done = new Set<string>();
|
||||
for (const a of articles) {
|
||||
const p = byKey.get(`${a.subject_conf}/${a.subject_ext_id}`);
|
||||
for (const pg of pages) {
|
||||
const key = pg.page.slice('paper/'.length);
|
||||
const p = byKey.get(key);
|
||||
if (!p) continue;
|
||||
done.add(`${p.conf}/${p.ext_id}`);
|
||||
analysed.push({ slug: a.slug, title: a.title, summary: a.summary, paperId: p.id, paperTitle: p.title, updatedAt: new Date(a.updated_at).toISOString().slice(0, 10) });
|
||||
done.add(key);
|
||||
analysed.push({ paperId: p.id, paperTitle: p.title, updatedAt: new Date(pg.updated_at).toISOString().slice(0, 10) });
|
||||
}
|
||||
|
||||
const ids = papers.map((p) => p.id);
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { tx } from './db';
|
||||
|
||||
// One-time copy of the legacy articles (analysis.article / section / block / link) into analysis.page_block.
|
||||
// Each legacy block becomes its own page block; section titles disappear (a block is a story, not a section);
|
||||
// list blocks get a short lead-in sentence so they still read on their own; the links become one `links` block at the end.
|
||||
const LEAD: Record<string, string> = {
|
||||
'key-contribution': 'What the paper puts on the table:',
|
||||
evaluation: 'How the evaluation is set up:',
|
||||
limitations: 'Where the work falls short:',
|
||||
notes: 'Worth keeping in mind:',
|
||||
};
|
||||
|
||||
const stripHeadings = (t: string) => t.split('\n').filter((l) => !/^\s*#{1,6}\s/.test(l)).join('\n').replace(/\n{3,}/g, '\n\n').trim();
|
||||
|
||||
export async function migrateLegacyArticles(): Promise<void> {
|
||||
await tx(async (q) => {
|
||||
await q('SELECT pg_advisory_xact_lock(7001)');
|
||||
if ((await q("SELECT 1 FROM analysis.migration WHERE name = 'articles-to-page-blocks'")).length) return;
|
||||
const arts = await q<{ id: number; subject_conf: string; subject_ext_id: string }>('SELECT id, subject_conf, subject_ext_id FROM analysis.article ORDER BY id');
|
||||
for (const a of arts) {
|
||||
const page = `paper/${a.subject_conf}/${a.subject_ext_id}`;
|
||||
const [{ n }] = await q<{ n: number }>('SELECT COALESCE(MAX(position) + 1, 0) AS n FROM analysis.page_block WHERE page = ?', [page]);
|
||||
let pos = n;
|
||||
const out: { type: string; data: any }[] = [];
|
||||
// depth-first over sections: parents before children, siblings by position
|
||||
const secs = await q<{ id: number; parent_id: number | null; key: string; title: string }>('SELECT id, parent_id, key, title FROM analysis.section WHERE article_id = ? ORDER BY position, id', [a.id]);
|
||||
const order: typeof secs = [];
|
||||
const walk = (parent: number | null) => { for (const s of secs.filter((x) => (x.parent_id ?? null) === parent)) { order.push(s); walk(s.id); } };
|
||||
walk(null);
|
||||
for (const s of order) {
|
||||
const blocks = await q<{ type: string; data: any }>('SELECT type, data FROM analysis.block WHERE section_id = ? ORDER BY position', [s.id]);
|
||||
for (const b of blocks) {
|
||||
let data = b.data;
|
||||
if (b.type === 'markdown') { const text = stripHeadings(String(data.text ?? '')); if (!text) continue; data = { ...data, text }; }
|
||||
if (b.type === 'list' && !data.lead) data = { ...data, lead: LEAD[s.key] ?? `${s.title}:` };
|
||||
out.push({ type: b.type, data });
|
||||
}
|
||||
}
|
||||
const links = await q<{ kind: string; title: string; url: string; note: string | null }>('SELECT kind, title, url, note FROM analysis.link WHERE article_id = ? ORDER BY position, id', [a.id]);
|
||||
if (links.length) out.push({ type: 'links', data: { items: links.map((l) => ({ kind: l.kind, title: l.title, url: l.url, ...(l.note ? { note: l.note } : {}) })) } });
|
||||
for (const b of out) await q('INSERT INTO analysis.page_block(page, position, type, data) VALUES (?,?,?,?::jsonb)', [page, pos++, b.type, JSON.stringify(b.data)]);
|
||||
}
|
||||
await q("INSERT INTO analysis.migration(name) VALUES ('articles-to-page-blocks')");
|
||||
});
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { route, bodyObject, bigBody, HttpError } from '../../../lib/api';
|
||||
import { deleteArticle, exportArticle, saveArticle } from '../../../lib/article-store';
|
||||
|
||||
export const config = bigBody;
|
||||
|
||||
// GET /api/articles/:slug the article as JSON (same shape PUT accepts)
|
||||
// PUT /api/articles/:slug create or replace the whole article
|
||||
// DELETE /api/articles/:slug
|
||||
export default route({
|
||||
GET: (req) => exportArticle(String(req.query.slug)),
|
||||
PUT: (req) => {
|
||||
const body = bodyObject(req);
|
||||
const slug = String(req.query.slug);
|
||||
if (body.slug && body.slug !== slug) throw new HttpError(400, `slug in body (${body.slug}) differs from the URL (${slug})`);
|
||||
return saveArticle({ ...body, slug });
|
||||
},
|
||||
DELETE: (req) => deleteArticle(String(req.query.slug)),
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
import { route, bodyObject, bigBody } from '../../../lib/api';
|
||||
import { listArticles, saveArticle } from '../../../lib/article-store';
|
||||
|
||||
export const config = bigBody;
|
||||
|
||||
// GET /api/articles list
|
||||
// POST /api/articles create or replace an article (slug in the body)
|
||||
export default route({
|
||||
GET: () => listArticles(),
|
||||
POST: (req) => saveArticle(bodyObject(req)),
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { route, bodyObject, HttpError } from '../../../lib/api';
|
||||
import { deleteBlock, getBlock, patchBlock } from '../../../lib/block-store';
|
||||
|
||||
export const config = { api: { bodyParser: { sizeLimit: '8mb' } } };
|
||||
|
||||
const id = (req: { query: Record<string, string | string[] | undefined> }) => {
|
||||
const n = Number(req.query.id);
|
||||
if (!Number.isInteger(n) || n < 1) throw new HttpError(400, 'block id must be a positive integer');
|
||||
return n;
|
||||
};
|
||||
|
||||
// GET /api/blocks/:id one block
|
||||
// PATCH /api/blocks/:id {"data": {...}} replaces the data; {"set": {"key": value|null}} changes some keys; {"type": ...} changes the type;
|
||||
// {"after": id} or {"before": id} moves it within its page
|
||||
// DELETE /api/blocks/:id
|
||||
export default route({
|
||||
GET: (req) => getBlock(id(req)),
|
||||
PATCH: (req) => patchBlock(id(req), bodyObject(req)),
|
||||
DELETE: (req) => deleteBlock(id(req)),
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { route, bodyObject, HttpError } from '../../../lib/api';
|
||||
import { addBlock, getBlocks, listPages, replacePage } from '../../../lib/block-store';
|
||||
|
||||
export const config = { api: { bodyParser: { sizeLimit: '8mb' } } };
|
||||
|
||||
const page = (req: { query: Record<string, string | string[] | undefined> }) => {
|
||||
const p = req.query.page;
|
||||
if (typeof p !== 'string' || !p) throw new HttpError(400, 'add ?page=paper/<conf>/<ext_id> or ?page=content/<node id>');
|
||||
return p;
|
||||
};
|
||||
|
||||
// GET /api/blocks pages that have blocks
|
||||
// GET /api/blocks?page=KEY the blocks of one page, in order (each has an id: that is what you point at)
|
||||
// PUT /api/blocks?page=KEY replace all blocks of the page: {"blocks":[{"type","data"}, ...]}
|
||||
// POST /api/blocks?page=KEY add one block: {"type","data","after"?: id,"before"?: id} (default: at the end)
|
||||
export default route({
|
||||
GET: async (req) => (req.query.page ? { page: page(req), blocks: await getBlocks(page(req)) } : { pages: await listPages() }),
|
||||
PUT: (req) => replacePage(page(req), bodyObject(req).blocks),
|
||||
POST: (req) => addBlock(page(req), bodyObject(req)),
|
||||
});
|
||||
+14
-107
@@ -1,125 +1,32 @@
|
||||
import type { GetServerSideProps } from 'next';
|
||||
import Link from 'next/link';
|
||||
import Layout from '../../components/Layout';
|
||||
import { getContent } from '../../lib/content';
|
||||
import Blocks from '../../components/Blocks';
|
||||
import { findNode } from '../../lib/content-tree';
|
||||
import { getToolTable, ToolTable } from '../../lib/tool-taxonomy';
|
||||
import { getPaperList, PaperListContent } from '../../lib/content-papers';
|
||||
import PaperGroup from '../../components/PaperGroup';
|
||||
import { typeSlug } from '../../lib/slug';
|
||||
import { defaultBlocks } from '../../lib/content-defaults';
|
||||
import { getBlocks, seedPage } from '../../lib/block-store';
|
||||
import { resolveBlocks } from '../../lib/block-resolve';
|
||||
import type { PageBlock } from '../../lib/blocks';
|
||||
|
||||
type Content = Awaited<ReturnType<typeof getContent>>;
|
||||
interface Props { node: { id: string; title: string; blurb: string; areas: string[]; taxonomy: string[] }; content: Content | null; tools: ToolTable | null; list: PaperListContent | null }
|
||||
interface Props { node: { id: string; title: string; blurb: string }; blocks: PageBlock[] }
|
||||
|
||||
export const getServerSideProps: GetServerSideProps<Props> = async ({ params }) => {
|
||||
const node = findNode(String(params?.node));
|
||||
if (!node || node.id === 'root') return { notFound: true };
|
||||
const { children: _c, ...plain } = node;
|
||||
if (node.kind === 'papers') return { props: { node: plain, content: null, tools: null, list: await getPaperList(node) } };
|
||||
const tools = node.kind === 'tools' ? await getToolTable() : null;
|
||||
return { props: { node: plain, content: await getContent(node), tools, list: null } };
|
||||
const page = `content/${node.id}`;
|
||||
let blocks = await getBlocks(page);
|
||||
if (!blocks.length) { await seedPage(page, defaultBlocks(node)); blocks = await getBlocks(page); }
|
||||
return { props: { node: { id: node.id, title: node.title, blurb: node.blurb }, blocks: await resolveBlocks(blocks) } };
|
||||
};
|
||||
|
||||
export default function Contents({ node, content, tools, list }: Props) {
|
||||
if (!content) {
|
||||
return (
|
||||
<Layout title={node.title}>
|
||||
<p><Link href="/contents">← Contents</Link></p>
|
||||
<h1>{node.title}</h1>
|
||||
<p className="sub">{node.blurb}</p>
|
||||
{list && <PaperGroup list={list} />}
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
const area = content.areas[0];
|
||||
/** An analysis page: title and blurb from the content tree, everything else is blocks from the database (page "content/<id>"). */
|
||||
export default function Contents({ node, blocks }: Props) {
|
||||
return (
|
||||
<Layout title={node.title}>
|
||||
<p><Link href="/contents">← Contents</Link></p>
|
||||
<h1>{node.title}</h1>
|
||||
<div>
|
||||
<section>
|
||||
<p className="sub">{node.blurb}</p>
|
||||
<div className="cards">
|
||||
<div className="card"><div className="stat">{content.total.toLocaleString()}</div>papers in this area{area ? ` (${area.label.split(',')[0]})` : ''}</div>
|
||||
{content.taxonomy.map((t) => (
|
||||
<Link key={t.id} href={`/papers?node=${t.id}`} className="card" style={{ color: 'inherit', textDecoration: 'none' }}>
|
||||
<div className="stat">{t.n.toLocaleString()}</div>in taxonomy: <b style={{ color: 'var(--accent)' }}>{t.label}</b>
|
||||
</Link>
|
||||
))}
|
||||
<div className="card"><div className="stat">{content.benchmarks.length}</div>benchmarks most used here</div>
|
||||
</div>
|
||||
|
||||
{tools && (
|
||||
<>
|
||||
<h2>Tools by category</h2>
|
||||
<p className="sub">
|
||||
{tools.tools} tool{tools.tools === 1 ? '' : 's'} from {tools.papers} paper{tools.papers === 1 ? '' : 's'}. A tool can sit in several categories. A category lists every tool filed under it or under a category below it
|
||||
(marked “via …”); each tool links to the paper that designed it.
|
||||
</p>
|
||||
{tools.rows.length === 0 && <p className="sub">No tools yet. Add them with <code>PUT /api/tool-taxonomy/papers/<conf>/<ext_id></code>.</p>}
|
||||
{tools.rows.length > 0 && (
|
||||
<div style={{ overflowX: 'auto' }}>
|
||||
<table>
|
||||
<thead><tr><th>Category</th><th>Papers</th><th>Tools (paper)</th></tr></thead>
|
||||
<tbody>
|
||||
{tools.rows.map((r) => (
|
||||
<tr key={r.slug} id={r.slug}>
|
||||
<td title={r.descr ?? undefined}>
|
||||
{r.path.slice(0, -1).map((t, i) => <span key={i} style={{ color: 'var(--muted)' }}>{t} → </span>)}
|
||||
<b>{r.title}</b>
|
||||
</td>
|
||||
<td>{r.papers || ''}</td>
|
||||
<td>
|
||||
{r.entries.length === 0 ? '—' : r.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>
|
||||
)}
|
||||
{tools.uncategorised.length > 0 && (
|
||||
<p className="sub">
|
||||
Not in any category yet: {tools.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>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{content.reviews.length > 0 && (
|
||||
<>
|
||||
<h2>Reviews</h2>
|
||||
<div className="cards">
|
||||
{content.reviews.map((r) => (
|
||||
<Link key={r.type_id} href={`/work-types/${typeSlug(r.type_id)}`} className="card" style={{ color: 'inherit', textDecoration: 'none' }}>
|
||||
<b style={{ color: 'var(--accent)' }}>{r.title}</b>
|
||||
<div className="sub" style={{ margin: '4px 0 0', fontSize: 13 }}>{r.n} papers</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<h2>Benchmarks used</h2>
|
||||
<table>
|
||||
<thead><tr><th>Benchmark</th><th>Papers</th><th>Introduced in 2026</th></tr></thead>
|
||||
<tbody>
|
||||
{content.benchmarks.map((b) => (
|
||||
<tr key={b.id}><td><Link href={`/benchmarks/${b.id}`}>{b.name}</Link></td><td>{b.n}</td><td>{b.n_new || ''}</td></tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
</section>
|
||||
</div>
|
||||
<p className="sub">{node.blurb}</p>
|
||||
<Blocks blocks={blocks} />
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
|
||||
+11
-8
@@ -5,20 +5,23 @@ import { getPaper } from '../../lib/queries';
|
||||
import { getPaperWork } from '../../lib/worktypes';
|
||||
import { typeSlug } from '../../lib/slug';
|
||||
import { Paper } from '../../lib/types';
|
||||
import ArticleView from '../../components/ArticleView';
|
||||
import { getArticlesFor } from '../../lib/articles';
|
||||
import type { ArticleData } from '../../lib/article-types';
|
||||
import Blocks from '../../components/Blocks';
|
||||
import { getBlocks } from '../../lib/block-store';
|
||||
import type { PageBlock } from '../../lib/blocks';
|
||||
|
||||
type Props = { paper: Paper & { topics: { id: string; label: string }[] }; work: Awaited<ReturnType<typeof getPaperWork>>; articles: ArticleData[] };
|
||||
type Props = { paper: Paper & { topics: { id: string; label: string }[] }; work: Awaited<ReturnType<typeof getPaperWork>>; blocks: PageBlock[] };
|
||||
|
||||
export const getServerSideProps: GetServerSideProps<Props> = async ({ params }) => {
|
||||
const paper = await getPaper(Number(params?.id));
|
||||
if (!paper) return { notFound: true };
|
||||
const [work, articles] = await Promise.all([getPaperWork(paper.id), getArticlesFor(paper.conf, paper.ext_id ?? null)]);
|
||||
return { props: { paper, work, articles } };
|
||||
const [work, blocks] = await Promise.all([
|
||||
getPaperWork(paper.id),
|
||||
paper.ext_id ? getBlocks(`paper/${paper.conf}/${paper.ext_id}`).catch(() => []) : Promise.resolve([]), // no database for blocks: show the paper without them
|
||||
]);
|
||||
return { props: { paper, work, blocks } };
|
||||
};
|
||||
|
||||
export default function PaperPage({ paper: p, work, articles }: Props) {
|
||||
export default function PaperPage({ paper: p, work, blocks }: Props) {
|
||||
return (
|
||||
<Layout title={p.title}>
|
||||
<p><Link href={`/papers?conf=${p.conf}`}>← {p.conf_short} 2026 papers</Link></p>
|
||||
@@ -30,7 +33,7 @@ export default function PaperPage({ paper: p, work, articles }: Props) {
|
||||
{p.award && p.award !== 'Poster' && <span className="badge award">{p.award}</span>}
|
||||
{p.topics.map((t) => <Link key={t.id} href={`/papers?node=${t.id}`} className="badge topic">{t.label}</Link>)}
|
||||
</p>
|
||||
{articles.map((a) => <ArticleView key={a.slug} a={a} />)}
|
||||
{blocks.length > 0 && <Blocks blocks={blocks} />}
|
||||
{work.meta?.summary && <p><b>Summary:</b> {work.meta.summary}</p>}
|
||||
<h2>Types of work</h2>
|
||||
<div className="card">
|
||||
|
||||
+19
-14
@@ -72,28 +72,33 @@ details.extract summary{cursor:pointer;font-weight:600;margin:8px 0}
|
||||
section[id]{scroll-margin-top:100px}
|
||||
h3{font-size:16px;margin:18px 0 8px}
|
||||
|
||||
/* analysis articles */
|
||||
.analysis{margin:18px 0 28px;padding:16px 18px;background:var(--card);border:1px solid var(--line);border-radius:12px}
|
||||
.analysis-head{padding-bottom:8px;border-bottom:1px solid var(--line);margin-bottom:12px}
|
||||
.art-body{min-width:0;font-size:15.5px;line-height:1.65}
|
||||
.art-section{scroll-margin-top:70px}
|
||||
.art-section h2{font-size:20px;margin:30px 0 10px;padding-top:6px;border-top:1px solid var(--line)}
|
||||
.art-section:first-child h2{border-top:0;margin-top:6px}
|
||||
.art-section h3,.art-body h3.md-h{font-size:16.5px;margin:20px 0 6px}
|
||||
.art-body table{font-size:13.5px;line-height:1.5;margin:8px 0 16px}
|
||||
.art-body table.num td:not(:first-child),.art-body table.num th:not(:first-child){text-align:right;font-variant-numeric:tabular-nums}
|
||||
.art-body td.hl{background:var(--accent-bg);font-weight:600}
|
||||
.callout{border-left:4px solid var(--accent);background:var(--accent-bg);border-radius:6px;padding:10px 14px;margin:12px 0}
|
||||
/* page blocks: a page is a flat list of independent cards ("stories"); no headings inside */
|
||||
.blocks{display:flex;flex-direction:column;gap:14px;margin:16px 0 28px;max-width:860px}
|
||||
.block{position:relative;padding:14px 18px;background:var(--card);border:1px solid var(--line);border-radius:12px;font-size:15.5px;line-height:1.65;scroll-margin-top:70px;min-width:0}
|
||||
.block.bare{padding:0;background:none;border:0}
|
||||
.block:target{border-color:var(--accent)}
|
||||
.block-id{position:absolute;top:6px;right:10px;font-size:11px;line-height:1;color:var(--muted);opacity:.55;text-decoration:none;font-variant-numeric:tabular-nums}
|
||||
.block:hover .block-id{opacity:1}
|
||||
.block.bare .block-id{top:-8px;right:0}
|
||||
.block > :first-child{margin-top:0}.block > :last-child{margin-bottom:0}
|
||||
.block p{margin:0 0 10px}
|
||||
.block ul,.block ol{margin:0 0 6px;padding-left:22px}
|
||||
.block ul.links{list-style:none;padding:0}.block ul.links li{margin:4px 0}
|
||||
.block table{font-size:13.5px;line-height:1.5;margin:0}
|
||||
.block table.num td:not(:first-child),.block table.num th:not(:first-child){text-align:right;font-variant-numeric:tabular-nums}
|
||||
.block td.hl{background:var(--accent-bg);font-weight:600}
|
||||
.callout{border-left:4px solid var(--accent);background:var(--accent-bg);border-radius:6px;padding:10px 14px}
|
||||
.block-callout{padding:0;border:0;background:none}
|
||||
.callout.note{border-left-color:#1b9e77;background:color-mix(in srgb,#1b9e77 12%,transparent)}
|
||||
.callout.warn{border-left-color:#e0702b;background:color-mix(in srgb,#e0702b 14%,transparent)}
|
||||
.chart-fig,.mermaid-fig,.tbl-wrap{margin:14px 0}
|
||||
.chart-fig,.mermaid-fig,.tbl-wrap{margin:0}
|
||||
.chart-title{font-weight:600;font-size:14px;margin-bottom:4px}
|
||||
.chart-note,.mermaid-fig figcaption{color:var(--muted);font-size:12.5px;margin-top:4px}
|
||||
.chart-fig .legend{display:flex;flex-wrap:wrap;gap:12px;font-size:12px;margin-top:4px}
|
||||
.legend i{display:inline-block;width:10px;height:10px;border-radius:2px;margin-right:5px}
|
||||
.mermaid-svg{overflow-x:auto;text-align:center}
|
||||
.mermaid-svg svg{max-width:100%;height:auto}
|
||||
pre.mermaid-src,pre.code-block{background:var(--bg);border:1px solid var(--line);border-radius:8px;padding:10px 12px;overflow:auto;font-size:12.5px}
|
||||
pre.mermaid-src,pre.code-block{background:var(--bg);border:1px solid var(--line);border-radius:8px;padding:10px 12px;overflow:auto;font-size:12.5px;margin:0}
|
||||
|
||||
/* waterfall (masonry) layout of analysis pages on /contents */
|
||||
.masonry{column-width:300px;column-gap:16px}
|
||||
|
||||
Reference in New Issue
Block a user