diff --git a/e2e/map-keyboard.spec.ts b/e2e/map-keyboard.spec.ts index 72d8764..680e080 100644 --- a/e2e/map-keyboard.spec.ts +++ b/e2e/map-keyboard.spec.ts @@ -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'))! + ); +}); diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index 648696d..96e80b7 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -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, @@ -165,6 +166,8 @@ } let map = $state.raw(); + let zoom = $state(0); + const uid = $props.id(); let leaflet: typeof import('leaflet') | undefined; let drawn: { groups: { key: string; group: import('leaflet').LayerGroup }[]; @@ -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 () => { @@ -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)) @@ -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[`${g.name}`] = group; @@ -361,6 +375,26 @@ aria-label={label} style={`${style}; height: ${height}px`} > + {#if lineLayers.length} + + {/if}

Drag to pan, use + / − to zoom. Select a circle for details.

{:else} 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(null); function showLine(at: { x: number; y: number }, l: MapLine) { @@ -165,19 +187,36 @@ > - {#each lines as l, i (l.id)} - + {#each colours as c, i (c)} + + + + {/each} + + {/if} + {#each drawn as d, i (d.line.id)} + showLine(pointerIn(e), l)} + onpointermove={(e) => showLine(pointerIn(e), d.line)} /> {/each} {#each sorted as p, i (p.id)} diff --git a/src/lib/components/lineGeometry.test.ts b/src/lib/components/lineGeometry.test.ts new file mode 100644 index 0000000..53af6d3 --- /dev/null +++ b/src/lib/components/lineGeometry.test.ts @@ -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); + }); +}); diff --git a/src/lib/components/lineGeometry.ts b/src/lib/components/lineGeometry.ts new file mode 100644 index 0000000..413b9a5 --- /dev/null +++ b/src/lib/components/lineGeometry.ts @@ -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; diff --git a/src/routes/recaptures/+page.server.ts b/src/routes/recaptures/+page.server.ts index 889b204..b4337b9 100644 --- a/src/routes/recaptures/+page.server.ts +++ b/src/routes/recaptures/+page.server.ts @@ -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(); + // One line per direction (#182): A → B and B → A are drawn side by side. + const byPair = new Map(); 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, @@ -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` } ]; }) diff --git a/src/routes/recaptures/+page.svelte b/src/routes/recaptures/+page.svelte index 0f6afce..ba938dd 100644 --- a/src/routes/recaptures/+page.svelte +++ b/src/routes/recaptures/+page.svelte @@ -100,7 +100,7 @@ {#if data.moves.length}