Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ Drop the workbook in `data/` named like `Physioshark_Shark Log 2026-2027.xlsx` (
## Charts & design

- Follow the dataviz method: categorical slots in fixed order (`--series-1…8`, validated light and dark), sequential = one hue (`--seq-*`), diverging = blue ↔ red with a neutral midpoint, one y-axis only (never dual axes), legends for ≥ 2 series, text in ink tokens (never the series colour), 4 px rounded bar ends, 2 px lines, hover tooltips, data tables via `ChartCard table`.
- Every chart registers its data with the enclosing `ChartCard` (`registerCsv` in `charts/csv.ts`), which shows **Download CSV**. A new chart component must call `registerCsv` too. An explicit `ChartCard table` takes precedence.
- Species colours come from `src/lib/species.ts` (blacktip = slot 1, sicklefin lemon = slot 2).
- Charts measure their width (`bind:clientWidth`) and carry a `viewBox` so pre-hydration renders scale down instead of overflowing.
- Interactive marks (links) inside an SVG → the SVG gets `role="group"`, not `img` (axe `nested-interactive`). Only put `aria-label` on elements that are links.
Expand Down
53 changes: 52 additions & 1 deletion src/lib/components/ChartCard.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<script lang="ts">
import type { Snippet } from 'svelte';
import { onMount, type Snippet } from 'svelte';
import DataTable, { type Column } from './DataTable.svelte';
import { collectCsv, slug, toCsv, type CsvTable } from './charts/csv';

let {
title,
Expand All @@ -19,6 +20,31 @@
table?: { columns: Column[]; rows: Record<string, unknown>[] };
children: Snippet;
} = $props();

// Charts inside the card register their data; the button needs JS, so it appears on mount.
const sources = collectCsv();
let canDownload = $state(false);
onMount(() => (canDownload = sources.length > 0 || !!table?.rows.length));

function download() {
const tables: CsvTable[] = table?.rows.length
? [
{
columns: table.columns.map((c) => c.label),
rows: table.rows.map((r) =>
table.columns.map((c) => r[c.key] as CsvTable['rows'][0][0])
)
}
]
: sources.map((s) => s());
const url = URL.createObjectURL(new Blob([toCsv(tables)], { type: 'text/csv;charset=utf-8' }));
const a = Object.assign(document.createElement('a'), {
href: url,
download: `physioshark-${slug(title)}.csv`
});
a.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
</script>

<figure class="card chart-card" {id}>
Expand All @@ -34,6 +60,11 @@
<DataTable columns={table.columns} rows={table.rows} max={500} />
</details>
{/if}
{#if canDownload}
<button type="button" class="csv" onclick={download}>
Download CSV<span class="sr"> for {title}</span>
</button>
{/if}
{#if source}<p class="source">Source: {source}</p>{/if}
</figure>

Expand Down Expand Up @@ -73,6 +104,26 @@
margin-top: 10px;
font-size: 0.85rem;
}
.csv {
align-self: flex-start;
margin-top: 8px;
padding: 0;
background: none;
border: 0;
color: var(--accent-ink);
font: inherit;
font-size: 0.8rem;
cursor: pointer;
text-decoration: underline;
text-underline-offset: 2px;
}
.sr {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
}
.tbl summary {
cursor: pointer;
color: var(--accent-ink);
Expand Down
10 changes: 10 additions & 0 deletions src/lib/components/charts/BarChart.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
</script>

<script lang="ts">
import { registerCsv } from './csv';
import { compact } from '#lib/format';
import Legend from './Legend.svelte';
import Tip, { type TipState } from './Tip.svelte';
Expand Down Expand Up @@ -38,6 +39,15 @@
errors?: ([number, number] | null)[];
} = $props();

registerCsv(() => ({
columns: ['category', ...series.map((s) => s.name), ...(errors ? ['ci_low', 'ci_high'] : [])],
rows: categories.map((c, i) => [
c,
...series.map((s) => s.values[i]),
...(errors ? [errors[i]?.[0], errors[i]?.[1]] : [])
])
}));

let width = $state(640);
const h = $derived(height ?? (horizontal ? Math.max(120, categories.length * 26 + 40) : 260));
const longest = $derived(Math.max(0, ...categories.map((c) => c.length)));
Expand Down
15 changes: 15 additions & 0 deletions src/lib/components/charts/BoxPlot.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
</script>

<script lang="ts">
import { registerCsv } from './csv';
import { compact } from '#lib/format';
import Tip, { type TipState } from './Tip.svelte';
import { linear, nice, ticks } from './scale';
Expand All @@ -26,6 +27,20 @@
yFormat = compact
}: { boxes: Box[]; height?: number; yLabel?: string; yFormat?: (v: number) => string } = $props();

registerCsv(() => ({
columns: ['group', 'n', 'low', 'q1', 'median', 'q3', 'high', 'mean'],
rows: boxes.map((b) => [
b.name,
b.stats?.n,
b.stats?.lo,
b.stats?.q1,
b.stats?.median,
b.stats?.q3,
b.stats?.hi,
b.stats?.mean
])
}));

let width = $state(640);
const longest = $derived(Math.max(0, ...boxes.map((b) => b.name.length)));
const band = $derived((width - 64) / Math.max(1, boxes.length));
Expand Down
6 changes: 6 additions & 0 deletions src/lib/components/charts/Heatmap.svelte
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<script lang="ts">
import { registerCsv } from './csv';
import { compact } from '#lib/format';
import Tip, { type TipState } from './Tip.svelte';

Expand All @@ -25,6 +26,11 @@
domain?: [number, number];
} = $props();

registerCsv(() => ({
columns: [yTitle || 'row', ...xLabels],
rows: yLabels.map((y, i) => [y, ...xLabels.map((_, j) => values[i]?.[j])])
}));

let width = $state(640);
const longestY = $derived(Math.max(0, ...yLabels.map((l) => l.length)));
const longestX = $derived(Math.max(0, ...xLabels.map((l) => l.length)));
Expand Down
6 changes: 6 additions & 0 deletions src/lib/components/charts/Histogram.svelte
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<script lang="ts">
import { registerCsv } from './csv';
import { compact } from '#lib/format';
import Legend from './Legend.svelte';
import Tip, { type TipState } from './Tip.svelte';
Expand All @@ -23,6 +24,11 @@
markers?: { x: number; label: string }[];
} = $props();

