Skip to content

Commit 4477fbc

Browse files
Luenclaude
andauthored
Charts: lighter scatter plots, compressed pages and keyboard access (#76, #32) (#115)
#76 page weight: - Scatter sends one path of dots per colour above 250 points and draws the circles after mount; hover picks the nearest point; coordinates rounded to 0.1 px and shared attributes moved onto one group per colour. - hooks.server.ts compresses HTML and JSON (Brotli/gzip) and sets a weak ETag from the build version and import hash, answering revalidation with a 304. - /sharks no longer ships derivable fields. #32 keyboard and motion: - charts/marks.ts: markKeys (one tab stop per chart, arrows/Home/End step through marks, Enter follows links, Escape hides) and markAt/pointerIn. All nine chart types use it; tooltips announce via role="status". - Reduced motion: global CSS override and no Leaflet zoom/fade animation. - e2e: keyboard test, compression/304 test, axe on /morphometrics and /pressure. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent fea20b3 commit 4477fbc

17 files changed

Lines changed: 415 additions & 92 deletions

‎AGENTS.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,8 @@ Drop the workbook in `data/` named like `Physioshark_Shark Log 2026-2027.xlsx` (
118118
- 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`).
119119
- Species colours come from `src/lib/species.ts` (blacktip = slot 1, sicklefin lemon = slot 2).
120120
- Charts measure their width (`bind:clientWidth`) and carry a `viewBox` so pre-hydration renders scale down instead of overflowing.
121-
- 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.
121+
- 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).
122+
- 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.
122123
- Style guide: `docs/dev/BRANDING.md`.
123124

124125
## Docker / release

‎e2e/pages.spec.ts‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ for (const theme of ['light', 'dark'] as const) {
4848
'/sharks',
4949
'/findings',
5050
'/crew',
51-
'/about'
51+
'/about',
52+
'/morphometrics',
53+
'/pressure'
5254
]) {
5355
await page.goto(route);
5456
for (const v of await axe(page))
@@ -70,3 +72,26 @@ test('nursery links open a profile and the menu works on mobile', async ({ page
7072
);
7173
expect(overflow).toBeLessThanOrEqual(1);
7274
});
75+
76+
test('charts can be read with the keyboard (#32)', async ({ page }) => {
77+
await page.goto('/morphometrics');
78+
for (const chart of await page.locator('svg.chart-svg[role="application"]').all()) {
79+
await chart.focus();
80+
await page.keyboard.press('ArrowRight');
81+
const tip = chart.locator('xpath=..').locator('.tip');
82+
await expect(tip).toBeVisible();
83+
await page.keyboard.press('End');
84+
await expect(tip).toBeVisible();
85+
await page.keyboard.press('Escape');
86+
await expect(tip).toBeHidden();
87+
}
88+
});
89+
90+
test('pages are compressed and revalidate with a 304 (#76)', async ({ request }) => {
91+
const res = await request.get('/morphometrics', { headers: { 'accept-encoding': 'gzip' } });
92+
expect(res.headers()['content-encoding']).toBe('gzip');
93+
const etag = res.headers()['etag'];
94+
expect(etag).toBeTruthy();
95+
const again = await request.get('/morphometrics', { headers: { 'if-none-match': etag } });
96+
expect(again.status()).toBe(304);
97+
});

‎src/app.css‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,3 +363,21 @@ select {
363363
max-width: 100%;
364364
height: auto;
365365
}
366+
367+
/* Keyboard-readable charts (#32): the outline sits outside the axes. */
368+
.chart-svg:focus-visible {
369+
outline-offset: 4px;
370+
border-radius: 4px;
371+
}
372+
373+
/* Reduced motion (#32): no transitions or smooth scrolling. */
374+
@media (prefers-reduced-motion: reduce) {
375+
*,
376+
::before,
377+
::after {
378+
animation-duration: 0.01ms !important;
379+
animation-iteration-count: 1 !important;
380+
transition-duration: 0.01ms !important;
381+
scroll-behavior: auto !important;
382+
}
383+
}

‎src/hooks.server.ts‎

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
import { building } from '$app/env';
1+
import { building, version } from '$app/env';
22
import type { Handle, ServerInit } from '@sveltejs/kit/hooks';
3+
import { brotliCompressSync, constants, gzipSync } from 'node:zlib';
34
import { refresh } from '#lib/server/db';
45

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

23+
const COMPRESSIBLE = /^(text\/|application\/json)/;
24+
25+
/**
26+
* Compress rendered pages and data (#76): adapter-node only precompresses static assets, and a
27+
* scatter-heavy page is several hundred KB of HTML that shrinks about tenfold.
28+
*/
29+
async function compress(req: Request, res: Response): Promise<Response> {
30+
const accept = req.headers.get('accept-encoding') ?? '';
31+
const enc = /\bbr\b/.test(accept) ? 'br' : /\bgzip\b/.test(accept) ? 'gzip' : null;
32+
const type = res.headers.get('content-type') ?? '';
33+
if (!enc || !res.body || res.headers.has('content-encoding') || !COMPRESSIBLE.test(type))
34+
return res;
35+
const raw = Buffer.from(await res.arrayBuffer());
36+
const body =
37+
enc === 'br'
38+
? brotliCompressSync(raw, { params: { [constants.BROTLI_PARAM_QUALITY]: 5 } })
39+
: gzipSync(raw, { level: 6 });
40+
const headers = new Headers(res.headers);
41+
headers.set('content-encoding', enc);
42+
headers.set('content-length', String(body.length));
43+
headers.append('vary', 'Accept-Encoding');
44+
return new Response(body, { status: res.status, statusText: res.statusText, headers });
45+
}
46+
2247
export const handle: Handle = async ({ event, resolve }) => {
48+
const { pathname } = event.url;
2349
// At most once a minute: re-import if a spreadsheet was added or changed (#8).
24-
if (!building && event.url.pathname !== '/health') {
50+
let hash: string | null = null;
51+
if (!building && pathname !== '/health') {
2552
try {
26-
refresh();
53+
hash = refresh().hash;
2754
} catch (err) {
2855
console.error('[import] refresh failed:', err);
2956
}
3057
}
31-
const res = await resolve(event);
58+
// Pages are a function of the build and the imported data only, so one validator covers
59+
// both (#76): a browser revalidating an unchanged page gets a 304 without a render.
60+
const etag =
61+
hash && event.request.method === 'GET' ? `W/"${version}-${hash.slice(0, 16)}"` : null;
62+
if (etag && event.request.headers.get('if-none-match') === etag)
63+
return new Response(null, { status: 304, headers: { etag, 'cache-control': 'no-cache' } });
64+
let res = await resolve(event);
65+
if (etag && res.status === 200 && !res.headers.has('cache-control')) {
66+
res.headers.set('etag', etag);
67+
res.headers.set('cache-control', 'no-cache');
68+
}
69+
if (event.request.method !== 'HEAD') res = await compress(event.request, res);
3270
for (const [k, v] of Object.entries(SECURITY_HEADERS)) res.headers.set(k, v);
3371
return res;
3472
};

‎src/lib/components/InteractiveMap.svelte‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,15 @@
9494
ready = true;
9595
await tick();
9696
if (!el || cancelled) return;
97-
map = L.map(el, { scrollWheelZoom: false, zoomSnap: 0.5 });
97+
// Reduced motion (#32): jump instead of animating zooms and fades.
98+
const still = matchMedia('(prefers-reduced-motion: reduce)').matches;
99+
map = L.map(el, {
100+
scrollWheelZoom: false,
101+
zoomSnap: 0.5,
102+
zoomAnimation: !still,
103+
fadeAnimation: !still,
104+
markerZoomAnimation: !still
105+
});
98106
const bases = Object.fromEntries(
99107
BASEMAPS.map((b) => [
100108
b.name,

‎src/lib/components/charts/BarChart.svelte‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import { compact } from '#lib/format';
1212
import Legend from './Legend.svelte';
1313
import Tip, { type TipState } from './Tip.svelte';
14+
import { KEYS_HINT, markAt, markKeys, pointerIn } from './marks';
1415
import { barPath, hbarPath, linear, nice, ticks } from './scale';
1516
1617
let {
@@ -93,11 +94,9 @@
9394
const rotate = $derived(!horizontal && band < longest * 6.5 + 6);
9495
9596
let tip = $state<TipState | null>(null);
96-
function show(e: PointerEvent, i: number) {
97-
const wrap = (e.currentTarget as Element).closest('.wrap')!.getBoundingClientRect();
97+
function show(at: { x: number; y: number }, i: number) {
9898
tip = {
99-
x: e.clientX - wrap.left,
100-
y: e.clientY - wrap.top,
99+
...at,
101100
title: categories[i],
102101
lines: series
103102
.map((s) => ({
@@ -118,17 +117,25 @@
118117
)
119118
};
120119
}
120+
let svg = $state<SVGSVGElement>();
121+
const keys = markKeys({
122+
count: () => categories.length,
123+
show: (i) => markAt(svg, i, (p) => show(p, i)),
124+
hide: () => (tip = null),
125+
href: (i) => hrefs?.[i]
126+
});
121127
</script>
122128

123129
<Legend items={series.map((s) => ({ label: s.name, color: s.color }))} />
124130
<div class="wrap" bind:clientWidth={width}>
125131
<svg
132+
bind:this={svg}
126133
class="chart-svg"
127134
viewBox={`0 0 ${width} ${h}`}
128135
{width}
129136
height={h}
130-
role={hrefs?.some(Boolean) ? 'group' : 'img'}
131-
aria-label={`${yLabel || 'Values'} by category`}
137+
{...keys}
138+
aria-label={`${yLabel || 'Values'} by category. ${KEYS_HINT}`}
132139
onpointerleave={() => (tip = null)}
133140
>
134141
{#each vt as t (t)}
@@ -169,7 +176,8 @@
169176
height={horizontal ? band : h - m.top - m.bottom}
170177
fill="transparent"
171178
role="presentation"
172-
onpointermove={(e) => show(e, i)}
179+
data-mark={i}
180+
onpointermove={(e) => show(pointerIn(e), i)}
173181
/>
174182
{#if stacked}
175183
{@const segs = series.reduce<{ s: BarSeries; a: number; b: number }[]>((acc, s) => {

‎src/lib/components/charts/BoxPlot.svelte‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import { registerCsv } from './csv';
1919
import { compact } from '#lib/format';
2020
import Tip, { type TipState } from './Tip.svelte';
21+
import { KEYS_HINT, markAt, markKeys, pointerIn } from './marks';
2122
import { linear, nice, ticks } from './scale';
2223
2324
let {
@@ -59,12 +60,10 @@
5960
const sy = $derived(linear(ext, [height - m.bottom, m.top]));
6061
const bw = $derived(Math.min(28, band * 0.6));
6162
let tip = $state<TipState | null>(null);
62-
function show(e: PointerEvent, b: Box) {
63-
const wrap = (e.currentTarget as Element).closest('.wrap')!.getBoundingClientRect();
63+
function show(at: { x: number; y: number }, b: Box) {
6464
const s = b.stats!;
6565
tip = {
66-
x: e.clientX - wrap.left,
67-
y: e.clientY - wrap.top,
66+
...at,
6867
title: `${b.name} (n = ${s.n})`,
6968
lines: [
7069
{ label: 'Upper whisker', value: yFormat(s.hi) },
@@ -76,16 +75,25 @@
7675
]
7776
};
7877
}
78+
let svg = $state<SVGSVGElement>();
79+
// Only boxes with data are marks.
80+
const withData = $derived(boxes.flatMap((b, i) => (b.stats ? [i] : [])));
81+
const keys = markKeys({
82+
count: () => withData.length,
83+
show: (k) => markAt(svg, withData[k], (p) => show(p, boxes[withData[k]])),
84+
hide: () => (tip = null)
85+
});
7986
</script>
8087

8188
<div class="wrap" bind:clientWidth={width}>
8289
<svg
90+
bind:this={svg}
8391
class="chart-svg"
8492
viewBox={`0 0 ${width} ${height}`}
8593
{width}
8694
{height}
87-
role="img"
88-
aria-label={`${yLabel} by group (box plots)`}
95+
{...keys}
96+
aria-label={`${yLabel} by group (box plots). ${KEYS_HINT}`}
8997
onpointerleave={() => (tip = null)}
9098
>
9199
{#each ticks(ext[0], ext[1], 5) as t (t)}
@@ -104,7 +112,7 @@
104112
{#if b.stats}
105113
{@const s = b.stats}
106114
{@const c = b.color ?? 'var(--series-1)'}
107-
<g role="presentation" onpointermove={(e) => show(e, b)}>
115+
<g role="presentation" data-mark={i} onpointermove={(e) => show(pointerIn(e), b)}>
108116
<rect
109117
x={cx - band / 2}
110118
width={band}

‎src/lib/components/charts/ForestPlot.svelte‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import { num } from '#lib/format';
2121
import Legend from './Legend.svelte';
2222
import Tip, { type TipState } from './Tip.svelte';
23+
import { KEYS_HINT, markAt, markKeys, pointerIn } from './marks';
2324
import { linear } from './scale';
2425
2526
let {
@@ -92,11 +93,9 @@
9293
const off = (k: number) => (series.length > 1 ? (k - (series.length - 1) / 2) * 9 : 0);
9394
9495
let tip = $state<TipState | null>(null);
95-
function show(e: PointerEvent, i: number) {
96-
const wrap = (e.currentTarget as Element).closest('.wrap')!.getBoundingClientRect();
96+
function show(at: { x: number; y: number }, i: number) {
9797
tip = {
98-
x: e.clientX - wrap.left,
99-
y: e.clientY - wrap.top,
98+
...at,
10099
title: rows[i],
101100
lines: series.map((s) => {
102101
const v = s.values[i];
@@ -108,17 +107,24 @@
108107
})
109108
};
110109
}
110+
let svg = $state<SVGSVGElement>();
111+
const keys = markKeys({
112+
count: () => rows.length,
113+
show: (i) => markAt(svg, i, (p) => show(p, i)),
114+
hide: () => (tip = null)
115+
});
111116
</script>
112117

113118
<Legend items={series.map((s) => ({ label: s.name, color: s.color, kind: 'dot' as const }))} />
114119
<div class="wrap" bind:clientWidth={width}>
115120
<svg
121+
bind:this={svg}
116122
class="chart-svg"
117123
viewBox={`0 0 ${width} ${h}`}
118124
{width}
119125
height={h}
120-
role="img"
121-
aria-label={`${xLabel || 'Estimates'} with 95% intervals`}
126+
{...keys}
127+
aria-label={`${xLabel || 'Estimates'} with 95% intervals. ${KEYS_HINT}`}
122128
onpointerleave={() => (tip = null)}
123129
>
124130
{#each xt as t (t)}
@@ -145,7 +151,8 @@
145151
height={band}
146152
fill="transparent"
147153
role="presentation"
148-
onpointermove={(e) => show(e, i)}
154+
data-mark={i}
155+
onpointermove={(e) => show(pointerIn(e), i)}
149156
/>
150157
{#each series as s, k (s.name)}
151158
{@const v = s.values[i]}

‎src/lib/components/charts/Heatmap.svelte‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { registerCsv } from './csv';
33
import { compact } from '#lib/format';
44
import Tip, { type TipState } from './Tip.svelte';
5+
import { KEYS_HINT, markAt, markKeys, pointerIn } from './marks';
56
67
let {
78
xLabels,
@@ -66,26 +67,35 @@
6667
}
6768
6869
let tip = $state<TipState | null>(null);
69-
function show(e: PointerEvent, r: number, c: number) {
70-
const wrap = (e.currentTarget as Element).closest('.wrap')!.getBoundingClientRect();
70+
function show(at: { x: number; y: number }, r: number, c: number) {
7171
const v = values[r]?.[c];
7272
tip = {
73-
x: e.clientX - wrap.left,
74-
y: e.clientY - wrap.top,
73+
...at,
7574
title: `${yLabels[r]} · ${xLabels[c]}`,
7675
lines: [{ value: v == null ? 'no data' : format(v) }]
7776
};
7877
}
78+
let svg = $state<SVGSVGElement>();
79+
const keys = markKeys({
80+
count: () => yLabels.length * xLabels.length,
81+
cols: () => xLabels.length,
82+
show: (k) => {
83+
const [r, c] = [Math.floor(k / xLabels.length), k % xLabels.length];
84+
markAt(svg, k, (p) => show(p, r, c));
85+
},
86+
hide: () => (tip = null)
87+
});
7988
</script>
8089

8190
<div class="wrap" bind:clientWidth={width}>
8291
<svg
92+
bind:this={svg}
8393
class="chart-svg"
8494
viewBox={`0 0 ${width} ${h}`}
8595
{width}
8696
height={h}
87-
role="img"
88-
aria-label={`Heatmap of ${yTitle} by ${xTitle}`}
97+
{...keys}
98+
aria-label={`Heatmap of ${yTitle} by ${xTitle}. ${KEYS_HINT}`}
8999
onpointerleave={() => (tip = null)}
90100
>
91101
{#each yLabels as yl, r (r)}
@@ -109,7 +119,8 @@
109119
fill={f.color}
110120
fill-opacity={f.opacity}
111121
role="presentation"
112-
onpointermove={(e) => show(e, r, c)}
122+
data-mark={r * xLabels.length + c}
123+
onpointermove={(e) => show(pointerIn(e), r, c)}
113124
/>
114125
{#if cellLabels && v != null && cellW > 28}
115126
<text

0 commit comments

Comments
 (0)