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 @@ -235,3 +235,4 @@ Questions for the lab go to Dr Jodie Rummer (`@JodieRummer`) on GitHub: label th
| 2026-11 | v0.2.10: pressure scores from the Bouyoucos et al. (2024) dataset (#131); year-off recaptures take their set's date (#133); lab statistics conventions (#132) and sex-ratio wording (#130); capture numbers that disagree with the tags go on the Data quality page (#168). |

- Security scans (#144): use Snyk CLI >=1.1308.3 with `test --all-projects --dev` for the pnpm 12 multi-document lockfile. Remaining upstream advisories and mitigations are tracked in docs/dev/SNYK-144.md.
- Leaflet treats string tooltips as HTML. Pass a DOM element populated with `textContent` for workbook-derived point and move labels, including when rebuilding overlays.
31 changes: 31 additions & 0 deletions e2e/map-tooltip.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { expect, test } from '@playwright/test';

test('map tooltips display workbook labels as text', async ({ page }) => {
const label = '<b data-tooltip-markup>Haapiti</b>';
await page.route('**/nurseries/__data.json*', async (route) => {
const response = await route.fetch();
const body = (await response.text()).replaceAll('"Haapiti"', JSON.stringify(label));
await route.fulfill({ response, body });
});
await page.route(/server\.arcgisonline\.com|tile\.openstreetmap\.org/, (route) => route.abort());
await page.goto('/');
await page
.locator('a[href="/nurseries"]')
.first()
.evaluate((a: HTMLAnchorElement) => a.click());
const points = page.locator('.leaflet-interactive.ps-layer-0');
await expect(points.first()).toBeVisible();
let found = false;
for (const point of await points.all()) {
await point.dispatchEvent('mouseover');
const tip = page.locator('.leaflet-tooltip').last();
if ((await tip.textContent())?.includes('Haapiti')) {
await expect(tip).toHaveText(label);
await expect(tip.locator('[data-tooltip-markup]')).toHaveCount(0);
found = true;
break;
}
await point.dispatchEvent('mouseout');
}
expect(found).toBe(true);
});
104 changes: 74 additions & 30 deletions src/lib/components/InteractiveMap.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
sized?: boolean;
/** Fixed radius in px when not sized (default 5). */
radius?: number;
/** Value that gets the largest circle; fix it to keep sizes comparable as points change. */
max?: number;
}

/** Base maps (#29). Hosts must match img-src in vite.config.ts. */
Expand Down Expand Up @@ -66,6 +68,12 @@
let el = $state<HTMLDivElement>();
let ready = $state(false);

function tooltip(label: string) {
const span = document.createElement('span');
span.textContent = label;
return span;
}

function popup(p: MapPoint) {
const box = document.createElement('div');
const title = document.createElement(p.href ? 'a' : 'strong');
Expand All @@ -84,8 +92,15 @@
return box;
}

let map = $state.raw<import('leaflet').Map>();
let leaflet: typeof import('leaflet') | undefined;
let drawn: {
groups: import('leaflet').LayerGroup[];
control: import('leaflet').Control.Layers;
}[] = [];
let bases: Record<string, import('leaflet').TileLayer> = {};

onMount(() => {
let map: import('leaflet').Map | undefined;
let cancelled = false;
(async () => {
const mod = await import('leaflet');
Expand All @@ -94,55 +109,79 @@
ready = true;
await tick();
if (!el || cancelled) return;
leaflet = L;
// Reduced motion (#32): jump instead of animating zooms and fades.
const still = matchMedia('(prefers-reduced-motion: reduce)').matches;
map = L.map(el, {
const m = L.map(el, {
scrollWheelZoom: false,
zoomSnap: 0.5,
zoomAnimation: !still,
fadeAnimation: !still,
markerZoomAnimation: !still
});
const bases = Object.fromEntries(
bases = Object.fromEntries(
BASEMAPS.map((b) => [
b.name,
L.tileLayer(b.url, { attribution: b.attribution, maxZoom: b.maxZoom })
])
);
bases[BASEMAPS[0].name].addTo(map);
const overlays: Record<string, import('leaflet').LayerGroup> = {};
const all: [number, number][] = [];
layers.forEach((layer, i) => {
const max = Math.max(1e-9, ...layer.points.map((p) => p.value ?? 0));
const group = L.layerGroup();
for (const p of layer.points) {
const r = layer.sized
? 5 + 13 * Math.sqrt(Math.max(0, p.value ?? 0) / max)
: (layer.radius ?? 5);
const tooltip = document.createElement('span');
tooltip.textContent = p.label;
L.circleMarker([p.lat, p.lon], { radius: r, className: `ps-layer ps-layer-${i}` })
.bindTooltip(tooltip)
.bindPopup(() => popup(p))
.addTo(group);
all.push([p.lat, p.lon]);
}
group.addTo(map!);
overlays[`<span class="ps-key ps-layer-${i}"></span>${layer.name}`] = group;
});
L.control
.layers(bases, layers.length > 1 ? overlays : {}, { collapsed: el.clientWidth < 560 })
.addTo(map);
if (focus) map.setView([focus.lat, focus.lon], focus.zoom ?? 14);
else if (all.length) map.fitBounds(L.latLngBounds(all), { padding: [24, 24], maxZoom: 14 });
else map.setView([-17.53, -149.83], 12);
bases[BASEMAPS[0].name].addTo(m);
const all = layers.flatMap((l) => l.points.map((p) => [p.lat, p.lon] as [number, number]));
if (focus) m.setView([focus.lat, focus.lon], focus.zoom ?? 14);
else if (all.length) m.fitBounds(L.latLngBounds(all), { padding: [24, 24], maxZoom: 14 });
else m.setView([-17.53, -149.83], 12);
map = m;
})();
return () => {
cancelled = true;
map?.remove();
};
});

// Redraw the overlays whenever the layers change (e.g. a season slider), keeping the view.
$effect(() => {
const m = map;
const L = leaflet;
const current = layers;
if (!m || !L || !el) return;
const hidden = new Set(
drawn.length
? current.map((l, i) => (drawn[0].groups[i] && !m.hasLayer(drawn[0].groups[i]) ? i : -1))
: []
);
for (const d of drawn) {
d.groups.forEach((g) => g.remove());
d.control.remove();
}
const overlays: Record<string, import('leaflet').LayerGroup> = {};
const groups = current.map((layer, i) => {
const max = layer.max ?? Math.max(1e-9, ...layer.points.map((p) => p.value ?? 0));
const group = L.layerGroup();
for (const p of layer.points) {
const empty = layer.sized && p.value == null;
const r = empty
? 5
: layer.sized
? 5 + 13 * Math.sqrt(Math.min(1, Math.max(0, p.value ?? 0) / max))
: (layer.radius ?? 5);
L.circleMarker([p.lat, p.lon], {
radius: r,
className: `ps-layer ps-layer-${i}${empty ? ' ps-empty' : ''}`
})
.bindTooltip(tooltip(p.label))
.bindPopup(() => popup(p))
.addTo(group);
}
if (!hidden.has(i)) group.addTo(m);
overlays[`<span class="ps-key ps-layer-${i}"></span>${layer.name}`] = group;
return group;
});
const control = L.control
.layers(bases, current.length > 1 ? overlays : {}, { collapsed: el.clientWidth < 560 })
.addTo(m);
drawn = [{ groups, control }];
});

const style = $derived(layers.map((l, i) => `--ps-layer-${i}: ${l.color}`).join('; '));
</script>

Expand Down Expand Up @@ -189,6 +228,11 @@
font-size: 0.8rem;
color: #13213a;
}
.map :global(.leaflet-interactive.ps-layer.ps-empty) {
fill: transparent;
stroke: var(--muted);
stroke-dasharray: 2 2;
}
.map :global(.ps-key) {
display: inline-block;
width: 10px;
Expand Down
10 changes: 9 additions & 1 deletion src/routes/nurseries/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@ export const load: PageServerLoad = () =>
round(cpueOf(eff.filter((s) => s.siteId === id && s.season === season)))
)
);
// Per-season counts for the map's season slider (#172).
const perSeason = ids.map((id) =>
d.seasons.map((season) => ({
sets: d.sets.filter((x) => x.siteId === id && x.season === season && x.gear === 'Gillnet')
.length,
captures: caps.filter((c) => c.siteId === id && c.season === season).length
}))
);
// Adult blacktips caught on hook and line, where the datasheet has both coordinates.
const adults = d.adults
.filter((a) => a.lat != null && a.lon != null && a.lon < 0)
Expand All @@ -79,5 +87,5 @@ export const load: PageServerLoad = () =>
)
)
};
return { rows, seasons: d.seasons, heat, adults, stats };
return { rows, seasons: d.seasons, heat, perSeason, adults, stats };
});
116 changes: 104 additions & 12 deletions src/routes/nurseries/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,57 @@
import type { PageProps } from './$types';

