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
27 changes: 27 additions & 0 deletions e2e/map-keyboard.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,30 @@ test('SVG map fallback supports the shared arrow-key chart controls', async ({ p
await svg.press('Escape');
await expect(map.locator('.tip')).toHaveCount(0);
});

test('directed move markers and keyboard controls survive a zoom redraw', async ({ page }) => {
await page.emulateMedia({ reducedMotion: 'reduce' });
await page.route(/server\.arcgisonline\.com|tile\.openstreetmap\.org/, (route) => route.abort());
await page.goto('/recaptures');
const map = page.getByRole('region', {
name: "Map of recaptured sharks' moves between nurseries"
});
const line = map.locator('.ps-line-0[role="button"]').first();
await expect(line).toBeVisible();
const before = await line.getAttribute('d');
// marker-mid needs an interior vertex, not just the two endpoints.
expect(before!.match(/[ML]/g)!.length).toBeGreaterThanOrEqual(3);
await map.getByRole('button', { name: 'Zoom in', exact: true }).click();
await expect.poll(() => line.getAttribute('d')).not.toBe(before);
for (const path of await map.locator('.ps-line').all()) {
const ref = await path.getAttribute('marker-mid');
expect(ref).toMatch(/^url\(#.+\)$/);
const id = ref!.slice(5, -1);
expect(await page.evaluate((id) => document.getElementById(id)?.tagName, id)).toBe('marker');
}
await line.focus();
await line.press('Enter');
await expect(map.locator('.leaflet-popup-content')).toContainText(
(await line.getAttribute('aria-label'))!
);
});
70 changes: 55 additions & 15 deletions src/lib/components/InteractiveMap.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
import { onMount, tick } from 'svelte';
import MooreaMap from './MooreaMap.svelte';
import { registerCsv } from './charts/csv';
import { directedPoints, lineWidth, reversed, shiftFor } from './lineGeometry';

let {
layers,
Expand Down Expand Up @@ -165,6 +166,8 @@
}

let map = $state.raw<import('leaflet').Map>();
let zoom = $state(0);
const uid = $props.id();
let leaflet: typeof import('leaflet') | undefined;
let drawn: {
groups: { key: string; group: import('leaflet').LayerGroup }[];
Expand Down Expand Up @@ -202,6 +205,9 @@
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);
// Line offsets are in screen pixels, so redraw them at each zoom (#182).
m.on('zoomend', () => (zoom = m.getZoom()));
zoom = m.getZoom();
map = m;
})();
return () => {
Expand All @@ -217,6 +223,7 @@
const current = layers;
const currentLines = lineLayers;
const currentDensity = density;
void zoom;
if (!m || !L || !el) return;
const hidden = new Set(
drawn.flatMap((d) => d.groups.filter((g) => !m.hasLayer(g.group)).map((g) => g.key))
Expand Down Expand Up @@ -248,26 +255,33 @@
})()
]
: [];
// Direction (#182): an arrow mid-line; a move drawn both ways splits into two parallel lines.
const back = reversed(currentLines.flatMap((g) => g.lines));
let n = 0;
const lineGroups = currentLines.map((g, i) => {
const group = L.layerGroup();
for (const l of g.lines)
keyboardLine(
L.polyline(
[
[l.from.lat, l.from.lon],
[l.to.lat, l.to.lon]
],
{
weight: 1.5 + 6 * Math.sqrt((l.value ?? 1) / lineMax),
className: `ps-line ps-line-${i}`,
lineCap: 'round'
}
),
l.label
)
for (const l of g.lines) {
const weight = lineWidth(l.value, lineMax);
const a = m.latLngToLayerPoint([l.from.lat, l.from.lon]);
const b = m.latLngToLayerPoint([l.to.lat, l.to.lon]);
const pts = directedPoints(a.x, a.y, b.x, b.y, back[n++] ? shiftFor(weight) : 0).map(
([x, y]) => m.layerPointToLatLng([x, y])
);
const line = L.polyline(pts, {
weight,
className: `ps-line ps-line-${i}`,
lineCap: 'round',
// Keep the midpoint the arrow marker hangs on (Leaflet would simplify it away).
smoothFactor: 0
});
line.on('add', () =>
line.getElement()?.setAttribute('marker-mid', `url(#${uid}-arrow-${i})`)
);
keyboardLine(line, l.label)
.bindTooltip(tooltip(l.label))
.bindPopup(() => popup(l, lineLabel))
.addTo(group);
}
const key = `line:${i}`;
if (!hidden.has(key)) group.addTo(m);
overlays[`<span class="ps-key ps-line-key ps-line-${i}"></span>${g.name}`] = group;
Expand Down Expand Up @@ -361,6 +375,26 @@
aria-label={label}
style={`${style}; height: ${height}px`}
></div>
{#if lineLayers.length}
<svg class="defs" aria-hidden="true">
<defs>
{#each lineLayers as g, i (i)}
<marker
id={`${uid}-arrow-${i}`}
viewBox="0 0 10 10"
refX="5"
refY="5"
markerWidth="16"
markerHeight="16"
markerUnits="userSpaceOnUse"
orient="auto"
>
<path d="M0,0 L10,5 L0,10 z" fill={g.color} stroke="#fff" stroke-width="1" />
</marker>
{/each}
</defs>
</svg>
{/if}
<p class="hint">Drag to pan, use + / − to zoom. Select a circle for details.</p>
{:else}
<MooreaMap
Expand All @@ -383,6 +417,12 @@
font: inherit;
z-index: 0;
}
.defs {
position: absolute;
width: 0;
height: 0;
overflow: hidden;
}
.hint {
margin: 6px 0 0;
font-size: 0.78rem;
Expand Down
61 changes: 50 additions & 11 deletions src/lib/components/MooreaMap.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import Tip, { type TipState } from './charts/Tip.svelte';
import { registerCsv } from './charts/csv';
import { KEYS_HINT, markAt, markKeys, pointerIn } from './charts/marks';
import { directedPoints, lineWidth, reversed, shiftFor } from './lineGeometry';

let {
points,
Expand Down Expand Up @@ -116,7 +117,28 @@
});

const lineMax = $derived(Math.max(1e-9, ...lines.map((l) => l.value ?? 1)));
const lineW = (v: number | undefined) => 1.5 + 6 * Math.sqrt((v ?? 1) / lineMax);
// Direction arrows (#182): one marker per line colour, in the middle of each line.
const uid = $props.id();
const colours = $derived([...new Set(lines.map((l) => l.color ?? 'var(--series-1)'))]);
const drawn = $derived.by(() => {
const back = reversed(lines);
return lines.map((l, i) => {
const w = lineWidth(l.value, lineMax);
const pts = directedPoints(
px(l.from.lon),
py(l.from.lat),
px(l.to.lon),
py(l.to.lat),
back[i] ? shiftFor(w) : 0
);
return {
line: l,
w,
points: pts.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(' '),
arrow: colours.indexOf(l.color ?? 'var(--series-1)')
};
});
});

let tip = $state<TipState | null>(null);
function showLine(at: { x: number; y: number }, l: MapLine) {
Expand Down Expand Up @@ -165,19 +187,36 @@
>
<rect {width} height={h} fill="var(--accent-wash)" rx="10" />
<path d={path} fill="var(--surface)" stroke="var(--axis)" stroke-width="1" />
{#each lines as l, i (l.id)}
<line
x1={px(l.from.lon)}
y1={py(l.from.lat)}
x2={px(l.to.lon)}
y2={py(l.to.lat)}
stroke={l.color ?? 'var(--series-1)'}
stroke-width={lineW(l.value)}
{#if lines.length}
<defs>
{#each colours as c, i (c)}
<marker
id={`${uid}-arrow-${i}`}
viewBox="0 0 10 10"
refX="5"
refY="5"
markerWidth="16"
markerHeight="16"
markerUnits="userSpaceOnUse"
orient="auto"
>
<path d="M0,0 L10,5 L0,10 z" fill={c} stroke="var(--surface)" stroke-width="1" />
</marker>
{/each}
</defs>
{/if}
{#each drawn as d, i (d.line.id)}
<polyline
points={d.points}
fill="none"
stroke={d.line.color ?? 'var(--series-1)'}
stroke-width={d.w}
stroke-linecap="round"
stroke-opacity="0.7"
stroke-opacity="0.75"
marker-mid={`url(#${uid}-arrow-${d.arrow})`}
role="presentation"
data-mark={i}
onpointermove={(e) => showLine(pointerIn(e), l)}
onpointermove={(e) => showLine(pointerIn(e), d.line)}
/>
{/each}
{#each sorted as p, i (p.id)}
Expand Down
42 changes: 42 additions & 0 deletions src/lib/components/lineGeometry.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest';
import { directedPoints, reversed, shiftFor } from './lineGeometry';

const A = { lat: -17.5, lon: -149.9 };
const B = { lat: -17.6, lon: -149.8 };
const C = { lat: -17.55, lon: -149.75 };

describe('reversed', () => {
it('flags only lines whose opposite direction is drawn too', () => {
expect(
reversed([
{ from: A, to: B },
{ from: B, to: A },
{ from: A, to: C }
])
).toEqual([true, true, false]);
});
});

describe('directedPoints', () => {
it('puts the arrow point 60% of the way along an unshifted line', () => {
expect(directedPoints(0, 0, 10, 0, 0)).toEqual([
[0, 0],
[6, 0],
[10, 0]
]);
});

it('shifts the two directions of a pair to opposite sides', () => {
const there = directedPoints(0, 0, 10, 0, 3);
const back = directedPoints(10, 0, 0, 0, 3);
expect(there[0][1]).toBe(3);
expect(back[0][1]).toBe(-3);
// Their arrows land at different places along the line.
expect(there[1][0]).not.toBe(back[1][0]);
});

it('separates lines by more than their width', () => {
const w = 6;
expect(2 * shiftFor(w)).toBeGreaterThan(w);
});
});
49 changes: 49 additions & 0 deletions src/lib/components/lineGeometry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* Directed move lines (#182): shared by MooreaMap (SVG) and InteractiveMap (Leaflet).
*
* A line is drawn as three points (start, arrow point, end) so an SVG `marker-mid` arrow sits
* 60% of the way along, clear of the circles at either end; the arrows of A → B and B → A then
* land at different places instead of side by side. When the reverse move is also drawn, both lines
* shift sideways to the right of their direction of travel, so A → B and B → A sit side by side
* instead of on top of each other.
*/

interface Ends {
from: { lat: number; lon: number };
to: { lat: number; lon: number };
}

const key = (a: { lat: number; lon: number }, b: { lat: number; lon: number }) =>
`${a.lat},${a.lon}|${b.lat},${b.lon}`;

/** For each line, whether a line in the opposite direction is drawn too. */
export function reversed(lines: Ends[]): boolean[] {
const all = new Set(lines.map((l) => key(l.from, l.to)));
return lines.map((l) => all.has(key(l.to, l.from)));
}

const ARROW_AT = 0.6;

/** Screen points of a line, shifted `shift` px to the right of travel, with its arrow point. */
export function directedPoints(
x1: number,
y1: number,
x2: number,
y2: number,
shift: number
): [number, number][] {
const len = Math.hypot(x2 - x1, y2 - y1) || 1;
// Right-hand normal in screen coordinates (y grows downwards).
const nx = (-(y2 - y1) / len) * shift;
const ny = ((x2 - x1) / len) * shift;
const a: [number, number] = [x1 + nx, y1 + ny];
const b: [number, number] = [x2 + nx, y2 + ny];
return [a, [a[0] + (b[0] - a[0]) * ARROW_AT, a[1] + (b[1] - a[1]) * ARROW_AT], b];
}

/** Line width in px for a value, relative to the largest (shared by both maps). */
export const lineWidth = (value: number | undefined, max: number) =>
1.5 + 6 * Math.sqrt((value ?? 1) / Math.max(1e-9, max));

/** Sideways shift for a line of this width when its reverse is drawn too. */
export const shiftFor = (width: number) => width / 2 + 4;
21 changes: 10 additions & 11 deletions src/routes/recaptures/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,22 +40,21 @@ export const load: PageServerLoad = () =>
const k = Math.cos((sa.lat * Math.PI) / 180);
return Math.hypot((sa.lat - sb.lat) * 110.574, (sa.lon - sb.lon) * 111.32 * k);
};
// Moves drawn on the map (#173): one line per nursery pair and species, both directions
// pooled. Sharks with identity conflicts are left out.
// Moves drawn on the map (#173). Sharks with identity conflicts are left out.
const conflicts = new Set(d.individuals.filter((i) => i.conflict).map((i) => i.id));
const place = (id: string | null) => {
const s = id ? d.siteById.get(id) : null;
return s?.lat != null && s.lon != null ? { lat: s.lat, lon: s.lon } : null;
};
const moveLines = (['Cm', 'Na'] as const).map((sp) => {
const byPair = new Map<string, { a: string; b: string; ab: number; ba: number }>();
// One line per direction (#182): A → B and B → A are drawn side by side.
const byPair = new Map<string, { a: string; b: string; n: number }>();
for (const p of moved) {
if (p.species !== sp || conflicts.has(p.id)) continue;
const [a, b] = [p.a.siteId!, p.b.siteId!].sort();
const e = byPair.get(`${a}|${b}`) ?? { a, b, ab: 0, ba: 0 };
if (p.a.siteId === a) e.ab++;
else e.ba++;
byPair.set(`${a}|${b}`, e);
const k = `${p.a.siteId}|${p.b.siteId}`;
const e = byPair.get(k) ?? { a: p.a.siteId!, b: p.b.siteId!, n: 0 };
e.n++;
byPair.set(k, e);
}
return {
species: sp,
Expand All @@ -67,11 +66,11 @@ export const load: PageServerLoad = () =>
return [
{
id: `${sp}-${e.a}-${e.b}`,
label: `${na} ↔ ${nb}`,
label: `${na} → ${nb}`,
from,
to,
value: e.ab + e.ba,
sub: `${na} → ${nb}: ${e.ab} · ${nb} → ${na}: ${e.ba} · ${round(dist(e.a, e.b), 1)} km`
value: e.n,
sub: `${e.n} move${e.n === 1 ? '' : 's'} · ${round(dist(e.a, e.b), 1)} km`
}
];
})
Expand Down
2 changes: 1 addition & 1 deletion src/routes/recaptures/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@
<ChartCard
title="Moves between nurseries on the map"
papers={['bouyoucos2020homerange']}
subtitle="Lines join the nurseries where a shark was caught one time and the next, both directions pooled; thicker is more moves. Grey circles: recaptures at the same nursery. Each shark's own page can play its moves one by one."
subtitle="Lines join the nurseries where a shark was caught one time and the next; arrows show the direction and thicker is more moves. Moves both ways between two nurseries are drawn side by side. Grey circles: recaptures at the same nursery. Each shark's own page can play its moves one by one."
note={`Lines join capture sites; they are not the route a shark swam. A shark can pass other nurseries, or move and come back, between two captures.${data.conflictsLeftOut ? ` ${num(data.conflictsLeftOut)} moves by sharks with conflicting records are left out.` : ''}`}
>
<InteractiveMap
Expand Down
2 changes: 1 addition & 1 deletion src/routes/sharks/[id]/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
<ChartCard
title="Where it was caught"
subtitle={data.moves.length
? 'Circle size = number of captures. Lines join consecutive captures at different nurseries (not the route swum). Play steps through the captures in order.'
? 'Circle size = number of captures. Arrows join consecutive captures at different nurseries (not the route swum). Play steps through the captures in order.'
: 'Circle size = number of captures'}
>
{#if data.moves.length}
Expand Down
Loading