From 10868bc762ed2e566538b89d0d580fb6f29c164d Mon Sep 17 00:00:00 2001 From: Peter Bons Date: Wed, 4 Nov 2026 16:49:14 +0100 Subject: [PATCH 1/4] Put the period table last, add How it's measured and the covered period Documents (table, Markdown, HTML) show the overview sections first and the per-session / per-day table at the bottom; CSV keeps it first. Every report names the period its data covers (first to last activity within the filters; coverage in JSON). HTML reports add a How it's measured section describing the data read and how each figure is counted, limited to what the report contains. Co-Authored-By: Claude Opus 5.5 --- README.md | 13 +++- bin/ccreports.mjs | 27 +++++++++ skills/report/SKILL.md | 3 + src/formats.mjs | 22 +++++-- src/method.mjs | 133 +++++++++++++++++++++++++++++++++++++++++ src/report.mjs | 18 ++++-- test/method.test.mjs | 56 +++++++++++++++++ 7 files changed, 261 insertions(+), 11 deletions(-) create mode 100644 src/method.mjs create mode 100644 test/method.test.mjs diff --git a/README.md b/README.md index ce0e8ef..5416ec0 100644 --- a/README.md +++ b/README.md @@ -70,10 +70,21 @@ both, so rows can add up to more than the total. With `--breakdown`, a **Per Session** column gives each tool / skill / command / agent count divided by the row's sessions. -Every period report, `session` included, ends with a **Skills** table: every +Every period report, `session` included, has a **Skills** table: every skill used in the range, by model and by user, with estimated tokens and cost, as in the summary. `--top` limits the breakdown sub-rows, not this list. +In table, Markdown and HTML output the overview comes first: skills, plugins, +usage limits and any `-a` / `-r` sections. The period table itself (*Usage per +session*, *per day*, ...) is at the bottom. CSV keeps the period table first. +Every report names the period its data covers, from the first to the last +activity within the filters, e.g. `Data: 2025-12-06 → 2026-11-04 (334 days)`. +It also appears as `coverage` in JSON. HTML reports add a **How it's measured** +section above the period table. It describes the data read, the period and +time zone, and how sessions, tokens, cost, tools, usage limits, adoption phases, +session intent and recommendations are counted, covering only what the +report contains. + The `session` report names each session by its title (the first 8 characters of its id when it has none), cut to at most 35 characters with `…` in every display format. JSON keeps the full title. diff --git a/bin/ccreports.mjs b/bin/ccreports.mjs index 18cae69..2909ed4 100644 --- a/bin/ccreports.mjs +++ b/bin/ccreports.mjs @@ -9,6 +9,7 @@ import { loadCursorRecords, defaultCursorDirs } from '../src/cursor.mjs'; import { defaultCursorUserDirs } from '../src/cursor-state.mjs'; import { aggregate, parseDateArg, toJSON, REPORTS } from '../src/aggregate.mjs'; import { buildPeriodReport, buildSummary } from '../src/report.mjs'; +import { coverage, methodSection } from '../src/method.mjs'; import { FORMATS, toTerminal, toMarkdown, toCsv, toHtml } from '../src/formats.mjs'; import { loadPricingTable, createPricer } from '../src/pricing.mjs'; import { buildAdoption, buildIntents, parseIntents, PHASES, AUTONOMY_THRESHOLD } from '../src/adoption.mjs'; @@ -284,9 +285,13 @@ const usageLimits = ['adoption', 'recommendations'].includes(report) ? null : limitStats(data, { since, until, project: opts.project, timeZone: opts.timezone }); +// The period the data covers: first to last activity within the filters. +const range = coverage(result.totals, { timeZone: opts.timezone }); + let output; if (format === 'json') { const meta = { report, source, since, until, pricingSource, ccreportsVersion: VERSION }; + if (range) meta.coverage = { from: range.from, to: range.to, days: range.days }; const adoptionJson = adoption && { summary: adoption.summary, phases: PHASES, @@ -332,6 +337,28 @@ if (format === 'json') { if (!part || part === doc) continue; doc = { ...doc, summary: [...(doc.summary ?? []), ...part.summary], sections: [...doc.sections, ...part.sections] }; } + // A page to read: how it is measured, then the period table (per session, + // day, ...) at the bottom, below the overview sections. + const tail = []; + if (format === 'html') { + const has = { + claude: !!claudeData?.files, + copilot: !!copilotData?.files, + cursor: !!cursorData?.files, + cost: showCost, + breakdown: report === 'summary' || !!opts.breakdown, + shell: opts.shell, + adoption: !!adoption, + intentsByClaude: !!intents, + recommendations: !!advice, + }; + tail.push(methodSection(has, { since, until, project: opts.project, timeZone: opts.timezone, pricingSource, range })); + } + doc = { + ...doc, + coverage: range, + sections: [...doc.sections.filter((s) => !s.main), ...tail, ...doc.sections.filter((s) => s.main)], + }; output = { table: () => toTerminal(doc, { color: toTTY && !opts['no-color'] && !process.env.NO_COLOR, version: VERSION }) + '\n', markdown: () => toMarkdown(doc, { version: VERSION }), diff --git a/skills/report/SKILL.md b/skills/report/SKILL.md index 0f2b228..d8bfec6 100644 --- a/skills/report/SKILL.md +++ b/skills/report/SKILL.md @@ -50,6 +50,9 @@ Useful options: `-s/--since` and `-u/--until` (`YYYYMMDD`), `-p/--project - For a page to view or share, write HTML to a file in the current working directory unless the user names another place, e.g. `-f html -o ccreports-adoption.html`, then give the user the full path. + HTML reports list the overview first, then a *How it's measured* section + and the period table (per session, day, ...) at the bottom; the header + names the period the data covers. When they ask to see or open it, add `--open`: the CLI launches the file in its associated app (browser for HTML, Excel for CSV). From your shell it does not open files unless `--open` is passed. diff --git a/src/formats.mjs b/src/formats.mjs index 7f2468d..86bae7d 100644 --- a/src/formats.mjs +++ b/src/formats.mjs @@ -81,10 +81,13 @@ function terminalTable({ columns, rows }, c) { export function toTerminal(doc, { color = false, version } = {}) { const c = paint(color); const out = [c.bold(doc.title)]; + if (doc.coverage) out.push(c.dim(`Data: ${doc.coverage.text}`)); if (doc.summary?.length) out.push(...doc.summary.map((l) => `• ${l}`), ''); doc.sections.forEach((s, i) => { if (s.title) out.push((i > 0 ? '\n' : '') + c.bold(s.title) + (s.note ? c.dim(` (${s.note})`) : '')); - if (s.items) { + if (s.notes) { + for (const note of s.notes) out.push('', `${c.bold(note.term)}: ${note.text}`); + } else if (s.items) { s.items.forEach((item, n) => { out.push('', `${n + 1}. ${c.bold(item.title)} ${c.dim(`[${itemImpact(item)}]`)}`); out.push(` ${c.dim('Evidence:')} ${item.evidence}`, ` ${c.cyan('→')} ${item.advice}`); @@ -118,10 +121,15 @@ const mdEscape = (s) => s.replace(/\\/g, '\\\\').replace(/\|/g, '\\|').replace(/ export function toMarkdown(doc, { version } = {}) { const out = [`# ${doc.title}`]; + if (doc.coverage) out.push('', `_Data: ${doc.coverage.text}_`); if (doc.summary?.length) out.push('', ...doc.summary.map((l) => `- ${l}`)); for (const s of doc.sections) { out.push(''); if (s.title) out.push(`## ${s.title}${s.note ? ` _(${s.note})_` : ''}`, ''); + if (s.notes) { + for (const note of s.notes) out.push(`- **${note.term}:** ${note.text}`); + continue; + } if (s.items) { s.items.forEach((item, n) => { out.push(`### ${n + 1}. ${item.title}`, '', `_${itemImpact(item)}_`, '', `**Evidence:** ${item.evidence}`, '', `**Do:** ${item.advice}`, ''); @@ -154,7 +162,7 @@ const csvField = (s) => (/[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s); */ export function toCsv(doc) { return ( - doc.sections + [...doc.sections.filter((s) => s.main), ...doc.sections.filter((s) => !s.main && !s.notes)] .map((section) => { const s = section.items ? itemsTable(section.items) : section; const lines = [s.columns.map((col) => csvField(col.title)).join(',')]; @@ -257,6 +265,8 @@ export function toHtml(doc, { generatedAt = new Date(), pricingSource, version, const sections = doc.sections .map((s) => { const heading = s.title ? `