let { data }: PageProps = $props();
const mapped = $derived(data.rows.filter((r) => r.lat != null && r.lon != null));

// Season slider (#172): the last stop shows every season pooled.
let idx = $state(Number.MAX_SAFE_INTEGER);
const all = $derived(data.seasons.length);
const at = $derived(Math.min(idx, all));
const seasonLabel = $derived(at === all ? 'All seasons' : season(data.seasons[at]));
// One scale for every frame so circle sizes stay comparable between seasons.
const scaleMax = $derived(
Math.max(1e-9, ...data.heat.flat().map((v) => v ?? 0), ...data.rows.map((r) => r.cpue ?? 0))
);
const points = $derived(
data.rows.flatMap((r, i) => {
if (r.lat == null || r.lon == null) return [];
const s = at === all ? null : data.perSeason[i][at];
const value = at === all ? r.cpue : data.heat[i][at];
return [
{
id: r.id,
label: r.name,
lat: r.lat,
lon: r.lon,
value,
href: r.href,
sub: s
? value == null
? s.sets
? `${num(s.sets)} sets, none timed`
: 'Not sampled this season'
: `${num(s.captures)} captures, ${num(s.sets)} sets`
: `${num(r.captures)} captures, ${num(r.sets)} sets`
}
];
})
);

