From 06b08cd9d5fd4dc7a47465e22029513281870cc8 Mon Sep 17 00:00:00 2001 From: Maurice Date: Sat, 28 Nov 2026 23:48:47 +0100 Subject: [PATCH] fix(atlas): name the globe hook dependencies, cover the mesh routes The second run of the globe Atlas was red on: - Client lint: the engine getter is a stable callback now, so the hooks that call it name it (and the refs and setters they read); an unused navigate and a seven parameter label helper are gone. - Atlas coverage: the mesh controller and the people and flights routes get unit tests, an unused region name helper is removed. - The French "Atlas" is marked as the same word, index.css is back at its length, the server people service is formatted, and the baselines drop the deleted AtlasPage and follow the lower counts. --- client/scripts/eslint-baseline.json | 6 +- client/scripts/strict-baseline.json | 1 - .../src/components/AtlasGlobe/globeLabels.ts | 10 +- client/src/index.css | 4 +- .../src/mobile/screens/atlas/MAtlasGlobe.tsx | 3 +- client/src/pages/atlas/useAtlasGlobe.ts | 62 ++++---- server/src/nest/atlas/atlas-geo.ts | 6 - server/src/nest/atlas/atlas-people.service.ts | 4 +- .../unit/nest/atlas-mesh.controller.test.ts | 136 ++++++++++++++++++ .../tests/unit/nest/atlas.controller.test.ts | 29 +++- shared/src/i18n/fr/atlas.ts | 2 +- 11 files changed, 211 insertions(+), 52 deletions(-) create mode 100644 server/tests/unit/nest/atlas-mesh.controller.test.ts diff --git a/client/scripts/eslint-baseline.json b/client/scripts/eslint-baseline.json index 343fc5c6d..c5a5176b1 100644 --- a/client/scripts/eslint-baseline.json +++ b/client/scripts/eslint-baseline.json @@ -3,13 +3,13 @@ "@typescript-eslint/no-non-null-assertion": 345, "@typescript-eslint/no-misused-promises": 812, "no-console": 85, - "complexity": 216, + "complexity": 215, "@typescript-eslint/no-explicit-any": 114, "trek/no-swallowed-catch": 124, "max-params": 31, "trek/store-without-selector": 65, - "react-hooks/refs": 533, - "react-hooks/set-state-in-effect": 189, + "react-hooks/refs": 522, + "react-hooks/set-state-in-effect": 188, "@typescript-eslint/no-floating-promises": 162, "react-hooks/exhaustive-deps": 113, "@typescript-eslint/no-unused-vars": 101, diff --git a/client/scripts/strict-baseline.json b/client/scripts/strict-baseline.json index 63a5e4f89..4e985d1dd 100644 --- a/client/scripts/strict-baseline.json +++ b/client/scripts/strict-baseline.json @@ -110,7 +110,6 @@ "src/mobile/screens/trip/sheets/MReservationSheet.tsx": 1, "src/mobile/screens/trip/tabs/transportsModel.ts": 1, "src/mobile/screens/vacay/MVacaySettingsSheet.tsx": 1, - "src/pages/AtlasPage.tsx": 6, "src/pages/FilesPage.tsx": 1, "src/pages/JourneyDetailPage.tsx": 1, "src/pages/LoginPage.tsx": 1, diff --git a/client/src/components/AtlasGlobe/globeLabels.ts b/client/src/components/AtlasGlobe/globeLabels.ts index 6b78ec34b..63b20f6c4 100644 --- a/client/src/components/AtlasGlobe/globeLabels.ts +++ b/client/src/components/AtlasGlobe/globeLabels.ts @@ -46,14 +46,12 @@ export function placeLabels( const m = engine.manifest; if (!m) return; const zoom = engine.zoom; - const { width, height } = engine.vp; + const { width } = engine.vp; const cands: Candidate[] = []; - const minArea = minAreaFor(zoom); - const regionA = engine.regionAlpha; const regionsOn = zoom >= (width < NARROW_WIDTH ? REGION_LABEL_ZOOM_PHONE : REGION_LABEL_ZOOM_WIDE); const named = regionsOn ? regionCandidates(engine, cands) : new Set(); - countryCandidates(engine, cands, named, minArea, regionA, labelFor, labelRegionsOf); + countryCandidates(engine, cands, named, labelFor, labelRegionsOf); cands.sort((a, b) => b.rank - a.rank); let regionCount = 0; @@ -132,14 +130,14 @@ function countryCandidates( engine: GlobeEngine, cands: Candidate[], named: Set, - minArea: number, - regionA: number, labelFor: (a2: string) => string | null, labelRegionsOf?: (a2: string) => boolean ): void { const m = engine.manifest; if (!m) return; const { width, height } = engine.vp; + const minArea = minAreaFor(engine.zoom); + const regionA = engine.regionAlpha; for (const c of m.countries) { if (!c.a2 || !c.anchor || named.has(c.a2)) continue; const mine = labelRegionsOf ? labelRegionsOf(c.a2) : false; diff --git a/client/src/index.css b/client/src/index.css index 010354e9d..b7be17add 100644 --- a/client/src/index.css +++ b/client/src/index.css @@ -356,9 +356,7 @@ input, textarea, select { transform: translateX(-2px); } -/* Global focus-visible ring — konsistent überall. Containers that only take the - focus from code (a dialog panel with tabindex="-1") never draw it: the ring and - its 4px radius would sit on the whole panel and square off its corners. */ +/* Global focus-visible ring, not on panels focused from code (tabindex="-1"). */ :focus-visible:not([tabindex="-1"]) { outline: 2px solid var(--accent); outline-offset: 2px; diff --git a/client/src/mobile/screens/atlas/MAtlasGlobe.tsx b/client/src/mobile/screens/atlas/MAtlasGlobe.tsx index 55c9df159..dcc54ff98 100644 --- a/client/src/mobile/screens/atlas/MAtlasGlobe.tsx +++ b/client/src/mobile/screens/atlas/MAtlasGlobe.tsx @@ -1,6 +1,6 @@ import { Globe2, Layers, X } from 'lucide-react'; import React from 'react'; -import { useNavigate, useSearchParams } from 'react-router'; +import { useSearchParams } from 'react-router'; import AtlasGlobe, { type AtlasGlobeHandle } from '../../../components/AtlasGlobe/AtlasGlobe'; import type { GlobeEngine } from '../../../components/AtlasGlobe/GlobeEngine'; import GlobePins, { type GlobePinsHandle } from '../../../components/AtlasGlobe/GlobePins'; @@ -31,7 +31,6 @@ export default function MAtlasGlobe(): React.ReactElement { const skyRef = React.useRef(null); const s = useAtlasGlobe({ globeRef, skyRef }); const stats = useGlobeStats(s); - const navigate = useNavigate(); const [layersOpen, setLayersOpen] = React.useState(false); const pinsRef = React.useRef(null); // The dock's search button hands over with ?search=1, as on every screen: take diff --git a/client/src/pages/atlas/useAtlasGlobe.ts b/client/src/pages/atlas/useAtlasGlobe.ts index 8d1c23fee..eff134ddd 100644 --- a/client/src/pages/atlas/useAtlasGlobe.ts +++ b/client/src/pages/atlas/useAtlasGlobe.ts @@ -116,7 +116,7 @@ export function useAtlasGlobe({ globeRef, skyRef }: AtlasGlobeRefs) { setRegions(regs as VisitedRegionMap); setBucket(items as BucketItem[]); setFlights(fl); - }, []); + }, [setBucket]); // Flight arcs, grouped by how often a route was flown so busy routes draw thicker (#1369). const arcLayers = useMemo(() => { @@ -134,7 +134,7 @@ export function useAtlasGlobe({ globeRef, skyRef }: AtlasGlobeRefs) { useEffect(() => { if (!manifest) return; globeRef.current?.engine?.setArcs(showFlights ? arcLayers : []); - }, [arcLayers, showFlights, manifest]); + }, [arcLayers, showFlights, manifest, globeRef]); // The first read, tried again with growing pauses before it counts as failed: // a server that restarts or a connection that drops for a moment answers @@ -238,22 +238,25 @@ export function useAtlasGlobe({ globeRef, skyRef }: AtlasGlobeRefs) { const planned = data.countries.filter((c) => countryStatus(c) !== 'visited').map((c) => c.code); const wished = bucket.map((b) => b.country_code).filter((c): c is string => !!c && c.length === 2); e.prefetchRegions([...visited, ...planned, ...wished]); - }, [manifest, data, bucket]); + }, [engine, manifest, data, bucket]); - const selectCountry = useCallback((a2: string, fly = true) => { - const e = engine(); - const m = e?.manifest; - if (!e || !m) return; - const index = m.countries.findIndex((c) => c.a2 === a2); - if (index < 0) return; - setSelection({ kind: 'country', a2, index }); - e.setSelected(index, null); - if (fly) { - const c = m.countries[index]; - if (c.anchor) e.flyTo(c.anchor[0], c.anchor[1], Math.max(e.zoom, 1.15)); - } - void e.loadRegionIndex(a2).then(() => setRegionTick((n) => n + 1)); - }, []); + const selectCountry = useCallback( + (a2: string, fly = true) => { + const e = engine(); + const m = e?.manifest; + if (!e || !m) return; + const index = m.countries.findIndex((c) => c.a2 === a2); + if (index < 0) return; + setSelection({ kind: 'country', a2, index }); + e.setSelected(index, null); + if (fly) { + const c = m.countries[index]; + if (c.anchor) e.flyTo(c.anchor[0], c.anchor[1], Math.max(e.zoom, 1.15)); + } + void e.loadRegionIndex(a2).then(() => setRegionTick((n) => n + 1)); + }, + [engine] + ); // ---- the classic Atlas dialogs: choose / unmark / bucket (shared with the phone) and the country detail const [confirmAction, setConfirmAction] = useState(null); @@ -317,7 +320,7 @@ export function useAtlasGlobe({ globeRef, skyRef }: AtlasGlobeRefs) { selectCountry(hit.a2, false); openCountry(hit.a2); }, - [selectCountry, openCountry, regions, resolveName] + [engine, selectCountry, openCountry, regions, resolveName] ); /** From the detail of a country marked by hand: ask to take the mark off. */ @@ -333,7 +336,7 @@ export function useAtlasGlobe({ globeRef, skyRef }: AtlasGlobeRefs) { setDetail(null); setSelection(null); engine()?.setSelected(-1, null); - }, []); + }, [engine]); const executeConfirmAction = useCallback(async () => { const a = confirmAction; @@ -370,7 +373,7 @@ export function useAtlasGlobe({ globeRef, skyRef }: AtlasGlobeRefs) { if (i >= 0 && anchor) e.startInk(i, anchor[0], anchor[1]); skyRef.current?.shootingStar(); } - }, [data]); + }, [data, engine, skyRef]); const countryRow = useMemo(() => { if (selection?.kind !== 'country') return null; @@ -488,7 +491,7 @@ export function useAtlasGlobe({ globeRef, skyRef }: AtlasGlobeRefs) { setRegionTick((n) => n + 1); }); }, - [selectCountry, openCountry] + [engine, selectCountry, openCountry] ); // Places from the geocoder under the countries and regions (#1115): the globe flies @@ -514,7 +517,7 @@ export function useAtlasGlobe({ globeRef, skyRef }: AtlasGlobeRefs) { countryName: resolveName(info.country_code), }); }, - [regions, resolveName, selectCountry] + [engine, regions, resolveName, selectCountry] ); // Badges are rules over the data on screen; nothing is stored (shared/src/atlas/atlas-badges.ts). @@ -585,10 +588,13 @@ export function useAtlasGlobe({ globeRef, skyRef }: AtlasGlobeRefs) { return [...people, mine].sort((a, b) => b.countries - a.countries || b.continents - a.continents); }, [people, me, totals, flights]); - const flyToPoint = useCallback((lon: number, lat: number) => { - setPassportOpen(false); - engine()?.flyTo(lon, lat, 6); - }, []); + const flyToPoint = useCallback( + (lon: number, lat: number) => { + setPassportOpen(false); + engine()?.flyTo(lon, lat, 6); + }, + [engine] + ); const pins = useMemo( () => @@ -605,8 +611,8 @@ export function useAtlasGlobe({ globeRef, skyRef }: AtlasGlobeRefs) { [bucket, openPassport] ); - const zoomIn = useCallback(() => engine()?.zoomBy(1.6), []); - const zoomOut = useCallback(() => engine()?.zoomBy(1 / 1.6), []); + const zoomIn = useCallback(() => engine()?.zoomBy(1.6), [engine]); + const zoomOut = useCallback(() => engine()?.zoomBy(1 / 1.6), [engine]); return { t, diff --git a/server/src/nest/atlas/atlas-geo.ts b/server/src/nest/atlas/atlas-geo.ts index e7948882a..75e611eb5 100644 --- a/server/src/nest/atlas/atlas-geo.ts +++ b/server/src/nest/atlas/atlas-geo.ts @@ -593,12 +593,6 @@ function parseRegionFeatures(cc: string): RegionFeature[] { return out; } -/** A bundled admin-1 region's name by its ISO code (`DE-BY`), or null when the bundle has none. */ -export function regionNameByCode(countryCode: string, regionCode: string): string | null { - const code = regionCode.toUpperCase(); - return getRegionFeatures(countryCode).find((f) => f.code.toUpperCase() === code)?.name ?? null; -} - // Resolve (lat,lng) to a bundled admin1 region within the given country, smallest // matching-part-first (mirroring getCountryFromCoords' candidate ranking) so a point near // a shared border prefers the tighter-fitting candidate. Returns null when the country has diff --git a/server/src/nest/atlas/atlas-people.service.ts b/server/src/nest/atlas/atlas-people.service.ts index 026cd9f9b..55e831169 100644 --- a/server/src/nest/atlas/atlas-people.service.ts +++ b/server/src/nest/atlas/atlas-people.service.ts @@ -70,7 +70,9 @@ export class AtlasPeopleService { if (!(await this.compareEnabled())) return []; const asked = [...new Set(ids)].slice(0, ATLAS_PEOPLE_MAX); // Each traveller is read on their own; the order of the answer is the order asked. - const answers = await Promise.all(asked.map(async (id) => ((await this.isHidden(id)) ? null : await this.person(id)))); + const answers = await Promise.all( + asked.map(async (id) => ((await this.isHidden(id)) ? null : await this.person(id))), + ); return answers.filter((p): p is AtlasPerson => p !== null); } diff --git a/server/tests/unit/nest/atlas-mesh.controller.test.ts b/server/tests/unit/nest/atlas-mesh.controller.test.ts new file mode 100644 index 000000000..3dd8369c2 --- /dev/null +++ b/server/tests/unit/nest/atlas-mesh.controller.test.ts @@ -0,0 +1,136 @@ +import { AtlasMeshController } from '../../../src/nest/atlas/atlas-mesh.controller'; +import { NotFoundException } from '@nestjs/common'; + +import type { Response } from 'express'; +import fs from 'node:fs'; +import { PassThrough, Readable } from 'node:stream'; +import zlib from 'node:zlib'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +// The geometry files are built at install time (scripts/build-atlas-mesh.mjs) and +// not committed, so the file system is stubbed: the controller's own job is which +// file it names, which headers it sets and how it sends the bytes. + +/** A writable stand-in for express's Response that records what the controller does with it. */ +class FakeResponse extends PassThrough { + headers: Record = {}; + sent: { name: string; options: Record } | null = null; + statusCode = 200; + headersSent = false; + body = ''; + + constructor() { + super(); + this.on('data', (chunk: Buffer) => { + this.headersSent = true; + this.body += chunk.toString('utf8'); + }); + } + + setHeader(name: string, value: string): this { + this.headers[name] = value; + return this; + } + + sendFile(name: string, options: Record): void { + this.sent = { name, options }; + } + + status(code: number): this { + this.statusCode = code; + return this; + } +} + +const FILE = 'world-110m.0123456789ab.json'; +const asRes = (r: FakeResponse) => r as unknown as Response; +const finished = (r: FakeResponse) => + new Promise((resolve) => { + r.on('finish', resolve); + r.on('close', resolve); + }); + +afterEach(() => vi.restoreAllMocks()); + +describe('AtlasMeshController', () => { + const controller = new AtlasMeshController(); + + it('ATLAS-MESH-001: sends the manifest uncached when it is built', () => { + vi.spyOn(fs, 'existsSync').mockReturnValue(true); + const res = new FakeResponse(); + + controller.manifest(asRes(res)); + + expect(res.headers['Cache-Control']).toBe('no-cache'); + expect(res.sent?.name).toBe('manifest.json'); + }); + + it('ATLAS-MESH-002: answers 404 while the geometry is not built', () => { + vi.spyOn(fs, 'existsSync').mockReturnValue(false); + + expect(() => controller.manifest(asRes(new FakeResponse()))).toThrow(NotFoundException); + }); + + it('ATLAS-MESH-003: refuses any file name the build script does not write, before touching the disk', () => { + const exists = vi.spyOn(fs, 'existsSync').mockReturnValue(true); + + for (const bad of ['../manifest.json', 'world.json', 'world-110m.0123456789ab.json.br', 'a/b.0123456789ab.json']) { + expect(() => controller.world(bad, 'br', asRes(new FakeResponse()))).toThrow(NotFoundException); + } + expect(exists).not.toHaveBeenCalled(); + }); + + it('ATLAS-MESH-004: answers 404 for a well-formed name with no file behind it', () => { + vi.spyOn(fs, 'existsSync').mockReturnValue(false); + + expect(() => controller.regions('DE.0123456789ab.json', 'br', asRes(new FakeResponse()))).toThrow( + NotFoundException, + ); + }); + + it('ATLAS-MESH-005: sends the stored Brotli file as it is to a client that accepts br, cached for a year', () => { + vi.spyOn(fs, 'existsSync').mockReturnValue(true); + const res = new FakeResponse(); + + controller.regions('DE.0123456789ab.json', 'gzip, deflate, br', asRes(res)); + + expect(res.headers['Content-Encoding']).toBe('br'); + expect(res.headers['Cache-Control']).toBe('public, max-age=31536000, immutable'); + expect(res.headers.Vary).toBe('Accept-Encoding'); + expect(res.sent?.name).toBe('DE.0123456789ab.json.br'); + expect(String(res.sent?.options.root)).toMatch(/atlas-mesh[\\/]regions$/); + }); + + it('ATLAS-MESH-006: decompresses as a stream for a client without br', async () => { + const json = JSON.stringify({ type: 'Topology', objects: {} }); + vi.spyOn(fs, 'existsSync').mockReturnValue(true); + vi.spyOn(fs, 'createReadStream').mockReturnValue( + Readable.from([zlib.brotliCompressSync(Buffer.from(json))]) as unknown as fs.ReadStream, + ); + const res = new FakeResponse(); + const done = finished(res); + + controller.world(FILE, 'gzip', asRes(res)); + await done; + + expect(res.headers['Content-Encoding']).toBeUndefined(); + expect(res.headers['Content-Type']).toBe('application/json; charset=utf-8'); + expect(res.sent).toBeNull(); + expect(res.body).toBe(json); + }); + + it('ATLAS-MESH-007: answers 500 when the stored file cannot be read before anything was sent', async () => { + vi.spyOn(fs, 'existsSync').mockReturnValue(true); + vi.spyOn(fs, 'createReadStream').mockReturnValue( + Readable.from([Buffer.from('not brotli at all')]) as unknown as fs.ReadStream, + ); + const res = new FakeResponse(); + const done = finished(res); + + controller.world(FILE, undefined, asRes(res)); + await done; + + expect(res.statusCode).toBe(500); + expect(res.body).toBe(''); + }); +}); diff --git a/server/tests/unit/nest/atlas.controller.test.ts b/server/tests/unit/nest/atlas.controller.test.ts index f7d62c5a9..a2b522b6b 100644 --- a/server/tests/unit/nest/atlas.controller.test.ts +++ b/server/tests/unit/nest/atlas.controller.test.ts @@ -1,5 +1,5 @@ import type { AtlasFlightsService } from '../../../src/nest/atlas/atlas-flights.service'; -import type { AtlasPeopleService } from '../../../src/nest/atlas/atlas-people.service'; +import { ATLAS_PEOPLE_MAX, type AtlasPeopleService } from '../../../src/nest/atlas/atlas-people.service'; import type { AtlasWritesService } from '../../../src/nest/atlas/atlas-writes.service'; import { AtlasController } from '../../../src/nest/atlas/atlas.controller'; import { BucketItemExistsError } from '../../../src/nest/atlas/atlas.service'; @@ -55,6 +55,33 @@ describe('AtlasController (parity with the legacy /api/addons/atlas route)', () expect(stats).toHaveBeenCalledWith(8); }); + describe('GET /people', () => { + it('asks for the well-formed ids only, as numbers, capped at the comparison maximum', async () => { + const people = vi.fn().mockResolvedValue([{ id: 2 }]); + const many = Array.from({ length: ATLAS_PEOPLE_MAX + 5 }, (_, i) => String(i + 1)).join(','); + + expect(await makeController({ people } as never).people('2,abc,,-3,1.5,12345678901')).toEqual({ + people: [{ id: 2 }], + }); + expect(people).toHaveBeenLastCalledWith([2]); + + await makeController({ people } as never).people(many); + expect(people.mock.calls[1][0]).toHaveLength(ATLAS_PEOPLE_MAX); + }); + + it('asks for nobody without ids', async () => { + const people = vi.fn().mockResolvedValue([]); + expect(await makeController({ people } as never).people(undefined)).toEqual({ people: [] }); + expect(people).toHaveBeenCalledWith([]); + }); + }); + + it('GET /flights hands back the flight map of the user', async () => { + const flights = vi.fn().mockResolvedValue({ routes: [] }); + expect(await makeController({ flights } as never).flights(user)).toEqual({ routes: [] }); + expect(flights).toHaveBeenCalledWith(8); + }); + // The region routes read the committed per-country files (server/assets/atlas/admin1). type RegionFeatures = { features: { properties: { iso_a2: string } }[] }; const countriesOf = (geo: RegionFeatures) => new Set(geo.features.map((f) => f.properties.iso_a2)); diff --git a/shared/src/i18n/fr/atlas.ts b/shared/src/i18n/fr/atlas.ts index b767b66dc..1ed5ea100 100644 --- a/shared/src/i18n/fr/atlas.ts +++ b/shared/src/i18n/fr/atlas.ts @@ -177,7 +177,7 @@ const atlas: TranslationStrings = { 'atlas.badgeTier.gold': 'Or', 'atlas.badgeTier.silver': 'Argent', 'atlas.globe.howTo': 'Comment l’obtenir', - 'atlas.globe.hub': 'Atlas', + 'atlas.globe.hub': 'Atlas', // same-as-en 'atlas.globe.newBadge': 'Nouveau badge', 'atlas.globe.progress': 'Progression', 'atlas.globe.worldShare': '{share} % du monde',