${esc(s.title)}${s.note ? ` ${esc(s.note)}` : ''}

` : ''; + if (s.notes) return `
${heading} +
${s.notes.map((n) => `
${esc(n.term)}
${escCode(n.text)}
`).join('')}
`; if (s.items) return `
${heading}\n${htmlItems(s.items)}
`; return s.cards ? `
${heading}\n${htmlCards(s)}
` : `
${heading}\n${htmlTable(s)}
`; }) @@ -281,7 +291,7 @@ body { margin:0; background:var(--bg); color:var(--fg); font:14px/1.45 system-ui /* The page grows to its widest table: one horizontal scrollbar for the page, not one per table. */ main { padding:24px 16px 48px; width:fit-content; min-width:100%; } /* Text stays at window width when the page is wider. */ -.meta, .summary, section.plain { max-width:calc(100vw - 32px); } +.meta, .summary, section.plain, section.method { max-width:calc(100vw - 32px); } h1 { font-size:22px; margin:0 0 4px; } .meta { color:var(--muted); margin:0 0 20px; } section { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:14px 16px; margin:0 0 16px; } @@ -290,6 +300,10 @@ h2 { font-size:15px; margin:0 0 10px; } .summary { background:var(--card); border:1px solid var(--line); border-left:3px solid var(--accent); border-radius:10px; margin:0 0 16px; padding:12px 16px 12px 34px; } .summary li { margin:3px 0; } section.plain { background:none; border:0; padding:0; } +.meta strong { color:var(--fg); font-weight:600; } +section.method dl { display:grid; grid-template-columns:minmax(140px, max-content) 1fr; gap:8px 16px; margin:0; } +section.method dt { font-weight:600; } section.method dd { margin:0; color:var(--muted); } +@media (max-width:640px) { section.method dl { grid-template-columns:1fr; gap:2px; } section.method dd { margin-bottom:8px; } } .recs { list-style:none; margin:0; padding:0; display:grid; gap:10px; } .rec { background:var(--card); border:1px solid var(--line); border-left:4px solid var(--muted); border-radius:10px; padding:12px 16px; } .rec.high { border-left-color:#dc2626; } .rec.medium { border-left-color:#d97706; } .rec.low { border-left-color:var(--accent); } @@ -334,7 +348,7 @@ tbody tr:not(.total):hover td { background-color:var(--bar); }

${esc(doc.title)}

-

${esc(meta.join(' · '))}

+

${doc.coverage ? `Data: ${esc(doc.coverage.text)} · ` : ''}${esc(meta.join(' · '))}

${summary}${sections}
diff --git a/src/report.mjs b/src/report.mjs index b6df5f6..d34b439 100644 --- a/src/report.mjs +++ b/src/report.mjs @@ -222,6 +222,9 @@ function estimateCells(usage, totals, opts) { ]; } +// Rows a long HTML table shows before "Show all". +const FOLD_ROWS = 15; + /** Every skill used, by who invoked it; `top` > 0 keeps the first rows. */ function skillSection(totals, opts, top = 0) { const entries = ranked(totals.skills, (s) => s.model + s.user); @@ -229,6 +232,8 @@ function skillSection(totals, opts, top = 0) { const shown = top > 0 ? entries.slice(0, top) : entries; return { title: 'Skills', + // HTML shows the first rows and a button for the rest. + fold: top > 0 ? undefined : FOLD_ROWS, note: shown.length < entries.length ? `top ${shown.length} of ${entries.length}` : undefined, columns: [left('Skill'), right('By model'), right('By user'), right('Total'), ...estimateColumns(opts)], rows: shown.map(([name, s]) => ({ diff --git a/test/adoption.test.mjs b/test/adoption.test.mjs index aac8441..6dad49c 100644 --- a/test/adoption.test.mjs +++ b/test/adoption.test.mjs @@ -73,7 +73,8 @@ test('buildAdoption: cohorts, weekly mix, capabilities, surfaces and summary', ( assert.equal(cohorts.cards, true); const agentRow = cohorts.rows[2].cells; assert.equal(agentRow[0], 'Phase 2 · Agent-first'); - assert.deepEqual(agentRow[2], { kind: 'avg', v: 2 }); // PRs per session + assert.deepEqual(agentRow[2], { kind: 'pct', v: 0.25 }); // headline: share of sessions + assert.deepEqual(agentRow[cohorts.columns.findIndex((c) => c.title === 'PRs per session')], { kind: 'avg', v: 2 }); assert.equal(agentRow[3], 1); // sessions assert.deepEqual(agentRow[cohorts.columns.findIndex((c) => c.title === 'Plan mode')], { kind: 'pct', v: 1 }); assert.deepEqual(weekly.rows.map((r) => r.cells[0]), ['2026-09-28']); // Oct 1-4, 2026 is Thu-Sun of one week diff --git a/test/method.test.mjs b/test/method.test.mjs index 09cead6..2147858 100644 --- a/test/method.test.mjs +++ b/test/method.test.mjs @@ -47,10 +47,35 @@ test('documents render the notes and the covered period; CSV keeps the period ta }; const html = toHtml(doc); assert.match(html, /Data: 2026-10-01 → 2026-10-30 \(30 days\)<\/strong>/); - assert.match(html, /

How it's measured<\/h2>\n
Data<\/dt>
local logs<\/code><\/dd><\/dl>/); + assert.match(html, /

How it's measured<\/h2><\/summary>\n
Data<\/dt>
local logs<\/code><\/dd><\/dl>/); assert.ok(html.indexOf('Skills') < html.indexOf('How it's measured') && html.indexOf('How it's measured') < html.indexOf('Usage per session')); const md = toMarkdown(doc); + assert.doesNotMatch(md, /
/); assert.match(md, /_Data: 2026-10-01 → 2026-10-30 \(30 days\)_/); assert.match(md, /- \*\*Data:\*\* local `logs`/); assert.equal(toCsv(doc), 'Session\ns1\n\nSkill\nplan\n'); }); + +test('HTML folds long tables and minor recommendations', () => { + const rows = Array.from({ length: 20 }, (_, i) => ({ cells: [`s${i}`] })); + const html = toHtml({ title: 'x', sections: [{ title: 'Skills', fold: 15, columns: [{ title: 'Skill' }], rows }] }); + assert.equal((html.match(//g) ?? []).length, 5); + assert.match(html, //); + assert.match(html, /data-fold-toggle[^>]*>Show all 20 ({ title, impact, atStakeUSD, evidence: 'e', advice: 'a' }); + const recs = toHtml({ + title: 'x', + sections: [{ title: 'R', items: [item('Big', 'high', 400), item('Cheap', 'medium', 0.2), item('Small', 'low')] }], + }); + const [open, more] = recs.split('
'); + assert.match(open, /Big/); + assert.doesNotMatch(open, /Cheap|Small/); + assert.match(more, /^2 more, with less at stake<\/summary>
    .*Cheap.*Small/s); + // Only minor items: the first stays open. + const onlyLow = toHtml({ title: 'x', sections: [{ title: 'R', items: [item('Small', 'low')] }] }); + assert.doesNotMatch(onlyLow, /
    Date: Thu, 5 Nov 2026 14:18:57 +0100 Subject: [PATCH 4/4] HTML: headline figures, contents, per-table scrolling, stacked phase mix; intent and phase per session - Sections keep to the window width; only a table wider than its section scrolls. - Headline figures (sessions, prompts, tool calls, PRs, tokens, cost) under the title, as tiles in HTML and a line in Markdown and table output. - HTML: a row of links to every section. - Phase mix per week: the phase shares as one stacked bar with a legend; weeks with fewer than 3 sessions dimmed. - Session report: Intent, Phase and Prompts per session; HTML and Markdown list the newest session first unless --order is given. Co-Authored-By: Claude Opus 5.5 --- README.md | 12 ++++- bin/ccreports.mjs | 32 ++++++++++++- src/adoption.mjs | 6 ++- src/formats.mjs | 103 ++++++++++++++++++++++++++++++++++++---- src/report.mjs | 21 +++++++- test/ccreports.test.mjs | 11 +++++ test/method.test.mjs | 34 ++++++++++++- 7 files changed, 202 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 449d440..cb9a397 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,12 @@ usage limits and any `-a` / `-r` sections. The period table itself (*Usage per session*, *per day*, ...) is at the bottom. CSV keeps the period table first. Every report names the period its data covers, from the first to the last activity within the filters, e.g. `Data: 2025-12-06 → 2026-11-04 (334 days)`. -It also appears as `coverage` in JSON. HTML reports add a **How it's measured** +It also appears as `coverage` in JSON. Below it are the headline figures: +sessions, prompts, tool calls, pull requests, tokens and estimated cost. In +HTML these are tiles, followed by a row of links to every section. Each table +keeps to the window width and scrolls sideways on its own. *Phase mix per +week* draws the phase shares as one stacked bar, and weeks with fewer than 3 +sessions are dimmed. HTML reports add a **How it's measured** section above the period table. It describes the data read, the period and time zone, and how sessions, tokens, cost, tools, usage limits, adoption phases, session intent and recommendations are counted, covering only what the @@ -91,7 +96,10 @@ CSV output keep everything open. The `session` report names each session by its title (the first 8 characters of its id when it has none), cut to at most 35 characters with `…` in every -display format. JSON keeps the full title. With `--source all` a **Tool** +display format. JSON keeps the full title. Each session's **Intent**, +**Phase** (as in the adoption report) and **Prompts** follow *Last Activity*. +HTML and Markdown list the newest session first, and `--order asc|desc` +overrides that. With `--source all` a **Tool** column names the AI tool each session ran in (Claude Code, GitHub Copilot or Cursor); JSON rows always have it as `tool`. diff --git a/bin/ccreports.mjs b/bin/ccreports.mjs index 06cf3c0..d1fe28a 100644 --- a/bin/ccreports.mjs +++ b/bin/ccreports.mjs @@ -12,7 +12,7 @@ import { buildPeriodReport, buildSummary } from '../src/report.mjs'; import { coverage, methodSection } from '../src/method.mjs'; import { FORMATS, toTerminal, toMarkdown, toCsv, toHtml } from '../src/formats.mjs'; import { loadPricingTable, createPricer } from '../src/pricing.mjs'; -import { buildAdoption, buildIntents, parseIntents, PHASES, AUTONOMY_THRESHOLD } from '../src/adoption.mjs'; +import { buildAdoption, buildIntents, parseIntents, sessionStats, PHASES, AUTONOMY_THRESHOLD } from '../src/adoption.mjs'; import { INTENTS } from '../src/intent.mjs'; import { buildRecommendations } from '../src/recommendations.mjs'; import { openFile, FORMAT_EXTENSIONS } from '../src/open.mjs'; @@ -215,7 +215,9 @@ if (showCost) { } const result = aggregate(data, { report, since, until, project: opts.project, timeZone: opts.timezone, pricer }); -if (opts.order === 'desc') result.buckets.reverse(); +// Documents read top-down list the newest session first; --order overrides. +const newestFirst = !opts.order && report === 'session' && ['html', 'markdown'].includes(format); +if (opts.order === 'desc' || newestFirst) result.buckets.reverse(); // Warnings go to stderr so redirected output stays clean. if (showCost) { @@ -290,6 +292,18 @@ const usageLimits = ['adoption', 'recommendations'].includes(report) // The period the data covers: first to last activity within the filters. const range = coverage(result.totals, { timeZone: opts.timezone }); +// Per-session phase, intent, prompts and PRs (the adoption assessment's stats): +// columns of the session table and figures in the headline. +const documentFormat = ['table', 'markdown', 'html'].includes(format); +const perSession = adoption?.stats ?? (documentFormat && result.totals.sessions.size ? sessionStats(data, docOpts) : null); +if (perSession && report === 'session') { + const phaseTitle = Object.fromEntries(PHASES.map((p) => [p.key, p.title.replace(/^Phase \d · /, '')])); + const intentTitle = Object.fromEntries(INTENTS.map((i) => [i.key, i.title])); + docOpts.sessionInfo = new Map( + perSession.map((s) => [s.id, { phase: phaseTitle[s.phase] ?? '', intent: intentTitle[s.intent] ?? '', prompts: s.prompts }]), + ); +} + let output; if (format === 'json') { const meta = { report, source, since, until, pricingSource, ccreportsVersion: VERSION }; @@ -358,6 +372,7 @@ if (format === 'json') { } doc = { ...doc, + kpis: headline(result.totals, perSession, { showCost, tokens: data.usage.length > 0 }), coverage: range, sections: [...doc.sections.filter((s) => !s.main), ...tail, ...doc.sections.filter((s) => s.main)], }; @@ -390,3 +405,16 @@ if (file) { } else { process.stdout.write(output); } + +/** The headline figures: sessions, prompts, tool calls, PRs, tokens and cost. */ +function headline(totals, perSession, { showCost, tokens }) { + const sum = (f) => perSession.reduce((n, s) => n + f(s), 0); + return [ + { label: 'sessions', value: totals.sessions.size }, + ...(perSession ? [{ label: 'prompts', value: sum((s) => s.prompts) }] : []), + { label: 'tool calls', value: totals.toolCalls }, + ...(perSession ? [{ label: 'pull requests', value: sum((s) => s.prs) }] : []), + ...(tokens ? [{ label: 'tokens', value: totals.totalTokens, compact: true }] : []), + ...(showCost ? [{ label: 'estimated cost', value: totals.costUSD, usd: true }] : []), + ]; +} diff --git a/src/adoption.mjs b/src/adoption.mjs index ad01826..2325313 100644 --- a/src/adoption.mjs +++ b/src/adoption.mjs @@ -272,6 +272,8 @@ export function buildAdoption(data, opts) { } const weeks = [...weekMap.values()].sort((a, b) => (a.key < b.key ? -1 : 1)); const weekRows = weeks.map((w) => ({ + // Weeks with only a session or two swing between 0% and 100%. + muted: w.total < 3, cells: [ w.key, w.total, @@ -327,7 +329,9 @@ export function buildAdoption(data, opts) { { title: 'Adoption cohorts', note: `sessions by how they used ${opts.product ?? 'Claude Code'}`, cards: true, columns: cohortColumns, rows: cohortRows }, { title: 'Phase mix per week', - note: 'by the week a session started', + note: 'by the week a session started; weeks with fewer than 3 sessions are dimmed', + // HTML draws the phase shares as one stacked bar. + stack: { start: 2, count: PHASES.length, title: 'Phase mix' }, columns: [ left('Week'), right('Sessions'), diff --git a/src/formats.mjs b/src/formats.mjs index d04d9ab..1d08a9f 100644 --- a/src/formats.mjs +++ b/src/formats.mjs @@ -23,6 +23,8 @@ function cellText(cell, { csv = false } = {}) { if (cell.v == null) return csv ? '' : '-'; return csv ? (cell.v * 100).toFixed(2) : `${(cell.v * 100).toFixed(1)}%`; } + // Shares drawn as one stacked bar (HTML); as text: "Chat 40.0% · Assisted 20.0%". + if (cell.kind === 'stack') return cell.parts.map((p) => `${p.label} ${cellText({ kind: 'pct', v: p.v })}`).join(' · '); return String(cell); } @@ -82,6 +84,7 @@ export function toTerminal(doc, { color = false, version } = {}) { const c = paint(color); const out = [c.bold(doc.title)]; if (doc.coverage) out.push(c.dim(`Data: ${doc.coverage.text}`)); + if (doc.kpis?.length) out.push(doc.kpis.map((k) => `${c.bold(kpiValue(k))} ${k.label}`).join(' · ')); if (doc.summary?.length) out.push(...doc.summary.map((l) => `• ${l}`), ''); doc.sections.forEach((s, i) => { if (s.title) out.push((i > 0 ? '\n' : '') + c.bold(s.title) + (s.note ? c.dim(` (${s.note})`) : '')); @@ -122,6 +125,7 @@ const mdEscape = (s) => s.replace(/\\/g, '\\\\').replace(/\|/g, '\\|').replace(/ export function toMarkdown(doc, { version } = {}) { const out = [`# ${doc.title}`]; if (doc.coverage) out.push('', `_Data: ${doc.coverage.text}_`); + if (doc.kpis?.length) out.push('', doc.kpis.map((k) => `**${kpiValue(k)}** ${k.label}`).join(' · ')); if (doc.summary?.length) out.push('', ...doc.summary.map((l) => `- ${l}`)); for (const s of doc.sections) { out.push(''); @@ -215,6 +219,12 @@ function htmlTable({ columns, rows, fold }) { ? '' : ''; // Clipped paths show in full on hover. + if (cell?.kind === 'stack') { + const segs = cell.parts + .map((p, n) => (p.v ? `` : '')) + .join(''); + return `
