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
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ Drop the workbook in `data/` named like `Physioshark_Shark Log 2026-2027.xlsx` (
- Cite the study behind a chart with `<ChartCard papers={['debaere2024lunar']}>` (ids in `src/lib/publications.ts`). Link only papers that analysed the same question with this dataset; check the abstract first. PDFs are served at `rummerlab.com/papers/<file>` (metadata in the rummerlab-website repo, `data/papers.json`).
- 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.
- Keyboard (#32): every chart spreads `markKeys()` from `charts/marks.ts` onto its svg (one tab stop, `role="application"` while it has marks, arrows/Home/End/Enter/Escape) and puts `data-mark={i}` on each mark's hover element so `markAt` can pin the tooltip there. Pointer handlers use `pointerIn(e)`. A new chart needs both, plus `KEYS_HINT` in its `aria-label`. Only put `aria-label` on elements that are links (e.g. linked scatter points).
- Page weight (#76): markup, not data, made pages heavy. Scatter sends one path of dots per colour above 250 points and swaps in circles after mount, hover picks the nearest point, coordinates are rounded to 0.1 px. Keep per-mark attributes off big charts; put shared ones on a parent `<g>`. `hooks.server.ts` Brotli/gzips HTML and JSON and sets a weak ETag (build version + import hash) so revalidation is a 304 without a render.
- Style guide: `docs/dev/BRANDING.md`.

## Docker / release
Expand Down
27 changes: 26 additions & 1 deletion e2e/pages.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ for (const theme of ['light', 'dark'] as const) {
'/sharks',
'/findings',
'/crew',
'/about'
'/about',
'/morphometrics',
'/pressure'
]) {
await page.goto(route);
for (const v of await axe(page))
Expand All @@ -70,3 +72,26 @@ test('nursery links open a profile and the menu works on mobile', async ({ page
);
expect(overflow).toBeLessThanOrEqual(1);
});

test('charts can be read with the keyboard (#32)', async ({ page }) => {
await page.goto('/morphometrics');
for (const chart of await page.locator('svg.chart-svg[role="application"]').all()) {
await chart.focus();
await page.keyboard.press('ArrowRight');
const tip = chart.locator('xpath=..').locator('.tip');
await expect(tip).toBeVisible();
await page.keyboard.press('End');
await expect(tip).toBeVisible();
await page.keyboard.press('Escape');
await expect(tip).toBeHidden();
}
});

test('pages are compressed and revalidate with a 304 (#76)', async ({ request }) => {
const res = await request.get('/morphometrics', { headers: { 'accept-encoding': 'gzip' } });
expect(res.headers()['content-encoding']).toBe('gzip');
const etag = res.headers()['etag'];
expect(etag).toBeTruthy();
const again = await request.get('/morphometrics', { headers: { 'if-none-match': etag } });
expect(again.status()).toBe(304);
});
18 changes: 18 additions & 0 deletions src/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -363,3 +363,21 @@ select {
max-width: 100%;
height: auto;
}

/* Keyboard-readable charts (#32): the outline sits outside the axes. */
.chart-svg:focus-visible {
outline-offset: 4px;
border-radius: 4px;
}

/* Reduced motion (#32): no transitions or smooth scrolling. */
@media (prefers-reduced-motion: reduce) {
*,
::before,
::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
46 changes: 42 additions & 4 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { building } from '$app/env';
import { building, version } from '$app/env';
import type { Handle, ServerInit } from '@sveltejs/kit/hooks';
import { brotliCompressSync, constants, gzipSync } from 'node:zlib';
import { refresh } from '#lib/server/db';

// Build (or validate) the derived database before the first request.
Expand All @@ -19,16 +20,53 @@ const SECURITY_HEADERS: Record<string, string> = {
'Permissions-Policy': 'camera=(), microphone=(), geolocation=()'
};

const COMPRESSIBLE = /^(text\/|application\/json)/;

/**
* Compress rendered pages and data (#76): adapter-node only precompresses static assets, and a
* scatter-heavy page is several hundred KB of HTML that shrinks about tenfold.
*/
async function compress(req: Request, res: Response): Promise<Response> {
const accept = req.headers.get('accept-encoding') ?? '';
const enc = /\bbr\b/.test(accept) ? 'br' : /\bgzip\b/.test(accept) ? 'gzip' : null;
const type = res.headers.get('content-type') ?? '';
if (!enc || !res.body || res.headers.has('content-encoding') || !COMPRESSIBLE.test(type))
return res;
const raw = Buffer.from(await res.arrayBuffer());
const body =
enc === 'br'
? brotliCompressSync(raw, { params: { [constants.BROTLI_PARAM_QUALITY]: 5 } })
: gzipSync(raw, { level: 6 });
const headers = new Headers(res.headers);
headers.set('content-encoding', enc);
headers.set('content-length', String(body.length));
headers.append('vary', 'Accept-Encoding');
return new Response(body, { status: res.status, statusText: res.statusText, headers });
}

export const handle: Handle = async ({ event, resolve }) => {
const { pathname } = event.url;
// At most once a minute: re-import if a spreadsheet was added or changed (#8).
if (!building && event.url.pathname !== '/health') {
let hash: string | null = null;
if (!building && pathname !== '/health') {
try {
refresh();
hash = refresh().hash;
} catch (err) {
console.error('[import] refresh failed:', err);
}
}
const res = await resolve(event);
// Pages are a function of the build and the imported data only, so one validator covers
// both (#76): a browser revalidating an unchanged page gets a 304 without a render.
const etag =
hash && event.request.method === 'GET' ? `W/"${version}-${hash.slice(0, 16)}"` : null;
if (etag && event.request.headers.get('if-none-match') === etag)
return new Response(null, { status: 304, headers: { etag, 'cache-control': 'no-cache' } });
let res = await resolve(event);
if (etag && res.status === 200 && !res.headers.has('cache-control')) {
res.headers.set('etag', etag);
res.headers.set('cache-control', 'no-cache');
}
if (event.request.method !== 'HEAD') res = await compress(event.request, res);
for (const [k, v] of Object.entries(SECURITY_HEADERS)) res.headers.set(k, v);
return res;
};
10 changes: 9 additions & 1 deletion src/lib/components/InteractiveMap.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,15 @@
ready = true;
await tick();
if (!el || cancelled) return;
map = L.map(el, { scrollWheelZoom: false, zoomSnap: 0.5 });
// Reduced motion (#32): jump instead of animating zooms and fades.
const still = matchMedia('(prefers-reduced-motion: reduce)').matches;
map = L.map(el, {
scrollWheelZoom: false,
zoomSnap: 0.5,
zoomAnimation: !still,
fadeAnimation: !still,
markerZoomAnimation: !still
});
const bases = Object.fromEntries(
BASEMAPS.map((b) => [
b.name,
Expand Down
22 changes: 15 additions & 7 deletions src/lib/components/charts/BarChart.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import { compact } from '#lib/format';
import Legend from './Legend.svelte';
import Tip, { type TipState } from './Tip.svelte';
import { KEYS_HINT, markAt, markKeys, pointerIn } from './marks';
import { barPath, hbarPath, linear, nice, ticks } from './scale';

let {
Expand Down Expand Up @@ -93,11 +94,9 @@
const rotate = $derived(!horizontal && band < longest * 6.5 + 6);

let tip = $state<TipState | null>(null);
function show(e: PointerEvent, i: number) {
const wrap = (e.currentTarget as Element).closest('.wrap')!.getBoundingClientRect();
function show(at: { x: number; y: number }, i: number) {
tip = {
x: e.clientX - wrap.left,
y: e.clientY - wrap.top,
...at,
title: categories[i],
lines: series
.map((s) => ({
Expand All @@ -118,17 +117,25 @@
)
};
}
let svg = $state<SVGSVGElement>();
const keys = markKeys({
count: () => categories.length,
show: (i) => markAt(svg, i, (p) => show(p, i)),
hide: () => (tip = null),
href: (i) => hrefs?.[i]
});
</script>

<Legend items={series.map((s) => ({ label: s.name, color: s.color }))} />
<div class="wrap" bind:clientWidth={width}>
<svg
bind:this={svg}
class="chart-svg"
viewBox={`0 0 ${width} ${h}`}
{width}
height={h}
role={hrefs?.some(Boolean) ? 'group' : 'img'}
aria-label={`${yLabel || 'Values'} by category`}
{...keys}
aria-label={`${yLabel || 'Values'} by category. ${KEYS_HINT}`}
onpointerleave={() => (tip = null)}
>
{#each vt as t (t)}
Expand Down Expand Up @@ -169,7 +176,8 @@
height={horizontal ? band : h - m.top - m.bottom}
fill="transparent"
role="presentation"
onpointermove={(e) => show(e, i)}
data-mark={i}
onpointermove={(e) => show(pointerIn(e), i)}
/>
{#if stacked}
{@const segs = series.reduce<{ s: BarSeries; a: number; b: number }[]>((acc, s) => {
Expand Down
22 changes: 15 additions & 7 deletions src/lib/components/charts/BoxPlot.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import { registerCsv } from './csv';
import { compact } from '#lib/format';
import Tip, { type TipState } from './Tip.svelte';
import { KEYS_HINT, markAt, markKeys, pointerIn } from './marks';
import { linear, nice, ticks } from './scale';

let {
Expand Down Expand Up @@ -59,12 +60,10 @@
const sy = $derived(linear(ext, [height - m.bottom, m.top]));
const bw = $derived(Math.min(28, band * 0.6));
let tip = $state<TipState | null>(null);
function show(e: PointerEvent, b: Box) {
const wrap = (e.currentTarget as Element).closest('.wrap')!.getBoundingClientRect();
function show(at: { x: number; y: number }, b: Box) {
const s = b.stats!;
tip = {
x: e.clientX - wrap.left,
y: e.clientY - wrap.top,
...at,
title: `${b.name} (n = ${s.n})`,
lines: [
{ label: 'Upper whisker', value: yFormat(s.hi) },
Expand All @@ -76,16 +75,25 @@
]
};
}
let svg = $state<SVGSVGElement>();
// Only boxes with data are marks.
const withData = $derived(boxes.flatMap((b, i) => (b.stats ? [i] : [])));
const keys = markKeys({
count: () => withData.length,
show: (k) => markAt(svg, withData[k], (p) => show(p, boxes[withData[k]])),
hide: () => (tip = null)
});
</script>

<div class="wrap" bind:clientWidth={width}>
<svg
bind:this={svg}
class="chart-svg"
viewBox={`0 0 ${width} ${height}`}
{width}
{height}
role="img"
aria-label={`${yLabel} by group (box plots)`}
{...keys}
aria-label={`${yLabel} by group (box plots). ${KEYS_HINT}`}
onpointerleave={() => (tip = null)}
>
{#each ticks(ext[0], ext[1], 5) as t (t)}
Expand All @@ -104,7 +112,7 @@
{#if b.stats}
{@const s = b.stats}
{@const c = b.color ?? 'var(--series-1)'}
<g role="presentation" onpointermove={(e) => show(e, b)}>
<g role="presentation" data-mark={i} onpointermove={(e) => show(pointerIn(e), b)}>
<rect
x={cx - band / 2}
width={band}
Expand Down
21 changes: 14 additions & 7 deletions src/lib/components/charts/ForestPlot.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import { num } from '#lib/format';
import Legend from './Legend.svelte';
import Tip, { type TipState } from './Tip.svelte';
import { KEYS_HINT, markAt, markKeys, pointerIn } from './marks';
import { linear } from './scale';

let {
Expand Down Expand Up @@ -92,11 +93,9 @@
const off = (k: number) => (series.length > 1 ? (k - (series.length - 1) / 2) * 9 : 0);

let tip = $state<TipState | null>(null);
function show(e: PointerEvent, i: number) {
const wrap = (e.currentTarget as Element).closest('.wrap')!.getBoundingClientRect();
function show(at: { x: number; y: number }, i: number) {
tip = {
x: e.clientX - wrap.left,
y: e.clientY - wrap.top,
...at,
title: rows[i],
lines: series.map((s) => {
const v = s.values[i];
Expand All @@ -108,17 +107,24 @@
})
};
}
let svg = $state<SVGSVGElement>();
const keys = markKeys({
count: () => rows.length,
show: (i) => markAt(svg, i, (p) => show(p, i)),
hide: () => (tip = null)
});
</script>

<Legend items={series.map((s) => ({ label: s.name, color: s.color, kind: 'dot' as const }))} />
<div class="wrap" bind:clientWidth={width}>
<svg
bind:this={svg}
class="chart-svg"
viewBox={`0 0 ${width} ${h}`}
{width}
height={h}
role="img"
aria-label={`${xLabel || 'Estimates'} with 95% intervals`}
{...keys}
aria-label={`${xLabel || 'Estimates'} with 95% intervals. ${KEYS_HINT}`}
onpointerleave={() => (tip = null)}
>
{#each xt as t (t)}
Expand All @@ -145,7 +151,8 @@
height={band}
fill="transparent"
role="presentation"
onpointermove={(e) => show(e, i)}
data-mark={i}
onpointermove={(e) => show(pointerIn(e), i)}
/>
{#each series as s, k (s.name)}
{@const v = s.values[i]}
Expand Down
25 changes: 18 additions & 7 deletions src/lib/components/charts/Heatmap.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { registerCsv } from './csv';
import { compact } from '#lib/format';
import Tip, { type TipState } from './Tip.svelte';
import { KEYS_HINT, markAt, markKeys, pointerIn } from './marks';

let {
xLabels,
Expand Down Expand Up @@ -66,26 +67,35 @@
}

let tip = $state<TipState | null>(null);
function show(e: PointerEvent, r: number, c: number) {
const wrap = (e.currentTarget as Element).closest('.wrap')!.getBoundingClientRect();
function show(at: { x: number; y: number }, r: number, c: number) {
const v = values[r]?.[c];
tip = {
x: e.clientX - wrap.left,
y: e.clientY - wrap.top,
...at,
title: `${yLabels[r]} · ${xLabels[c]}`,
lines: [{ value: v == null ? 'no data' : format(v) }]
};
}
let svg = $state<SVGSVGElement>();
const keys = markKeys({
count: () => yLabels.length * xLabels.length,
cols: () => xLabels.length,
show: (k) => {
const [r, c] = [Math.floor(k / xLabels.length), k % xLabels.length];
markAt(svg, k, (p) => show(p, r, c));
},
hide: () => (tip = null)
});
</script>

<div class="wrap" bind:clientWidth={width}>
<svg
bind:this={svg}
class="chart-svg"
viewBox={`0 0 ${width} ${h}`}
{width}
height={h}
role="img"
aria-label={`Heatmap of ${yTitle} by ${xTitle}`}
{...keys}
aria-label={`Heatmap of ${yTitle} by ${xTitle}. ${KEYS_HINT}`}
onpointerleave={() => (tip = null)}
>
{#each yLabels as yl, r (r)}
Expand All @@ -109,7 +119,8 @@
fill={f.color}
fill-opacity={f.opacity}
role="presentation"
onpointermove={(e) => show(e, r, c)}
data-mark={r * xLabels.length + c}
onpointermove={(e) => show(pointerIn(e), r, c)}
/>
{#if cellLabels && v != null && cellW > 28}
<text
Expand Down
Loading
Loading