registerCsv(() => ({
columns: ['bin_start', 'bin_end', ...series.map((s) => s.name)],
rows: edges.slice(0, -1).map((e, i) => [e, edges[i + 1], ...series.map((s) => s.counts[i])])
}));

let width = $state(640);
const m = $derived({
top: markers.length ? 18 : 10,
Expand Down
18 changes: 18 additions & 0 deletions src/lib/components/charts/LineChart.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
</script>

<script lang="ts">
import { isoDay, registerCsv } from './csv';
import { compact } from '#lib/format';
import Legend from './Legend.svelte';
import Tip, { type TipState } from './Tip.svelte';
Expand Down Expand Up @@ -41,6 +42,23 @@
yDomain?: [number, number];
} = $props();

registerCsv(() => ({
columns: [
'series',
xLabel || (xType === 'date' ? 'date' : 'x'),
...(xFormat && xType !== 'date' ? ['x_label'] : []),
yLabel || 'y'
],
rows: series.flatMap((s) =>
s.points.map((p) => [
s.name,
xType === 'date' ? isoDay(p.x) : p.x,
...(xFormat && xType !== 'date' ? [xFormat(p.x)] : []),
p.y
])
)
}));

let width = $state(640);
const m = $derived({ top: 12, right: 16, bottom: xLabel ? 44 : 30, left: 52 });
const fx = $derived(
Expand Down
6 changes: 6 additions & 0 deletions src/lib/components/charts/Polar.svelte
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<script lang="ts">
import { registerCsv } from './csv';
import { compact } from '#lib/format';
import Tip, { type TipState } from './Tip.svelte';

Expand All @@ -17,6 +18,11 @@
startAngle?: number;
} = $props();

registerCsv(() => ({
columns: ['sector', 'value', 'note'],
rows: sectors.map((s) => [s.label, s.value, s.sub])
}));

let width = $state(400);
const size = $derived(Math.min(width, height));
const cx = $derived(width / 2);
Expand Down
6 changes: 6 additions & 0 deletions src/lib/components/charts/Scatter.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
</script>

<script lang="ts">
import { isoDay, registerCsv } from './csv';
import { compact } from '#lib/format';
import Legend from './Legend.svelte';
import Tip, { type TipState } from './Tip.svelte';
Expand Down Expand Up @@ -53,6 +54,11 @@
opacity?: number;
} = $props();

