diff --git a/components/ArticleView.tsx b/components/ArticleView.tsx deleted file mode 100644 index 99fb011..0000000 --- a/components/ArticleView.tsx +++ /dev/null @@ -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: () =>
Loading diagram…
}); - -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({text}); - else out.push({text} ↗); - } else if (m[2]) out.push({inline(t.slice(2, -2))}); - else if (m[3]) out.push({t.slice(1, -1)}); - else out.push({t.slice(1, -1)}); - 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 ?

{inline(h[2])}

:

{inline(h[2])}

; - const lines = src.split('\n'); - if (lines.every((l) => /^\s*[-*]\s+/.test(l))) return ; - if (lines.every((l) => /^\s*\d+[.)]\s+/.test(l))) return
    {lines.map((l, j) =>
  1. {inline(l.replace(/^\s*\d+[.)]\s+/, ''))}
  2. )}
; - return

{inline(lines.join(' '))}

; - })} - - ); -} - -/* ---------- horizontal bar chart (SVG) ---------- */ -function BarChart({ d }: { d: Extract['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 ( -
-
{d.title}
- - {d.labels.map((lab, i) => { - const y = top + i * (rowH + 8); - return ( - - {lab.length > 26 ? lab.slice(0, 25) + '…' : lab}{lab} - {d.series.map((s, j) => { - const h = rowH / d.series.length, yy = y + j * h; - const hi = d.highlight?.includes(i); - return ( - - - {`${lab}${d.series.length > 1 ? ' · ' + s.name : ''}: ${fmt(s.values[i])}`} - - {fmt(s.values[i])} - - ); - })} - - ); - })} - - {d.series.length > 1 &&
{d.series.map((s, j) => {s.name})}
} - {d.note &&
{d.note}
} -
- ); -} - -function BlockView({ b }: { b: Block }) { - switch (b.type) { - case 'markdown': return ; - case 'list': { - const Tag = b.data.ordered ? 'ol' : 'ul'; - return {b.data.items.map((it, i) =>
  • {inline(it)}
  • )}
    ; - } - case 'callout': - return
    {b.data.title && {b.data.title}. }{inline(b.data.text)}
    ; - case 'table': { - const d = b.data; - return ( -
    - {d.caption &&
    {d.caption}
    } -
    - - {d.columns.map((c, i) => )} - {d.rows.map((r, i) => {r.map((c, j) => )})} -
    {c}
    {inline(c)}
    -
    -
    - ); - } - case 'chart': return ; - case 'mermaid': return ; - case 'figure': - return /^(https:\/\/|\/)/.test(b.data.src) - ?
    {b.data.alt}{b.data.caption &&
    {b.data.caption}
    }
    - : null; - case 'code': return
    {b.data.text}
    ; - } -} - -function SectionView({ s, id }: { s: Section; id: string }) { - const H = (s.level <= 2 ? 'h2' : 'h3') as 'h2' | 'h3'; - return ( -
    - {s.title} - {s.blocks.map((b, i) => )} - {s.children.map((c) => )} -
    - ); -} - -const toc = (secs: Section[], id: string, depth = 0): ReactNode => - secs.map((s) => ( - - {s.title} - {toc(s.children, id, depth + 1)} - - )); - -export default function ArticleView({ a }: { a: ArticleData }) { - return ( -
    -
    - Analysis -

    {a.title}

    - {a.summary &&

    {a.summary}

    } -

    revision {a.revision} · updated {a.updatedAt}

    -
    -
    - -
    - {a.sections.map((s) => )} - {a.links.length > 0 && ( -
    -

    Links

    -
      - {a.links.map((l) => ( -
    • - {l.kind}{' '} - {l.url.startsWith('/') ? {l.title} : {l.title} ↗} - {l.note && — {l.note}} -
    • - ))} -
    -
    - )} -
    -
    -
    - ); -} diff --git a/components/Blocks.tsx b/components/Blocks.tsx new file mode 100644 index 0000000..fac0961 --- /dev/null +++ b/components/Blocks.tsx @@ -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: () =>
    Loading diagram…
    }); + +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({text}); + else out.push({text} ↗); + } else if (m[2]) out.push({inline(t.slice(2, -2))}); + else if (m[3]) out.push({t.slice(1, -1)}); + else out.push({t.slice(1, -1)}); + 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
      {lines.map((l, j) =>
    • {inline(l.replace(/^\s*[-*]\s+/, ''))}
    • )}
    ; + if (lines.every((l) => /^\s*\d+[.)]\s+/.test(l))) return
      {lines.map((l, j) =>
    1. {inline(l.replace(/^\s*\d+[.)]\s+/, ''))}
    2. )}
    ; + return

    {inline(lines.join(' '))}

    ; + })} + + ); +} + +/* ---------- horizontal bar chart (SVG) ---------- */ +function BarChart({ d }: { d: Extract['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 ( +
    +
    {d.title}
    + + {d.labels.map((lab, i) => { + const y = top + i * (rowH + 8); + return ( + + {lab.length > 26 ? lab.slice(0, 25) + '…' : lab}{lab} + {d.series.map((s, j) => { + const h = rowH / d.series.length, yy = y + j * h; + const hi = d.highlight?.includes(i); + return ( + + + {`${lab}${d.series.length > 1 ? ' · ' + s.name : ''}: ${fmt(s.values[i])}`} + + {fmt(s.values[i])} + + ); + })} + + ); + })} + + {d.series.length > 1 &&
    {d.series.map((s, j) => {s.name})}
    } + {d.note &&
    {d.note}
    } +
    + ); +} + +const Caption = ({ text }: { text?: string }) => (text ?
    {text}
    : null); +const Note = ({ text, vars }: { text?: string; vars?: Record }) => + text ?

    {inline(Object.entries(vars ?? {}).reduce((t, [k, v]) => t.split(`{${k}}`).join(String(v)), text))}

    : null; + +function StaticBlock({ b }: { b: Block }) { + switch (b.type) { + case 'markdown': return ; + case 'list': { + const Tag = b.data.ordered ? 'ol' : 'ul'; + return <>{b.data.lead &&

    {inline(b.data.lead)}

    }{b.data.items.map((it, i) =>
  • {inline(it)}
  • )}
    ; + } + case 'callout': + return
    {b.data.title && {b.data.title}. }{inline(b.data.text)}
    ; + case 'table': { + const d = b.data; + return ( +
    + +
    + + {d.columns.map((c, i) => )} + {d.rows.map((r, i) => {r.map((c, j) => )})} +
    {c}
    {inline(c)}
    +
    +
    + ); + } + case 'chart': return ; + case 'mermaid': return ; + case 'figure': + return /^(https:\/\/|\/)/.test(b.data.src) + ?
    {b.data.alt}{b.data.caption &&
    {b.data.caption}
    }
    + : null; + case 'code': return
    {b.data.text}
    ; + case 'links': + return ( +
      + {b.data.items.map((l) => ( +
    • + {l.kind}{' '} + {l.url.startsWith('/') ? {l.title} : {l.title} ↗} + {l.note && — {l.note}} +
    • + ))} +
    + ); + 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 ( +
    + {r.items.map((s, i) => { + const inner = <>
    {typeof s.value === 'number' ? s.value.toLocaleString() : s.value}
    {s.label}; + return s.href + ? {inner} + :
    {inner}
    ; + })} +
    + ); + } + if (b.type === 'tool-table' && r.type === 'tool-table') { + const t = r.table; + return ( + <> + + + {t.rows.length === 0 &&

    No tools yet. Add them with PUT /api/tool-taxonomy/papers/<conf>/<ext_id>.

    } + {t.rows.length > 0 && ( +
    + + + + {t.rows.map((row) => ( + + + + + + ))} + +
    CategoryPapersTools (paper)
    + {row.path.slice(0, -1).map((x, i) => {x} → )} + {row.title} + {row.papers || ''} + {row.entries.length === 0 ? '—' : row.entries.map((e, i) => ( +
    + {e.tool}{' '} + ({e.paperId ? {e.paperLabel} : e.paperLabel}) + {e.via && · via {e.via}} +
    + ))} +
    +
    + )} + {t.uncategorised.length > 0 && ( +

    + Not in any category yet: {t.uncategorised.map((e, i) => ( + {i ? ', ' : ''}{e.tool} ({e.paperId ? {e.paperLabel} : e.paperLabel}) + ))} +

    + )} + + ); + } + if (b.type === 'paper-table' && r.type === 'paper-table') { + return ( + <> + + +
    + + + + {r.papers.map((p) => ( + + + + + + + ))} + +
    PaperVenueDateAnalysis
    {p.title}{p.conf_short}{p.date}{p.analysed ? '✓' : ''}
    +
    + + ); + } + if (b.type === 'benchmark-table' && r.type === 'benchmark-table') { + if (!r.rows.length) return null; + return ( + <> + + +
    + + {r.showNew && } + {r.rows.map((x) => {r.showNew && })} +
    BenchmarkPapersIntroduced in 2026
    {x.name}{x.n}{x.n_new || ''}
    +
    + + ); + } + 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 ( +
    + {blocks.map((pb) => { + const live = LIVE.includes(pb.block.type); + if (live && !pb.resolved) return null; + return ( +
    + #{pb.id} + {live ? : } +
    + ); + })} +
    + ); +} diff --git a/components/PaperGroup.tsx b/components/PaperGroup.tsx deleted file mode 100644 index e342eb2..0000000 --- a/components/PaperGroup.tsx +++ /dev/null @@ -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 ( - <> -
    -
    {list.total}
    papers in this group
    -
    {list.analysed.length}
    analysed in depth
    - {list.byVenue.slice(0, 4).map((v) =>
    {v.n}
    at {v.conf_short}
    )} -
    - - {list.benchmarks.length > 0 && ( - <> -

    Benchmarks these papers use

    - - - {list.benchmarks.map((b) => )} -
    BenchmarkPapers
    {b.name}{b.n}
    - - )} - -

    All papers in the group

    -

    Matched by text (title, abstract, keywords); a paper may be a false match.

    - - - - {list.papers.map((p) => ( - - - - - - - ))} - -
    PaperVenueDateAnalysis
    {p.title}{p.conf_short}{p.date}{p.analysed ? '✓' : ''}
    - - ); -} diff --git a/lib/analysis-schema.ts b/lib/analysis-schema.ts index f10de7b..802ab3b 100644 --- a/lib/analysis-schema.ts +++ b/lib/analysis-schema.ts @@ -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//' (a paper's detail page) or 'content/' (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 | null = null; /** Create the analysis schema if it is missing (cached per process). */ export function ensureAnalysisSchema(): Promise { - 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; } diff --git a/lib/api.ts b/lib/api.ts index 2a49689..6bc1c9f 100644 --- a/lib/api.ts +++ b/lib/api.ts @@ -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; /** Dispatch by HTTP method; a handler returns the JSON to send, or throws HttpError. */ diff --git a/lib/article-store.ts b/lib/article-store.ts deleted file mode 100644 index d83ccf2..0000000 --- a/lib/article-store.ts +++ /dev/null @@ -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(); - 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 = {}; - 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 { - await ensureAnalysisSchema(); - const [a] = await query('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('SELECT id, parent_id, key, title, level FROM analysis.section WHERE article_id = ? ORDER BY position, id', [a.id]), - query('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('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(); - 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 }; -} diff --git a/lib/article-types.ts b/lib/article-types.ts deleted file mode 100644 index 65f15af..0000000 --- a/lib/article-types.ts +++ /dev/null @@ -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[] } diff --git a/lib/articles.ts b/lib/articles.ts deleted file mode 100644 index 810e4cb..0000000 --- a/lib/articles.ts +++ /dev/null @@ -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 { - 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(); - 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(); - 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(); - 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 - } -} diff --git a/lib/block-resolve.ts b/lib/block-resolve.ts new file mode 100644 index 0000000..6402fd1 --- /dev/null +++ b/lib/block-resolve.ts @@ -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>; +type List = Awaited>; + +/** Fill the dynamic blocks of a page (stats, tables) with live numbers. Static blocks pass through unchanged. */ +export async function resolveBlocks(blocks: PageBlock[]): Promise { + const contents = new Map>(); + const lists = new Map>(); + 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 | null = null; + + return Promise.all(blocks.map(async (pb): Promise => { + 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; + })); +} diff --git a/lib/block-store.ts b/lib/block-store.ts new file mode 100644 index 0000000..3921119 --- /dev/null +++ b/lib/block-store.ts @@ -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//" (a paper) or "content/" (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 { + await ensureAnalysisSchema(); + return (await query('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 = (sql: string, params?: unknown[]) => Promise; +async function placeAt(q: Q, page: string, body: { after?: number; before?: number }): Promise { + 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('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)]); + } + }); +} diff --git a/lib/blocks.ts b/lib/blocks.ts new file mode 100644 index 0000000..0c178cc --- /dev/null +++ b/lib/blocks.ts @@ -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 } diff --git a/lib/content-defaults.ts b/lib/content-defaults.ts new file mode 100644 index 0000000..a9f3ad0 --- /dev/null +++ b/lib/content-defaults.ts @@ -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.' } }, + ]; +} diff --git a/lib/content-papers.ts b/lib/content-papers.ts index cbfd800..9e5f16e 100644 --- a/lib/content-papers.ts +++ b/lib/content-papers.ts @@ -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 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//) + 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(); - 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); diff --git a/lib/legacy-migrate.ts b/lib/legacy-migrate.ts new file mode 100644 index 0000000..8c9487a --- /dev/null +++ b/lib/legacy-migrate.ts @@ -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 = { + '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 { + 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')"); + }); +} diff --git a/pages/api/articles/[slug].ts b/pages/api/articles/[slug].ts deleted file mode 100644 index dcd1e85..0000000 --- a/pages/api/articles/[slug].ts +++ /dev/null @@ -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)), -}); diff --git a/pages/api/articles/index.ts b/pages/api/articles/index.ts deleted file mode 100644 index 84ddd02..0000000 --- a/pages/api/articles/index.ts +++ /dev/null @@ -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)), -}); diff --git a/pages/api/blocks/[id].ts b/pages/api/blocks/[id].ts new file mode 100644 index 0000000..2b0581e --- /dev/null +++ b/pages/api/blocks/[id].ts @@ -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 }) => { + 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)), +}); diff --git a/pages/api/blocks/index.ts b/pages/api/blocks/index.ts new file mode 100644 index 0000000..f821d22 --- /dev/null +++ b/pages/api/blocks/index.ts @@ -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 }) => { + const p = req.query.page; + if (typeof p !== 'string' || !p) throw new HttpError(400, 'add ?page=paper// or ?page=content/'); + 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)), +}); diff --git a/pages/contents/[node].tsx b/pages/contents/[node].tsx index e6aad9f..76e8698 100644 --- a/pages/contents/[node].tsx +++ b/pages/contents/[node].tsx @@ -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>; -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 = 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 ( - -

    ← Contents

    -

    {node.title}

    -

    {node.blurb}

    - {list && } -
    - ); - } - const area = content.areas[0]; +/** An analysis page: title and blurb from the content tree, everything else is blocks from the database (page "content/"). */ +export default function Contents({ node, blocks }: Props) { return (

    ← Contents

    {node.title}

    -
    -
    -

    {node.blurb}

    -
    -
    {content.total.toLocaleString()}
    papers in this area{area ? ` (${area.label.split(',')[0]})` : ''}
    - {content.taxonomy.map((t) => ( - -
    {t.n.toLocaleString()}
    in taxonomy: {t.label} - - ))} -
    {content.benchmarks.length}
    benchmarks most used here
    -
    - - {tools && ( - <> -

    Tools by category

    -

    - {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. -

    - {tools.rows.length === 0 &&

    No tools yet. Add them with PUT /api/tool-taxonomy/papers/<conf>/<ext_id>.

    } - {tools.rows.length > 0 && ( -
    - - - - {tools.rows.map((r) => ( - - - - - - ))} - -
    CategoryPapersTools (paper)
    - {r.path.slice(0, -1).map((t, i) => {t} → )} - {r.title} - {r.papers || ''} - {r.entries.length === 0 ? '—' : r.entries.map((e, i) => ( -
    - {e.tool}{' '} - ({e.paperId ? {e.paperLabel} : e.paperLabel}) - {e.via && · via {e.via}} -
    - ))} -
    -
    - )} - {tools.uncategorised.length > 0 && ( -

    - Not in any category yet: {tools.uncategorised.map((e, i) => ( - {i ? ', ' : ''}{e.tool} ({e.paperId ? {e.paperLabel} : e.paperLabel}) - ))} -

    - )} - - )} - - {content.reviews.length > 0 && ( - <> -

    Reviews

    -
    - {content.reviews.map((r) => ( - - {r.title} -
    {r.n} papers
    - - ))} -
    - - )} - -

    Benchmarks used

    - - - - {content.benchmarks.map((b) => ( - - ))} - -
    BenchmarkPapersIntroduced in 2026
    {b.name}{b.n}{b.n_new || ''}
    - -
    -
    +

    {node.blurb}

    +
    ); } diff --git a/pages/papers/[id].tsx b/pages/papers/[id].tsx index bfa58a6..eb7e2ef 100644 --- a/pages/papers/[id].tsx +++ b/pages/papers/[id].tsx @@ -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>; articles: ArticleData[] }; +type Props = { paper: Paper & { topics: { id: string; label: string }[] }; work: Awaited>; blocks: PageBlock[] }; export const getServerSideProps: GetServerSideProps = 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 (

    ← {p.conf_short} 2026 papers

    @@ -30,7 +33,7 @@ export default function PaperPage({ paper: p, work, articles }: Props) { {p.award && p.award !== 'Poster' && {p.award}} {p.topics.map((t) => {t.label})}

    - {articles.map((a) => )} + {blocks.length > 0 && } {work.meta?.summary &&

    Summary: {work.meta.summary}

    }

    Types of work

    diff --git a/styles/globals.css b/styles/globals.css index 1970236..342bde1 100644 --- a/styles/globals.css +++ b/styles/globals.css @@ -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}