From 96398ae5c14a251158b466ab8c69a01052795dca Mon Sep 17 00:00:00 2001 From: luen Date: Tue, 3 Nov 2026 21:32:48 +1000 Subject: [PATCH] Charts: lighter scatter plots, compressed pages and keyboard access (#76, #32) #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 --- AGENTS.md | 3 +- e2e/pages.spec.ts | 27 +++- src/app.css | 18 +++ src/hooks.server.ts | 46 ++++++- src/lib/components/InteractiveMap.svelte | 10 +- src/lib/components/charts/BarChart.svelte | 22 ++-- src/lib/components/charts/BoxPlot.svelte | 22 ++-- src/lib/components/charts/ForestPlot.svelte | 21 ++-- src/lib/components/charts/Heatmap.svelte | 25 ++-- src/lib/components/charts/Histogram.svelte | 21 ++-- src/lib/components/charts/LineChart.svelte | 23 ++-- src/lib/components/charts/Polar.svelte | 21 ++-- src/lib/components/charts/Scatter.svelte | 129 ++++++++++++++++---- src/lib/components/charts/Timeline.svelte | 28 +++-- src/lib/components/charts/marks.ts | 84 +++++++++++++ src/routes/sharks/+page.server.ts | 6 +- src/routes/sharks/+page.svelte | 1 + 17 files changed, 415 insertions(+), 92 deletions(-) create mode 100644 src/lib/components/charts/marks.ts diff --git a/AGENTS.md b/AGENTS.md index d447cf2..8dac3bd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -111,7 +111,8 @@ Drop the workbook in `data/` named like `Physioshark_Shark Log 2026-2027.xlsx` ( - Cite the study behind a chart with `` (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/` (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 ``. `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 diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index 25e5c88..16cf2bf 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -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)) @@ -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); +}); diff --git a/src/app.css b/src/app.css index d7d30d8..a9d5e17 100644 --- a/src/app.css +++ b/src/app.css @@ -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; + } +} diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 5f30403..9944317 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -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. @@ -19,16 +20,53 @@ const SECURITY_HEADERS: Record = { '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 { + 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; }; diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index df1c828..07629fa 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -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, diff --git a/src/lib/components/charts/BarChart.svelte b/src/lib/components/charts/BarChart.svelte index 2251b36..31a00ba 100644 --- a/src/lib/components/charts/BarChart.svelte +++ b/src/lib/components/charts/BarChart.svelte @@ -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 { @@ -93,11 +94,9 @@ const rotate = $derived(!horizontal && band < longest * 6.5 + 6); let tip = $state(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) => ({ @@ -118,17 +117,25 @@ ) }; } + let svg = $state(); + const keys = markKeys({ + count: () => categories.length, + show: (i) => markAt(svg, i, (p) => show(p, i)), + hide: () => (tip = null), + href: (i) => hrefs?.[i] + }); ({ label: s.name, color: s.color }))} />
(tip = null)} > {#each vt as t (t)} @@ -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) => { diff --git a/src/lib/components/charts/BoxPlot.svelte b/src/lib/components/charts/BoxPlot.svelte index a2bcd0d..806cae0 100644 --- a/src/lib/components/charts/BoxPlot.svelte +++ b/src/lib/components/charts/BoxPlot.svelte @@ -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 { @@ -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(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) }, @@ -76,16 +75,25 @@ ] }; } + let svg = $state(); + // 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) + });
(tip = null)} > {#each ticks(ext[0], ext[1], 5) as t (t)} @@ -104,7 +112,7 @@ {#if b.stats} {@const s = b.stats} {@const c = b.color ?? 'var(--series-1)'} - show(e, b)}> + show(pointerIn(e), b)}> (series.length > 1 ? (k - (series.length - 1) / 2) * 9 : 0); let tip = $state(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]; @@ -108,17 +107,24 @@ }) }; } + let svg = $state(); + const keys = markKeys({ + count: () => rows.length, + show: (i) => markAt(svg, i, (p) => show(p, i)), + hide: () => (tip = null) + }); ({ label: s.name, color: s.color, kind: 'dot' as const }))} />
(tip = null)} > {#each xt as t (t)} @@ -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]} diff --git a/src/lib/components/charts/Heatmap.svelte b/src/lib/components/charts/Heatmap.svelte index 2cb229f..7d6ea1f 100644 --- a/src/lib/components/charts/Heatmap.svelte +++ b/src/lib/components/charts/Heatmap.svelte @@ -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, @@ -66,26 +67,35 @@ } let tip = $state(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(); + 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) + });
(tip = null)} > {#each yLabels as yl, r (r)} @@ -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} (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: `${xFormat(edges[i])} – ${xFormat(edges[i + 1])}`, lines: series.map((s) => ({ label: series.length > 1 ? s.name : undefined, @@ -79,17 +78,24 @@ })) }; } + let svg = $state(); + const keys = markKeys({ + count: () => edges.length - 1, + show: (i) => markAt(svg, i, (p) => show(p, i)), + hide: () => (tip = null) + }); ({ label: s.name, color: s.color }))} />
(tip = null)} > {#each ticks(yExt[0], yExt[1], 4) as t (t)} @@ -127,7 +133,8 @@ height={height - m.top - m.bottom} fill="transparent" role="presentation" - onpointermove={(e) => show(e, i)} + data-mark={i} + onpointermove={(e) => show(pointerIn(e), i)} /> {/each} {#if mode === 'overlay'} diff --git a/src/lib/components/charts/LineChart.svelte b/src/lib/components/charts/LineChart.svelte index 59f3bd7..a2af521 100644 --- a/src/lib/components/charts/LineChart.svelte +++ b/src/lib/components/charts/LineChart.svelte @@ -14,6 +14,7 @@ import { compact } from '#lib/format'; import Legend from './Legend.svelte'; import Tip, { type TipState } from './Tip.svelte'; + import { KEYS_HINT, markKeys } from './marks'; import { dateTicks, fromDay, linear, linePath, nice, ticks } from './scale'; let { @@ -110,11 +111,8 @@ return Math.abs(pts[lo].x - x) <= Math.abs(pts[hi].x - x) ? pts[lo] : pts[hi]; } - function move(e: PointerEvent) { - const rect = (e.currentTarget as SVGElement).getBoundingClientRect(); - const px = e.clientX - rect.left; - if (px < m.left || px > width - m.right) return leave(); - const x = sx.invert(px); + /** Tooltip for the points nearest x; `y` is the tooltip's height (default: the first point). */ + function showX(x: number, y?: number) { const hits = series .map((s) => ({ s, p: nearest(s.points, x) })) .filter((h) => h.p && h.p.y != null) as { s: LineSeries; p: { x: number; y: number } }[]; @@ -123,7 +121,7 @@ hoverX = px0; tip = { x: sx(px0), - y: e.clientY - rect.top, + y: y ?? sy(hits[0].p.y), title: fx(px0), lines: hits.map((h) => ({ label: series.length > 1 ? h.s.name : undefined, @@ -132,10 +130,19 @@ })) }; } + function move(e: PointerEvent) { + const rect = (e.currentTarget as SVGElement).getBoundingClientRect(); + const px = e.clientX - rect.left; + if (px < m.left || px > width - m.right) return leave(); + showX(sx.invert(px), e.clientY - rect.top); + } function leave() { tip = null; hoverX = null; } + // Keyboard: every distinct x, left to right. + const steps = $derived([...new Set(xs)].sort((a, b) => a - b)); + const keys = markKeys({ count: () => steps.length, show: (k) => showX(steps[k]), hide: leave }); s.name).join(', ')}`} + {...keys} + aria-label={`${yLabel || 'Value'} over ${xLabel || (xType === 'date' ? 'time' : 'x')}: ${series.map((s) => s.name).join(', ')}. ${KEYS_HINT}`} onpointermove={move} onpointerleave={leave} > diff --git a/src/lib/components/charts/Polar.svelte b/src/lib/components/charts/Polar.svelte index 0e483fb..a1e8ba8 100644 --- a/src/lib/components/charts/Polar.svelte +++ b/src/lib/components/charts/Polar.svelte @@ -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 { sectors, @@ -40,12 +41,10 @@ return `M${cx},${cy}L${cx + r * Math.cos(a0)},${cy + r * Math.sin(a0)}A${r},${r} 0 0 1 ${cx + r * Math.cos(a1)},${cy + r * Math.sin(a1)}Z`; } let tip = $state(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) { const s = sectors[i]; tip = { - x: e.clientX - wrap.left, - y: e.clientY - wrap.top, + ...at, title: s.label, lines: [ { value: s.value == null ? '–' : format(s.value) }, @@ -53,16 +52,23 @@ ] }; } + let svg = $state(); + const keys = markKeys({ + count: () => sectors.length, + show: (i) => markAt(svg, i, (p) => show(p, i)), + hide: () => (tip = null) + });
(tip = null)} > {#each [0.25, 0.5, 0.75, 1] as f (f)} @@ -78,7 +84,8 @@ stroke="var(--surface)" stroke-width="1" role="presentation" - onpointermove={(e) => show(e, i)} + data-mark={i} + onpointermove={(e) => show(pointerIn(e), i)} />
p.href) ? 'group' : 'img'} - aria-label={`${yLabel} against ${xLabel}`} - onpointerleave={() => (tip = null)} + {...keys} + aria-label={`${yLabel} against ${xLabel}. ${KEYS_HINT}`} + onpointermove={move} + onpointerleave={hide} > {#each yt as t (t)} @@ -153,25 +216,43 @@ y2={height - m.bottom} stroke="var(--axis)" /> - {#each pts as p, i (i)} - - show(e, p)} + {#each layers as l (l.color)} + {#if !circles} + - + {:else if links} + + {#each l.idx as i (i)} + + + + {/each} + + {:else} + + {#each l.idx as i (i)} + + {/each} + + {/if} {/each} + {#if active != null && placed[active]} + + {/if} {#each fits as f (f.name)} `${sx(q.x).toFixed(1)},${sy(q.y).toFixed(1)}`).join(' ')} diff --git a/src/lib/components/charts/Timeline.svelte b/src/lib/components/charts/Timeline.svelte index c03a6ba..9b00429 100644 --- a/src/lib/components/charts/Timeline.svelte +++ b/src/lib/components/charts/Timeline.svelte @@ -1,6 +1,7 @@
(tip = null)} > {#each dateTicks(lo, hi, Math.max(3, Math.floor(width / 90))) as t (t.v)} @@ -75,7 +88,8 @@ rx="4" fill={it.color ?? 'var(--series-1)'} role="presentation" - onpointermove={(e) => show(e, r.label, it.tip)} + data-mark={first[i] + k} + onpointermove={(e) => show(pointerIn(e), r.label, it.tip)} /> {/each} {/each} diff --git a/src/lib/components/charts/marks.ts b/src/lib/components/charts/marks.ts new file mode 100644 index 0000000..3e06260 --- /dev/null +++ b/src/lib/components/charts/marks.ts @@ -0,0 +1,84 @@ +/** + * Keyboard access to chart marks (#32). Each chart is one tab stop: arrow keys step through its + * marks (left/right along a row, up/down across a grid), Home/End jump to the ends, Enter follows + * a mark's link and Escape hides the tooltip. The tooltip (role="status") announces each value. + */ +import { goto } from '$app/navigation'; + +export interface MarkKeysOptions { + count: () => number; + /** Marks per row for grids (heatmaps); omit and up/down step like left/right. */ + cols?: () => number; + show: (i: number) => void; + hide: () => void; + href?: (i: number) => string | null | undefined; +} + +export function markKeys(o: MarkKeysOptions) { + let i = -1; + const go = (j: number) => { + const n = o.count(); + if (!n) return; + i = Math.max(0, Math.min(n - 1, j)); + o.show(i); + }; + return { + // "application" makes screen readers pass the arrow keys through instead of browsing. A + // chart with nothing to read stays a plain, unfocusable image. (Getters keep both reactive + // when the props are spread onto the svg.) + get role() { + return o.count() ? 'application' : 'img'; + }, + get tabindex() { + return o.count() ? 0 : undefined; + }, + // Mouse clicks also focus the chart; only keyboard focus opens the first tooltip. + onfocus: (e: FocusEvent) => { + if ((e.currentTarget as Element).matches(':focus-visible')) go(Math.max(i, 0)); + }, + onblur: () => o.hide(), + onkeydown: (e: KeyboardEvent) => { + const row = o.cols?.() ?? 1; + const step: Record = { + ArrowRight: 1, + ArrowLeft: -1, + ArrowDown: row, + ArrowUp: -row, + Home: -Infinity, + End: Infinity + }; + if (e.key in step) { + e.preventDefault(); + const s = step[e.key]; + go(!Number.isFinite(s) ? (s > 0 ? o.count() - 1 : 0) : i < 0 ? 0 : i + s); + } else if (e.key === 'Escape') o.hide(); + else if (e.key === 'Enter' && i >= 0) { + const href = o.href?.(i); + if (href) goto(href); + } + } + }; +} + +/** Pointer position relative to the chart's .wrap (tooltip origin). */ +export function pointerIn(e: PointerEvent) { + const w = (e.currentTarget as Element).closest('.wrap')!.getBoundingClientRect(); + return { x: e.clientX - w.left, y: e.clientY - w.top }; +} + +/** Calls `fn` with the centre of the element marked data-mark="i", relative to the .wrap. */ +export function markAt( + svg: SVGSVGElement | undefined, + i: number, + fn: (at: { x: number; y: number }) => void +) { + const el = svg?.querySelector(`[data-mark="${i}"]`); + const wrap = svg?.closest('.wrap'); + if (!el || !wrap) return; + const a = el.getBoundingClientRect(); + const w = wrap.getBoundingClientRect(); + fn({ x: a.left + a.width / 2 - w.left, y: a.top + a.height / 2 - w.top }); +} + +/** Accessible name suffix for keyboard-readable charts. */ +export const KEYS_HINT = 'Use the arrow keys to read each value.'; diff --git a/src/routes/sharks/+page.server.ts b/src/routes/sharks/+page.server.ts index cdf37d5..2544dff 100644 --- a/src/routes/sharks/+page.server.ts +++ b/src/routes/sharks/+page.server.ts @@ -6,10 +6,9 @@ export const load: PageServerLoad = () => memo('sharks', (d) => { const rows = d.individuals .filter((i) => i.species !== 'Unknown') + // Only what the table shows: every byte here is sent for ~2,500 sharks (#76). .map((i) => ({ id: i.id, - href: `/sharks/${encodeURIComponent(i.id)}`, - tagged: /^\d{14,16}$|^COFA/.test(i.id), species: i.species, sex: i.sex, n: i.nCaptures, @@ -18,8 +17,7 @@ export const load: PageServerLoad = () => last: i.lastDate, sites: (JSON.parse(i.sites ?? '[]') as string[]).map((s) => siteName(d, s)).join(' → '), tl0: i.firstTlMm, - tl1: i.lastTlMm, - conflict: i.conflict + tl1: i.lastTlMm })) .sort((a, b) => b.n - a.n || (b.last ?? '').localeCompare(a.last ?? '')); return { rows }; diff --git a/src/routes/sharks/+page.svelte b/src/routes/sharks/+page.svelte index 66f0298..d640188 100644 --- a/src/routes/sharks/+page.svelte +++ b/src/routes/sharks/+page.svelte @@ -72,6 +72,7 @@ ]} rows={filtered.map((r) => ({ ...r, + href: `/sharks/${encodeURIComponent(r.id)}`, speciesL: speciesName(r.species), firstL: date(r.first), lastL: date(r.last)