`; + } const text = cellText(cell); const shown = clipStart(text, col, r); if (shown !== text) attrs.push(`title="${esc(text)}"`); @@ -222,7 +232,8 @@ function htmlTable({ columns, rows, fold }) { }) .join(''); const rowAttrs = []; - if (r.style) rowAttrs.push(`class="${r.style}"`); + const rowClasses = [r.style, r.muted && 'muted'].filter(Boolean); + if (rowClasses.length) rowAttrs.push(`class="${rowClasses.join(' ')}"`); if (folded && r.style !== 'total' && ++shownRows > fold) rowAttrs.push('hidden'); if (isSub) rowAttrs.push(`data-parent="${group}" hidden`); if (hasChildren) rowAttrs.push(`data-group="${group}"`); @@ -275,26 +286,86 @@ function htmlCards({ columns, rows }) { return `
${cards.join('\n')}
`; } +const slug = (s) => + s + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, ''); + +/** A headline figure: 1,234 · $56.78 · 1.2B tokens. */ +export function kpiValue({ value, usd, compact }) { + if (usd) return cellText({ kind: 'usd', v: value }); + if (compact) { + for (const [n, unit] of [[1e9, 'B'], [1e6, 'M'], [1e3, 'k']]) { + if (value >= n) return `${(value / n).toLocaleString('en-US', { maximumFractionDigits: value >= n * 100 ? 0 : 1 })}${unit}`; + } + } + return value.toLocaleString('en-US'); +} + +/** + * A section whose columns start..start+count are shares of one whole (phases + * per week): those columns become one stacked bar, with a legend. + */ +function stackSection(s) { + const { start, count, title } = s.stack; + const labels = s.columns.slice(start, start + count).map((c) => c.title.replace(/^Phase \d · /, '')); + return { + ...s, + legend: labels, + columns: [...s.columns.slice(0, start), { title, align: 'left' }, ...s.columns.slice(start + count)], + rows: s.rows.map((r) => ({ + ...r, + cells: [ + ...r.cells.slice(0, start), + { kind: 'stack', parts: r.cells.slice(start, start + count).map((c, i) => ({ label: labels[i], v: c?.v ?? 0 })) }, + ...r.cells.slice(start + count), + ], + })), + }; +} + export function toHtml(doc, { generatedAt = new Date(), pricingSource, version, copilot = false } = {}) { const meta = [`Generated ${generatedAt.toLocaleString('sv-SE').slice(0, 16)}${version ? ` with ccreports ${version}` : ''}`]; if (copilot) meta.push('GitHub Copilot cost from its billed AI credits'); if (pricingSource) { meta.push(`${copilot ? 'other ' : ''}cost estimates at ${pricingSource === 'builtin' ? 'built-in ' : ''}Claude API list prices`); } + // Section ids for the table of contents. + const ids = new Map(); + const idOf = (s, n) => { + if (!ids.has(s)) ids.set(s, `s${n + 1}-${slug(s.title ?? '')}`); + return ids.get(s); + }; + const toc = + doc.sections.filter((s) => s.title).length > 3 + ? `\n` + : ''; const sections = doc.sections - .map((s) => { - const heading = s.title ? `

