diff --git a/AGENTS.md b/AGENTS.md index 469dfcd..9edfdef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -238,3 +238,4 @@ Questions for the lab go to Dr Jodie Rummer (`@JodieRummer`) on GitHub: label th - Seasonal comparisons must report dates from their eligible sets, not an assumed October–February window (2020–21 starts in September). ISPF's Moorea hotel-room sales are a visitor proxy, not a count of people on the water. - Leaflet treats string tooltips as HTML. Pass a DOM element populated with `textContent` for workbook-derived point and move labels, including when rebuilding overlays. - Leaflet polylines are pointer-only by default. Keep move paths keyboard-focusable, with focus tooltips and Enter/Space popup handlers; the SVG fallback uses the shared chart `markKeys` contract. +- Leaflet hides a popup body (`visibility: hidden`) while it lays the popup out, so a `focus()` straight from `popupopen` is ignored; `InteractiveMap` retries for a few frames. A popup without a link still focuses its body (not the close button, which is also an ``). diff --git a/e2e/map-keyboard.spec.ts b/e2e/map-keyboard.spec.ts index 680e080..cba1873 100644 --- a/e2e/map-keyboard.spec.ts +++ b/e2e/map-keyboard.spec.ts @@ -73,3 +73,152 @@ test('directed move markers and keyboard controls survive a zoom redraw', async (await line.getAttribute('aria-label'))! ); }); + +test('nursery circles are keyboard reachable, support popup links and survive season redraws (#185)', async ({ + page +}) => { + await page.route(/server\.arcgisonline\.com|tile\.openstreetmap\.org/, (route) => route.abort()); + await page.goto('/nurseries'); + const map = page.getByRole('region', { + name: "Map of Mo'orea's shark nurseries" + }); + const circle = map.locator('.ps-layer[role="button"]').first(); + await expect(circle).toBeVisible(); + const label = await circle.getAttribute('aria-label'); + expect(label).toBeTruthy(); + // Focus visibly identifies the selected circle and opens the tooltip + await circle.focus(); + await expect(map.locator('.leaflet-tooltip').last()).toBeVisible(); + // Press Enter to open details popup; focus moves to the reachable link + await circle.press('Enter'); + const popup = map.locator('.leaflet-popup-content'); + await expect(popup).toBeVisible(); + const link = popup.locator('a'); + await expect(link).toBeVisible(); + await expect(link).toBeFocused(); + // Escape dismisses details without trapping focus and restores focus to circle + await page.keyboard.press('Escape'); + await expect(popup).toHaveCount(0); + await expect(circle).toBeFocused(); + // Space key also activates + await circle.press('Space'); + await expect(popup).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(popup).toHaveCount(0); + await expect(circle).toBeFocused(); + // Controls survive season redraws + const slider = page.getByRole('slider', { name: /season/i }); + await expect(slider).toBeVisible(); + await slider.fill('0'); + const seasonCircle = map.locator('.ps-layer[role="button"]').first(); + await expect(seasonCircle).toBeVisible(); + await seasonCircle.focus(); + await seasonCircle.press('Enter'); + await expect(map.locator('.leaflet-popup-content')).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(map.locator('.leaflet-popup-content')).toHaveCount(0); + await expect(seasonCircle).toBeFocused(); +}); + +test('adult capture circles are keyboard reachable and survive zoom and overlay toggles (#185)', async ({ + page +}) => { + await page.emulateMedia({ reducedMotion: 'reduce' }); + await page.route(/server\.arcgisonline\.com|tile\.openstreetmap\.org/, (route) => route.abort()); + // Inject synthetic adult points so the density map renders with circle markers + await page.route('**/adults/__data.json*', async (route) => { + const response = await route.fetch(); + const body = await response.json(); + const node = body.nodes.find( + (n: { data?: unknown[] } | null) => n?.data?.[0] && 'where' in (n.data[0] as object) + ); + if (!node) { + await route.fulfill({ response, json: body }); + return; + } + const data: unknown[] = node.data; + const root = data[0] as Record; + const where = data[root.where] as Record; + const add = (v: unknown) => data.push(v) - 1; + root.n = add(1); + const point = add({ + id: add('adult-0'), + label: add('Adult blacktip “Synthetic”'), + lat: add(-17.5), + lon: add(-149.85), + sub: add('2022-01-01 · Haapiti') + }); + where.points = add([point]); + const cell = add({ + south: add(-17.51), + west: add(-149.86), + north: add(-17.5), + east: add(-149.85), + bin: add(1) + }); + where.density = add({ + n: add(20), + bandwidthKm: add(0.3), + cells: add([cell]) + }); + where.missing = add(0); + where.setAside = add([]); + await route.fulfill({ response, json: body }); + }); + await page.goto('/'); + await page + .locator('a[href="/adults"]') + .first() + .evaluate((a: HTMLAnchorElement) => a.click()); + const map = page.getByRole('region', { + name: 'Map of adult blacktip capture density' + }); + await expect(map).toBeVisible(); + const circle = map.locator('.ps-layer[role="button"]').first(); + await expect(circle).toBeVisible(); + const label = await circle.getAttribute('aria-label'); + expect(label).toContain('Adult blacktip'); + await circle.focus(); + await expect(map.locator('.leaflet-tooltip').last()).toBeVisible(); + await circle.press('Enter'); + const popupContent = map.locator('.leaflet-popup-content'); + await expect(popupContent).toContainText('Adult blacktip “Synthetic”'); + // Adult popups have no link: focus still enters the details so they are read out + await expect(popupContent).toBeFocused(); + await page.keyboard.press('Escape'); + await expect(popupContent).toHaveCount(0); + await expect(circle).toBeFocused(); + // Close button also restores focus to the circle marker when activated + await circle.press('Enter'); + await expect(popupContent).toBeVisible(); + const closeBtn = map.locator('.leaflet-popup-close-button'); + await closeBtn.focus(); + await closeBtn.press('Enter'); + await expect(popupContent).toHaveCount(0); + await expect(circle).toBeFocused(); + // Controls survive zoom redraws. The single adult capture sits under the map centre, so the + // circle keeps its `d` on zoom; the basemap tile zoom is what shows the overlay was redrawn. + const tile = map.locator('img.leaflet-tile').first(); + const tileZoom = await tile.getAttribute('src'); + await map.getByRole('button', { name: 'Zoom in', exact: true }).click(); + await expect.poll(() => tile.getAttribute('src')).not.toBe(tileZoom); + await circle.focus(); + await circle.press('Space'); + await expect(map.locator('.leaflet-popup-content')).toContainText('Adult blacktip “Synthetic”'); + await page.keyboard.press('Escape'); + await expect(map.locator('.leaflet-popup-content')).toHaveCount(0); + await expect(circle).toBeFocused(); + // Controls survive overlay toggles + const toggle = map.getByRole('checkbox', { name: /Adult captures/i }); + await expect(toggle).toBeVisible(); + await toggle.uncheck(); + await expect(circle).not.toBeVisible(); + await toggle.check(); + await expect(circle).toBeVisible(); + await circle.focus(); + await circle.press('Enter'); + await expect(map.locator('.leaflet-popup-content')).toContainText('Adult blacktip “Synthetic”'); + await page.keyboard.press('Escape'); + await expect(map.locator('.leaflet-popup-content')).toHaveCount(0); + await expect(circle).toBeFocused(); +}); diff --git a/src/lib/components/InteractiveMap.svelte b/src/lib/components/InteractiveMap.svelte index 96e80b7..5405284 100644 --- a/src/lib/components/InteractiveMap.svelte +++ b/src/lib/components/InteractiveMap.svelte @@ -116,34 +116,87 @@ } // Leaflet paths have pointer handlers but are not keyboard controls by default. - function keyboardLine(line: import('leaflet').Polyline, label: string) { - line.on('add', () => { - const path = line.getElement() as SVGElement | undefined; - if (!path) return; - path.setAttribute('tabindex', '0'); - path.setAttribute('role', 'button'); - path.setAttribute('aria-label', label); - path.onfocus = () => line.openTooltip(); - path.onblur = () => line.closeTooltip(); - path.onkeydown = (e) => { + function keyboardInteractive(layer: T, label: string): T { + const init = () => { + const el = layer.getElement() as SVGElement | undefined; + if (!el) return; + el.setAttribute('tabindex', '0'); + el.setAttribute('role', 'button'); + el.setAttribute('aria-label', label); + el.onfocus = () => layer.openTooltip(); + el.onblur = () => layer.closeTooltip(); + el.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); - if (e.key === 'Enter') line.openPopup(); + if (e.key === 'Enter') layer.openPopup(); } else if (e.key === 'Escape') { - line.closePopup(); - line.closeTooltip(); + layer.closePopup(); + layer.closeTooltip(); } }; - path.onkeyup = (e) => { + el.onkeyup = (e) => { if (e.key === ' ') { e.preventDefault(); e.stopPropagation(); - line.openPopup(); + layer.openPopup(); } }; + }; + layer.on('add', init); + if (layer.getElement()) init(); + layer.on('popupopen', (e) => { + const popupEl = (e as unknown as { popup?: import('leaflet').Popup })?.popup?.getElement(); + if (!popupEl) return; + // The close button is also an , so look inside the body only. Without a link or + // button there, focus the content so the details are still read out (adult captures). + const content = popupEl.querySelector('.leaflet-popup-content'); + let target = content?.querySelector('a[href], button') ?? null; + if (!target && content) { + content.tabIndex = -1; + target = content; + } + if (target) focusSoon(target, document.activeElement); + const dismiss = (ev: Event) => { + ev.preventDefault(); + ev.stopPropagation(); + layer.closePopup(); + (layer.getElement() as HTMLElement | undefined)?.focus(); + }; + const closeBtn = popupEl.querySelector('.leaflet-popup-close-button'); + if (closeBtn) { + closeBtn.onclick = dismiss; + closeBtn.onkeydown = (ev: KeyboardEvent) => { + if (ev.key === 'Enter' || ev.key === ' ') dismiss(ev); + }; + } + popupEl.onkeydown = (ev: KeyboardEvent) => { + if (ev.key === 'Escape') dismiss(ev); + }; }); - return line; + return layer; + } + + // Leaflet hides the popup body while it lays the popup out, so focusing it straight from + // popupopen can land while it is still visibility: hidden and be ignored. Retry for a few + // frames, but stop as soon as focus has moved somewhere else (the user tabbed or clicked). + function focusSoon(target: HTMLElement, from: Element | null) { + const attempt = (tries: number) => { + if (!target.isConnected) return; + target.focus(); + if (document.activeElement === target) return; + const active = document.activeElement; + if (active && active !== from && active !== document.body) return; + if (tries > 1) requestAnimationFrame(() => attempt(tries - 1)); + }; + attempt(30); + } + + function pointLabel(p: MapPoint, unit = valueLabel) { + const parts = [p.label]; + if (p.value != null && unit) parts.push(`${unit}: ${format(p.value)}`); + if (p.sub) parts.push(p.sub); + return parts.join(' · '); } function popup(p: MapPoint | MapLine, unit = valueLabel) { @@ -277,7 +330,7 @@ line.on('add', () => line.getElement()?.setAttribute('marker-mid', `url(#${uid}-arrow-${i})`) ); - keyboardLine(line, l.label) + keyboardInteractive(line, l.label) .bindTooltip(tooltip(l.label)) .bindPopup(() => popup(l, lineLabel)) .addTo(group); @@ -299,10 +352,11 @@ ((layer.maxRadius ?? 18) - 5) * Math.sqrt(Math.min(1, Math.max(0, p.value ?? 0) / max)) : (layer.radius ?? 5); - L.circleMarker([p.lat, p.lon], { + const marker = L.circleMarker([p.lat, p.lon], { radius: r, className: `ps-layer ps-layer-${i}${empty ? ' ps-empty' : ''}` - }) + }); + keyboardInteractive(marker, pointLabel(p)) .bindTooltip(tooltip(p.label)) .bindPopup(() => popup(p)) .addTo(group); @@ -501,6 +555,10 @@ outline: 2px solid var(--ink); outline-offset: 4px; } + .map :global(.ps-layer:focus-visible) { + outline: 2px solid var(--ink); + outline-offset: 3px; + } .map :global(.ps-line-key) { border-radius: 2px; height: 4px;