/** * A chart inside an article: a fenced ` ```chart ` block holding a small spec * the writer can read and edit by hand. Pure parsing and fallbacks; drawing is * `@bitbaum/chartkit`'s (see `@bitbaum/writingkit/react/chart`). * * Two spellings, both short enough to type on a phone: * * JSON — the block the Chart tool inserts: * { "kind": "bar", "title": "…", "unit": "CHF", "source": "…", * "series": [{ "name": "Sales", "points": [["2024", 10], ["2025", 14]] }] } * * CSV — optional `key: value` lines, then a header row and data rows * (bip-kit's `series Name: Jan=12, Feb=30` lines are read too): * title: Members by year * kind: line * year,Members * 2024,120 * 2025,180 * * Kinds: `bar` (columns, in the order given — periods read left to right), * `ranking` (horizontal bars, largest first), `line`, `area`. A line or area * whose labels are not periods or numbers is drawn as columns: a line between * "Zurich" and "Basel" means nothing. * * Anywhere a chart cannot be drawn (an RSS reader, a share card, a plain * Markdown renderer) the same numbers become a table: `chartTableMarkdown`. * A spec that does not parse is reported in words, never drawn half. */ export const CHART_FENCE = "chart"; export const CHART_KINDS = ["bar", "ranking", "line", "area"]; export const CHART_LIMITS = { series: 8, points: 120, label: 40, title: 160, source: 200, unit: 16, /** The whole block, before parsing. */ block: 20_000, }; const fail = (problem) => ({ ok: false, problem }); const clip = (value, max) => typeof value === "string" ? value.trim().slice(0, max) : ""; function toNumber(value) { if (value === null || value === "" || value === "-" || value === "—") return null; if (typeof value === "number") return Number.isFinite(value) ? value : undefined; if (typeof value !== "string") return undefined; // "1,234.5", "12%", "CHF 40" → the number; a stray word is not a number. const cleaned = value.trim().replace(/[\s'’]/g, "").replace(/,(?=\d{3}\b)/g, ""); const match = cleaned.match(/^[^\d+-]{0,4}([+-]?\d+(?:\.\d+)?)%?$/); return match ? Number(match[1]) : undefined; } function kindOf(value) { const k = typeof value === "string" ? value.trim().toLowerCase() : "bar"; if (k === "column" || k === "columns") return "bar"; if (k === "bars" || k === "rank") return "ranking"; return CHART_KINDS.includes(k) ? k : null; } function finish(kind, meta, series) { if (!kind) return fail(`Kind must be one of: ${CHART_KINDS.join(", ")}.`); const title = clip(meta.title, CHART_LIMITS.title); if (!title) return fail("Give the chart a title that says what it shows."); if (series.length === 0) return fail("The chart has no numbers yet."); if (series.length > CHART_LIMITS.series) return fail(`At most ${CHART_LIMITS.series} series in one chart.`); for (const s of series) { if (s.points.length === 0) return fail(`“${s.name}” has no points.`); if (s.points.length > CHART_LIMITS.points) return fail(`At most ${CHART_LIMITS.points} points in a series.`); } if (!series.some((s) => s.points.some(([, y]) => y !== null))) return fail("Every value is empty."); const unit = clip(meta.unit, CHART_LIMITS.unit) || undefined; const source = clip(meta.source, CHART_LIMITS.source) || undefined; return { ok: true, chart: { kind, title, ...(unit ? { unit } : {}), ...(source ? { source } : {}), series, }, }; } function parseJson(raw) { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return fail("The chart block must be one JSON object."); const r = raw; if (!Array.isArray(r.series)) return fail("The chart needs a series list."); const series = []; for (const [i, entry] of r.series.entries()) { if (!entry || typeof entry !== "object") return fail(`Series ${i + 1} is not an object.`); const e = entry; const name = clip(e.name, CHART_LIMITS.label) || `Series ${i + 1}`; if (!Array.isArray(e.points)) return fail(`“${name}” needs points.`); const points = []; for (const p of e.points) { const [x, y] = Array.isArray(p) ? [p[0], p[1]] : p && typeof p === "object" ? [p.x, p.y] : [undefined, undefined]; const label = typeof x === "number" ? String(x) : clip(x, CHART_LIMITS.label); const value = toNumber(y); if (!label || value === undefined) return fail(`A point in “${name}” is not [label, number].`); points.push([label, value]); } series.push({ name, points }); } return finish(kindOf(r.kind), r, series); } function splitCsvLine(line) { const delimiter = line.includes("\t") ? "\t" : line.includes(";") ? ";" : ","; const cells = []; let cell = ""; let quoted = false; for (let i = 0; i < line.length; i++) { const ch = line[i]; if (ch === '"') { if (quoted && line[i + 1] === '"') { cell += '"'; i++; } else quoted = !quoted; } else if (ch === delimiter && !quoted) { cells.push(cell.trim()); cell = ""; } else cell += ch; } cells.push(cell.trim()); return cells; } function parseCsv(text) { const meta = {}; const rows = []; const lineSeries = []; for (const line of text.split(/\r?\n/)) { if (!line.trim()) continue; // bip-kit's line format, so a block written for its reader still draws: // series Organic: Jan=12, Feb=30 const named = rows.length === 0 ? line.match(/^\s*series\s+(.+?)\s*:\s*(.+)$/i) : null; if (named) { const points = []; for (const pair of named[2].split(",")) { const m = pair.trim().match(/^(.+?)\s*=\s*(.*)$/); const value = m ? toNumber(m[2]) : undefined; if (!m || value === undefined) return fail(`“${pair.trim()}” in “${named[1]}” is not label=number.`); points.push([m[1].slice(0, CHART_LIMITS.label), value]); } lineSeries.push({ name: named[1].slice(0, CHART_LIMITS.label), points }); continue; } const kv = rows.length === 0 ? line.match(/^\s*(title|kind|unit|ylabel|source)\s*:\s*(.*)$/i) : null; if (kv) { const key = kv[1].toLowerCase(); meta[key === "ylabel" ? "unit" : key] = kv[2]; continue; } rows.push(splitCsvLine(line)); } if (lineSeries.length > 0) { if (rows.length > 0) return fail("Use either series lines or a table, not both."); return finish(kindOf(meta.kind ?? "bar"), meta, lineSeries); } const [header, ...data] = rows; if (!header || header.length < 2 || data.length === 0) return fail("Write a header row (label, then one name per series) and at least one row of numbers."); const series = header.slice(1).map((name, i) => ({ name: name.slice(0, CHART_LIMITS.label) || `Series ${i + 1}`, points: [], })); for (const row of data) { const label = (row[0] ?? "").slice(0, CHART_LIMITS.label); if (!label) return fail("Every row starts with its label."); for (const [i, s] of series.entries()) { const value = toNumber(row[i + 1] ?? ""); if (value === undefined) return fail(`“${row[i + 1]}” in the row “${label}” is not a number.`); s.points.push([label, value]); } } return finish(kindOf(meta.kind ?? "bar"), meta, series); } /** Parse the text inside a ` ```chart ` fence. */ export function parseChartBlock(source) { if (typeof source !== "string" || !source.trim()) return fail("The chart block is empty."); if (source.length > CHART_LIMITS.block) return fail("The chart block is too long."); const trimmed = source.trim(); if (trimmed.startsWith("{")) { try { return parseJson(JSON.parse(trimmed)); } catch { return fail("The chart block is not valid JSON. Check the commas and quotes."); } } return parseCsv(trimmed); } /** Periods (2025, 2025-Q2, 2025-03, 2025-03-31) or plain numbers: a line can join them. */ export function chartHasOrderedLabels(chart) { return chart.series.every((s) => s.points.every(([x]) => /^\d{4}(?:-Q[1-4]|-\d{2}(?:-\d{2})?)?$/.test(x) || /^-?\d+(?:\.\d+)?$/.test(x))); } /** The kind that will actually be drawn: a line over non-periods is columns. */ export function drawnKind(chart) { return (chart.kind === "line" || chart.kind === "area") && !chartHasOrderedLabels(chart) ? "bar" : chart.kind; } /** The numbers as rows: first column the label, one column per series. */ export function chartTable(chart) { const labels = []; for (const s of chart.series) for (const [x] of s.points) if (!labels.includes(x)) labels.push(x); const value = (s, x) => { const y = s.points.find(([px]) => px === x)?.[1]; return y === null || y === undefined ? "—" : String(y); }; return { head: ["", ...chart.series.map((s) => s.name)], rows: labels.map((x) => [x, ...chart.series.map((s) => value(s, x))]), }; } const cell = (text) => text.replace(/\|/g, "\\|"); /** A GFM table with the title above and the source under: the chart without a drawing. */ export function chartTableMarkdown(chart) { const { head, rows } = chartTable(chart); const unit = chart.unit ? ` (${chart.unit})` : ""; return [ `**${cell(chart.title)}**${unit}`, "", `| ${head.map(cell).join(" | ")} |`, `| ${head.map(() => "---").join(" | ")} |`, ...rows.map((r) => `| ${r.map(cell).join(" | ")} |`), ...(chart.source ? ["", `Source: ${chart.source}`] : []), ].join("\n"); } const FENCE = /^(```|~~~)[ \t]*chart[ \t]*\r?\n([\s\S]*?)\r?\n\1[ \t]*$/gm; /** Split Markdown into prose and ` ```chart ` blocks, in order. */ export function splitChartBlocks(markdown) { const out = []; let last = 0; for (const match of markdown.matchAll(FENCE)) { const at = match.index ?? 0; if (at > last) out.push({ kind: "markdown", text: markdown.slice(last, at) }); const source = match[2] ?? ""; out.push({ kind: "chart", source, parsed: parseChartBlock(source) }); last = at + match[0].length; } if (last < markdown.length) out.push({ kind: "markdown", text: markdown.slice(last) }); return out.filter((s) => s.kind === "chart" || s.text.trim()); } /** * Markdown for a renderer that cannot draw: every chart block becomes its * table; a block that does not parse is left out rather than shown as code. */ export function chartsToTables(markdown) { return splitChartBlocks(markdown) .map((s) => s.kind === "markdown" ? s.text.trim() : s.parsed.ok ? chartTableMarkdown(s.parsed.chart) : "") .filter(Boolean) .join("\n\n"); } /** A chart as the fenced block to put in the text. */ export function chartBlock(chart) { const json = JSON.stringify({ kind: chart.kind, title: chart.title, ...(chart.unit ? { unit: chart.unit } : {}), ...(chart.source ? { source: chart.source } : {}), series: chart.series, }); return "```" + CHART_FENCE + "\n" + json + "\n```"; } const NUMBER = /[+-]?\d[\d'’,]*(?:\.\d+)?/g; /** Every number written in a text, as numbers ("1,200" and "1’200" are 1200). */ export function numbersInText(text) { return (text.match(NUMBER) ?? []) .map((n) => Number(n.replace(/['’]/g, "").replace(/,(?=\d{3}\b)/g, "").replace(/,/g, ""))) .filter((n) => Number.isFinite(n)); } /** * The values of a chart that do not appear in the text. A chart proposed by a * model must draw only the writer's own numbers: an empty list means it does. */ export function chartValuesNotInText(chart, text) { const present = new Set(numbersInText(text)); const missing = []; for (const s of chart.series) for (const [, y] of s.points) if (y !== null && !present.has(y) && !missing.includes(y)) missing.push(y); return missing; }