${esc(s.title)}${s.note ? ` ${esc(s.note)}` : ''}

` : ''; + .map((section, n) => { + const s = section.stack ? stackSection(section) : section; + const id = idOf(section, n); + const heading = s.title ? `

${esc(s.title)}${s.note ? ` ${esc(s.note)}` : ''}

` : ''; // Reference material: collapsed, the heading opens it. if (s.notes) return `
${heading}
${s.notes.map((n) => `
${esc(n.term)}
${escCode(n.text)}
`).join('')}
`; if (s.items) return `
${heading}\n${htmlItems(s.items)}
`; - return s.cards ? `
${heading}\n${htmlCards(s)}
` : `
${heading}\n${htmlTable(s)}
`; + if (s.cards) return `
${heading}\n${htmlCards(s)}
`; + const legend = s.legend + ? `
${s.legend.map((label, i) => `${esc(label)}`).join('')}
\n` + : ''; + return `
${heading}\n${legend}${htmlTable(s)}
`; }) .join('\n'); const summary = doc.summary?.length ? `
    ${doc.summary.map((l) => `
  • ${esc(l)}
  • `).join('')}
\n` : ''; + const kpis = doc.kpis?.length + ? `
${doc.kpis.map((k) => `
${esc(kpiValue(k))}${esc(k.label)}
`).join('')}
\n` + : ''; return ` @@ -309,10 +380,24 @@ export function toHtml(doc, { generatedAt = new Date(), pricingSource, version, } * { box-sizing:border-box; } body { margin:0; background:var(--bg); color:var(--fg); font:14px/1.45 system-ui,-apple-system,"Segoe UI",sans-serif; } -/* The page grows to its widest table: one horizontal scrollbar for the page, not one per table. */ -main { padding:24px 16px 48px; width:fit-content; min-width:100%; } -/* Text stays at window width when the page is wider. */ -.meta, .summary, section.plain, section.method { max-width:calc(100vw - 32px); } +/* Sections keep to the window; a table wider than its section scrolls on its own. */ +main { padding:24px 16px 48px; max-width:100%; } +.scroll { overflow-x:auto; } +.kpis { display:flex; flex-wrap:wrap; gap:10px; margin:0 0 16px; } +.kpi { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:10px 16px; min-width:120px; } +.kpi b { display:block; font-size:22px; font-variant-numeric:tabular-nums; } +.kpi span { color:var(--muted); font-size:13px; } +.toc { display:flex; flex-wrap:wrap; gap:6px; margin:0 0 16px; } +.toc a { font-size:13px; color:var(--fg); text-decoration:none; border:1px solid var(--line); border-radius:999px; padding:2px 10px; background:var(--card); } +.toc a:hover { border-color:var(--accent); color:var(--accent); } +h2[id] { scroll-margin-top:12px; } +:root { --seg0:#9ca3af; --seg1:#93c5fd; --seg2:#3b82f6; --seg3:#7c3aed; } +.seg0 { background:var(--seg0); } .seg1 { background:var(--seg1); } .seg2 { background:var(--seg2); } .seg3 { background:var(--seg3); } +.stackcell { min-width:260px; width:40%; } +.stack { display:flex; height:14px; border-radius:4px; overflow:hidden; background:var(--line); } +.legend { display:flex; flex-wrap:wrap; gap:14px; margin:0 0 8px; font-size:13px; color:var(--muted); } +.legend i { display:inline-block; width:10px; height:10px; border-radius:2px; margin-right:6px; vertical-align:-1px; } +tr.muted td { opacity:.5; } h1 { font-size:22px; margin:0 0 4px; } .meta { color:var(--muted); margin:0 0 20px; } section { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:14px 16px; margin:0 0 16px; } @@ -377,7 +462,7 @@ tbody tr:not(.total):hover td { background-color:var(--bar); }

${esc(doc.title)}

${doc.coverage ? `Data: ${esc(doc.coverage.text)} · ` : ''}${esc(meta.join(' · '))}

-${summary}${sections} +${kpis}${summary}${toc}${sections}
${segs}