let timer: ReturnType<typeof setInterval> | undefined;
let playing = $state(false);
function stop() {
clearInterval(timer);
playing = false;
}
function play() {
if (playing) return stop();
if (at >= all - 1) idx = 0;
playing = true;
timer = setInterval(() => {
if (idx >= all - 1) stop();
else idx = Math.min(idx, all) + 1;
}, 1200);
}
$effect(() => stop);
</script>

<div class="container">
Expand All @@ -26,26 +76,39 @@
<ChartCard
title="Nurseries around the island"
papers={['eustache2024density', 'bouyoucos2022nursery']}
subtitle="Circles sized by sharks per net-hour (both species). Switch between satellite and street maps, or show adult blacktip capture spots."
subtitle="Circles sized by sharks per net-hour (both species), on one scale for every season. Dashed rings: not sampled with timed sets that season. Switch between satellite and street maps, or show adult blacktip capture spots."
>
<div class="slider">
<button type="button" class="play" onclick={play} aria-pressed={playing}>
{playing ? 'Pause' : 'Play seasons'}
</button>
<label for="season-slider">Season</label>
<input
id="season-slider"
type="range"
min="0"
max={all}
step="1"
value={at}
oninput={(e) => {
stop();
idx = Number(e.currentTarget.value);
}}
aria-valuetext={seasonLabel}
/>
<output for="season-slider">{seasonLabel}</output>
</div>
<InteractiveMap
label="Map of Mo'orea's shark nurseries"
valueLabel="Sharks / net-hour"
format={(v) => num(v, 2)}
layers={[
{
name: 'Nurseries',
name: at === all ? 'Nurseries' : `Nurseries, ${seasonLabel}`,
color: 'var(--series-1)',
sized: true,
points: mapped.map((r) => ({
id: r.id,
label: r.name,
lat: r.lat!,
lon: r.lon!,
value: r.cpue,
href: r.href,
sub: `${num(r.captures)} captures, ${num(r.sets)} sets`
}))
max: scaleMax,
points
},
...(data.adults.length
? [{ name: 'Adult blacktip captures', color: 'var(--series-4)', points: data.adults }]
Expand Down Expand Up @@ -138,3 +201,32 @@
</p>
</section>
</div>

<style>
.slider {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 12px;
margin-bottom: 12px;
font-size: 0.9rem;
}
.slider input {
flex: 1 1 220px;
accent-color: var(--series-1);
}
.slider output {
min-width: 7.5em;
font-weight: 650;
font-variant-numeric: tabular-nums;
}
.play {
font: inherit;
padding: 4px 12px;
border-radius: 999px;
border: 1px solid var(--hairline);
background: var(--surface-2);
color: var(--ink);
cursor: pointer;
}
</style>
Loading