registerCsv(() => ({
columns: [xLabel || (xDate ? 'date' : 'x'), yLabel || 'y', 'group', 'label'],
rows: points.map((p) => [xDate ? isoDay(p.x) : p.x, p.y, p.g, p.label])
}));

let width = $state(640);
const m = $derived({ top: 10, right: 16, bottom: xLabel ? 44 : 28, left: 54 });
const colorOf = $derived(new Map(groups.map((g) => [g.name, g.color])));
Expand Down
8 changes: 8 additions & 0 deletions src/lib/components/charts/Timeline.svelte
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<script lang="ts">
import { isoDay, registerCsv } from './csv';
import Tip, { type TipState } from './Tip.svelte';
import { dateTicks, linear } from './scale';

Expand All @@ -8,6 +9,13 @@
rows: { label: string; items: { start: number; end: number; color?: string; tip: string }[] }[];
} = $props();

registerCsv(() => ({
columns: ['row', 'start', 'end', 'detail'],
rows: rows.flatMap((r) =>
r.items.map((it) => [r.label, isoDay(it.start), isoDay(it.end), it.tip])
)
}));

let width = $state(640);
const longest = $derived(Math.max(0, ...rows.map((r) => r.label.length)));
const m = $derived({ top: 6, right: 14, bottom: 26, left: Math.min(180, 14 + longest * 6.6) });
Expand Down
28 changes: 28 additions & 0 deletions src/lib/components/charts/csv.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { describe, expect, it } from 'vitest';
import { isoDay, slug, toCsv } from './csv';

describe('chart CSV', () => {
it('quotes, blanks missing values and rounds floats', () => {
const csv = toCsv([
{
columns: ['site', 'cpue'],
rows: [
['Haapiti, "old"', 0.1 + 0.2],
['Tiki', null],
['Line\nbreak', Number.NaN]
]
}
]);
expect(csv).toBe('site,cpue\r\n"Haapiti, ""old""",0.3\r\nTiki,\r\n"Line\nbreak",');
});

it('separates several tables and skips empty ones', () => {
const t = { columns: ['a'], rows: [[1]] };
expect(toCsv([t, { columns: ['b'], rows: [] }, t])).toBe('a\r\n1\r\n\r\na\r\n1');
});

it('makes file names and dates', () => {
expect(slug("Catch rate by moon phase (Mo'orea)")).toBe('catch-rate-by-moon-phase-mo-orea');
expect(isoDay(0)).toBe('1970-01-01');
});
});
53 changes: 53 additions & 0 deletions src/lib/components/charts/csv.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* "Download CSV" for every chart (#31). Each chart component registers a function that returns
* its data as a table; the enclosing ChartCard turns the registered tables into a CSV file on
* click. Nothing is computed until someone asks, and no call site has to pass extra props.
*/
import { getContext, setContext } from 'svelte';

export type Cell = string | number | null | undefined;
export interface CsvTable {
columns: string[];
rows: Cell[][];
}
export type CsvSource = () => CsvTable;

const KEY = Symbol('chart-csv');

/** ChartCard: collect the tables of the charts inside it. */
export function collectCsv(): CsvSource[] {
const sources: CsvSource[] = [];
setContext(KEY, (s: CsvSource) => sources.push(s));
return sources;
}

/** Chart components: offer this chart's data to the enclosing ChartCard (if any). */
export function registerCsv(source: CsvSource) {
getContext<((s: CsvSource) => void) | undefined>(KEY)?.(source);
}

const cell = (v: Cell) => {
if (v == null || (typeof v === 'number' && !Number.isFinite(v))) return '';
const s = typeof v === 'number' ? String(Math.round(v * 1e6) / 1e6) : v;
return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
};

/** RFC 4180 CSV; several tables are separated by a blank line. */
export function toCsv(tables: CsvTable[]): string {
return tables
.filter((t) => t.rows.length)
.map((t) => [t.columns, ...t.rows].map((r) => r.map(cell).join(',')).join('\r\n'))
.join('\r\n\r\n');
}

export const slug = (s: string) =>
s
.normalize('NFKD')
.replace(/[̀-ͯ]/g, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 60) || 'chart';

/** Day number (days since 1970-01-01) → ISO date. */
export const isoDay = (d: number) => new Date(d * 86_400_000).toISOString().slice(0, 10);
Loading